three.module.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '165';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBAIntegerFormat = 1033;
  110. const RGB_S3TC_DXT1_Format = 33776;
  111. const RGBA_S3TC_DXT1_Format = 33777;
  112. const RGBA_S3TC_DXT3_Format = 33778;
  113. const RGBA_S3TC_DXT5_Format = 33779;
  114. const RGB_PVRTC_4BPPV1_Format = 35840;
  115. const RGB_PVRTC_2BPPV1_Format = 35841;
  116. const RGBA_PVRTC_4BPPV1_Format = 35842;
  117. const RGBA_PVRTC_2BPPV1_Format = 35843;
  118. const RGB_ETC1_Format = 36196;
  119. const RGB_ETC2_Format = 37492;
  120. const RGBA_ETC2_EAC_Format = 37496;
  121. const RGBA_ASTC_4x4_Format = 37808;
  122. const RGBA_ASTC_5x4_Format = 37809;
  123. const RGBA_ASTC_5x5_Format = 37810;
  124. const RGBA_ASTC_6x5_Format = 37811;
  125. const RGBA_ASTC_6x6_Format = 37812;
  126. const RGBA_ASTC_8x5_Format = 37813;
  127. const RGBA_ASTC_8x6_Format = 37814;
  128. const RGBA_ASTC_8x8_Format = 37815;
  129. const RGBA_ASTC_10x5_Format = 37816;
  130. const RGBA_ASTC_10x6_Format = 37817;
  131. const RGBA_ASTC_10x8_Format = 37818;
  132. const RGBA_ASTC_10x10_Format = 37819;
  133. const RGBA_ASTC_12x10_Format = 37820;
  134. const RGBA_ASTC_12x12_Format = 37821;
  135. const RGBA_BPTC_Format = 36492;
  136. const RGB_BPTC_SIGNED_Format = 36494;
  137. const RGB_BPTC_UNSIGNED_Format = 36495;
  138. const RED_RGTC1_Format = 36283;
  139. const SIGNED_RED_RGTC1_Format = 36284;
  140. const RED_GREEN_RGTC2_Format = 36285;
  141. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  142. const LoopOnce = 2200;
  143. const LoopRepeat = 2201;
  144. const LoopPingPong = 2202;
  145. const InterpolateDiscrete = 2300;
  146. const InterpolateLinear = 2301;
  147. const InterpolateSmooth = 2302;
  148. const ZeroCurvatureEnding = 2400;
  149. const ZeroSlopeEnding = 2401;
  150. const WrapAroundEnding = 2402;
  151. const NormalAnimationBlendMode = 2500;
  152. const AdditiveAnimationBlendMode = 2501;
  153. const TrianglesDrawMode = 0;
  154. const TriangleStripDrawMode = 1;
  155. const TriangleFanDrawMode = 2;
  156. const BasicDepthPacking = 3200;
  157. const RGBADepthPacking = 3201;
  158. const TangentSpaceNormalMap = 0;
  159. const ObjectSpaceNormalMap = 1;
  160. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  161. const NoColorSpace = '';
  162. const SRGBColorSpace = 'srgb';
  163. const LinearSRGBColorSpace = 'srgb-linear';
  164. const DisplayP3ColorSpace = 'display-p3';
  165. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  166. const LinearTransfer = 'linear';
  167. const SRGBTransfer = 'srgb';
  168. const Rec709Primaries = 'rec709';
  169. const P3Primaries = 'p3';
  170. const ZeroStencilOp = 0;
  171. const KeepStencilOp = 7680;
  172. const ReplaceStencilOp = 7681;
  173. const IncrementStencilOp = 7682;
  174. const DecrementStencilOp = 7683;
  175. const IncrementWrapStencilOp = 34055;
  176. const DecrementWrapStencilOp = 34056;
  177. const InvertStencilOp = 5386;
  178. const NeverStencilFunc = 512;
  179. const LessStencilFunc = 513;
  180. const EqualStencilFunc = 514;
  181. const LessEqualStencilFunc = 515;
  182. const GreaterStencilFunc = 516;
  183. const NotEqualStencilFunc = 517;
  184. const GreaterEqualStencilFunc = 518;
  185. const AlwaysStencilFunc = 519;
  186. const NeverCompare = 512;
  187. const LessCompare = 513;
  188. const EqualCompare = 514;
  189. const LessEqualCompare = 515;
  190. const GreaterCompare = 516;
  191. const NotEqualCompare = 517;
  192. const GreaterEqualCompare = 518;
  193. const AlwaysCompare = 519;
  194. const StaticDrawUsage = 35044;
  195. const DynamicDrawUsage = 35048;
  196. const StreamDrawUsage = 35040;
  197. const StaticReadUsage = 35045;
  198. const DynamicReadUsage = 35049;
  199. const StreamReadUsage = 35041;
  200. const StaticCopyUsage = 35046;
  201. const DynamicCopyUsage = 35050;
  202. const StreamCopyUsage = 35042;
  203. const GLSL1 = '100';
  204. const GLSL3 = '300 es';
  205. const WebGLCoordinateSystem = 2000;
  206. const WebGPUCoordinateSystem = 2001;
  207. /**
  208. * https://github.com/mrdoob/eventdispatcher.js/
  209. */
  210. class EventDispatcher {
  211. addEventListener( type, listener ) {
  212. if ( this._listeners === undefined ) this._listeners = {};
  213. const listeners = this._listeners;
  214. if ( listeners[ type ] === undefined ) {
  215. listeners[ type ] = [];
  216. }
  217. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  218. listeners[ type ].push( listener );
  219. }
  220. }
  221. hasEventListener( type, listener ) {
  222. if ( this._listeners === undefined ) return false;
  223. const listeners = this._listeners;
  224. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  225. }
  226. removeEventListener( type, listener ) {
  227. if ( this._listeners === undefined ) return;
  228. const listeners = this._listeners;
  229. const listenerArray = listeners[ type ];
  230. if ( listenerArray !== undefined ) {
  231. const index = listenerArray.indexOf( listener );
  232. if ( index !== - 1 ) {
  233. listenerArray.splice( index, 1 );
  234. }
  235. }
  236. }
  237. dispatchEvent( event ) {
  238. if ( this._listeners === undefined ) return;
  239. const listeners = this._listeners;
  240. const listenerArray = listeners[ event.type ];
  241. if ( listenerArray !== undefined ) {
  242. event.target = this;
  243. // Make a copy, in case listeners are removed while iterating.
  244. const array = listenerArray.slice( 0 );
  245. for ( let i = 0, l = array.length; i < l; i ++ ) {
  246. array[ i ].call( this, event );
  247. }
  248. event.target = null;
  249. }
  250. }
  251. }
  252. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  253. let _seed = 1234567;
  254. const DEG2RAD = Math.PI / 180;
  255. const RAD2DEG = 180 / Math.PI;
  256. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  257. function generateUUID() {
  258. const d0 = Math.random() * 0xffffffff | 0;
  259. const d1 = Math.random() * 0xffffffff | 0;
  260. const d2 = Math.random() * 0xffffffff | 0;
  261. const d3 = Math.random() * 0xffffffff | 0;
  262. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  263. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  264. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  265. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  266. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  267. return uuid.toLowerCase();
  268. }
  269. function clamp( value, min, max ) {
  270. return Math.max( min, Math.min( max, value ) );
  271. }
  272. // compute euclidean modulo of m % n
  273. // https://en.wikipedia.org/wiki/Modulo_operation
  274. function euclideanModulo( n, m ) {
  275. return ( ( n % m ) + m ) % m;
  276. }
  277. // Linear mapping from range <a1, a2> to range <b1, b2>
  278. function mapLinear( x, a1, a2, b1, b2 ) {
  279. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  280. }
  281. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  282. function inverseLerp( x, y, value ) {
  283. if ( x !== y ) {
  284. return ( value - x ) / ( y - x );
  285. } else {
  286. return 0;
  287. }
  288. }
  289. // https://en.wikipedia.org/wiki/Linear_interpolation
  290. function lerp( x, y, t ) {
  291. return ( 1 - t ) * x + t * y;
  292. }
  293. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  294. function damp( x, y, lambda, dt ) {
  295. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  296. }
  297. // https://www.desmos.com/calculator/vcsjnyz7x4
  298. function pingpong( x, length = 1 ) {
  299. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  300. }
  301. // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep( x, min, max ) {
  303. if ( x <= min ) return 0;
  304. if ( x >= max ) return 1;
  305. x = ( x - min ) / ( max - min );
  306. return x * x * ( 3 - 2 * x );
  307. }
  308. function smootherstep( x, min, max ) {
  309. if ( x <= min ) return 0;
  310. if ( x >= max ) return 1;
  311. x = ( x - min ) / ( max - min );
  312. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  313. }
  314. // Random integer from <low, high> interval
  315. function randInt( low, high ) {
  316. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  317. }
  318. // Random float from <low, high> interval
  319. function randFloat( low, high ) {
  320. return low + Math.random() * ( high - low );
  321. }
  322. // Random float from <-range/2, range/2> interval
  323. function randFloatSpread( range ) {
  324. return range * ( 0.5 - Math.random() );
  325. }
  326. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  327. function seededRandom( s ) {
  328. if ( s !== undefined ) _seed = s;
  329. // Mulberry32 generator
  330. let t = _seed += 0x6D2B79F5;
  331. t = Math.imul( t ^ t >>> 15, t | 1 );
  332. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  333. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  334. }
  335. function degToRad( degrees ) {
  336. return degrees * DEG2RAD;
  337. }
  338. function radToDeg( radians ) {
  339. return radians * RAD2DEG;
  340. }
  341. function isPowerOfTwo( value ) {
  342. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  343. }
  344. function ceilPowerOfTwo( value ) {
  345. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  346. }
  347. function floorPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  351. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  352. // rotations are applied to the axes in the order specified by 'order'
  353. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  354. // angles are in radians
  355. const cos = Math.cos;
  356. const sin = Math.sin;
  357. const c2 = cos( b / 2 );
  358. const s2 = sin( b / 2 );
  359. const c13 = cos( ( a + c ) / 2 );
  360. const s13 = sin( ( a + c ) / 2 );
  361. const c1_3 = cos( ( a - c ) / 2 );
  362. const s1_3 = sin( ( a - c ) / 2 );
  363. const c3_1 = cos( ( c - a ) / 2 );
  364. const s3_1 = sin( ( c - a ) / 2 );
  365. switch ( order ) {
  366. case 'XYX':
  367. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  368. break;
  369. case 'YZY':
  370. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  371. break;
  372. case 'ZXZ':
  373. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  374. break;
  375. case 'XZX':
  376. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  377. break;
  378. case 'YXY':
  379. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  380. break;
  381. case 'ZYZ':
  382. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  383. break;
  384. default:
  385. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  386. }
  387. }
  388. function denormalize( value, array ) {
  389. switch ( array.constructor ) {
  390. case Float32Array:
  391. return value;
  392. case Uint32Array:
  393. return value / 4294967295.0;
  394. case Uint16Array:
  395. return value / 65535.0;
  396. case Uint8Array:
  397. return value / 255.0;
  398. case Int32Array:
  399. return Math.max( value / 2147483647.0, - 1.0 );
  400. case Int16Array:
  401. return Math.max( value / 32767.0, - 1.0 );
  402. case Int8Array:
  403. return Math.max( value / 127.0, - 1.0 );
  404. default:
  405. throw new Error( 'Invalid component type.' );
  406. }
  407. }
  408. function normalize( value, array ) {
  409. switch ( array.constructor ) {
  410. case Float32Array:
  411. return value;
  412. case Uint32Array:
  413. return Math.round( value * 4294967295.0 );
  414. case Uint16Array:
  415. return Math.round( value * 65535.0 );
  416. case Uint8Array:
  417. return Math.round( value * 255.0 );
  418. case Int32Array:
  419. return Math.round( value * 2147483647.0 );
  420. case Int16Array:
  421. return Math.round( value * 32767.0 );
  422. case Int8Array:
  423. return Math.round( value * 127.0 );
  424. default:
  425. throw new Error( 'Invalid component type.' );
  426. }
  427. }
  428. const MathUtils = {
  429. DEG2RAD: DEG2RAD,
  430. RAD2DEG: RAD2DEG,
  431. generateUUID: generateUUID,
  432. clamp: clamp,
  433. euclideanModulo: euclideanModulo,
  434. mapLinear: mapLinear,
  435. inverseLerp: inverseLerp,
  436. lerp: lerp,
  437. damp: damp,
  438. pingpong: pingpong,
  439. smoothstep: smoothstep,
  440. smootherstep: smootherstep,
  441. randInt: randInt,
  442. randFloat: randFloat,
  443. randFloatSpread: randFloatSpread,
  444. seededRandom: seededRandom,
  445. degToRad: degToRad,
  446. radToDeg: radToDeg,
  447. isPowerOfTwo: isPowerOfTwo,
  448. ceilPowerOfTwo: ceilPowerOfTwo,
  449. floorPowerOfTwo: floorPowerOfTwo,
  450. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  451. normalize: normalize,
  452. denormalize: denormalize
  453. };
  454. class Vector2 {
  455. constructor( x = 0, y = 0 ) {
  456. Vector2.prototype.isVector2 = true;
  457. this.x = x;
  458. this.y = y;
  459. }
  460. get width() {
  461. return this.x;
  462. }
  463. set width( value ) {
  464. this.x = value;
  465. }
  466. get height() {
  467. return this.y;
  468. }
  469. set height( value ) {
  470. this.y = value;
  471. }
  472. set( x, y ) {
  473. this.x = x;
  474. this.y = y;
  475. return this;
  476. }
  477. setScalar( scalar ) {
  478. this.x = scalar;
  479. this.y = scalar;
  480. return this;
  481. }
  482. setX( x ) {
  483. this.x = x;
  484. return this;
  485. }
  486. setY( y ) {
  487. this.y = y;
  488. return this;
  489. }
  490. setComponent( index, value ) {
  491. switch ( index ) {
  492. case 0: this.x = value; break;
  493. case 1: this.y = value; break;
  494. default: throw new Error( 'index is out of range: ' + index );
  495. }
  496. return this;
  497. }
  498. getComponent( index ) {
  499. switch ( index ) {
  500. case 0: return this.x;
  501. case 1: return this.y;
  502. default: throw new Error( 'index is out of range: ' + index );
  503. }
  504. }
  505. clone() {
  506. return new this.constructor( this.x, this.y );
  507. }
  508. copy( v ) {
  509. this.x = v.x;
  510. this.y = v.y;
  511. return this;
  512. }
  513. add( v ) {
  514. this.x += v.x;
  515. this.y += v.y;
  516. return this;
  517. }
  518. addScalar( s ) {
  519. this.x += s;
  520. this.y += s;
  521. return this;
  522. }
  523. addVectors( a, b ) {
  524. this.x = a.x + b.x;
  525. this.y = a.y + b.y;
  526. return this;
  527. }
  528. addScaledVector( v, s ) {
  529. this.x += v.x * s;
  530. this.y += v.y * s;
  531. return this;
  532. }
  533. sub( v ) {
  534. this.x -= v.x;
  535. this.y -= v.y;
  536. return this;
  537. }
  538. subScalar( s ) {
  539. this.x -= s;
  540. this.y -= s;
  541. return this;
  542. }
  543. subVectors( a, b ) {
  544. this.x = a.x - b.x;
  545. this.y = a.y - b.y;
  546. return this;
  547. }
  548. multiply( v ) {
  549. this.x *= v.x;
  550. this.y *= v.y;
  551. return this;
  552. }
  553. multiplyScalar( scalar ) {
  554. this.x *= scalar;
  555. this.y *= scalar;
  556. return this;
  557. }
  558. divide( v ) {
  559. this.x /= v.x;
  560. this.y /= v.y;
  561. return this;
  562. }
  563. divideScalar( scalar ) {
  564. return this.multiplyScalar( 1 / scalar );
  565. }
  566. applyMatrix3( m ) {
  567. const x = this.x, y = this.y;
  568. const e = m.elements;
  569. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  570. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  571. return this;
  572. }
  573. min( v ) {
  574. this.x = Math.min( this.x, v.x );
  575. this.y = Math.min( this.y, v.y );
  576. return this;
  577. }
  578. max( v ) {
  579. this.x = Math.max( this.x, v.x );
  580. this.y = Math.max( this.y, v.y );
  581. return this;
  582. }
  583. clamp( min, max ) {
  584. // assumes min < max, componentwise
  585. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  586. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  587. return this;
  588. }
  589. clampScalar( minVal, maxVal ) {
  590. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  591. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  592. return this;
  593. }
  594. clampLength( min, max ) {
  595. const length = this.length();
  596. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  597. }
  598. floor() {
  599. this.x = Math.floor( this.x );
  600. this.y = Math.floor( this.y );
  601. return this;
  602. }
  603. ceil() {
  604. this.x = Math.ceil( this.x );
  605. this.y = Math.ceil( this.y );
  606. return this;
  607. }
  608. round() {
  609. this.x = Math.round( this.x );
  610. this.y = Math.round( this.y );
  611. return this;
  612. }
  613. roundToZero() {
  614. this.x = Math.trunc( this.x );
  615. this.y = Math.trunc( this.y );
  616. return this;
  617. }
  618. negate() {
  619. this.x = - this.x;
  620. this.y = - this.y;
  621. return this;
  622. }
  623. dot( v ) {
  624. return this.x * v.x + this.y * v.y;
  625. }
  626. cross( v ) {
  627. return this.x * v.y - this.y * v.x;
  628. }
  629. lengthSq() {
  630. return this.x * this.x + this.y * this.y;
  631. }
  632. length() {
  633. return Math.sqrt( this.x * this.x + this.y * this.y );
  634. }
  635. manhattanLength() {
  636. return Math.abs( this.x ) + Math.abs( this.y );
  637. }
  638. normalize() {
  639. return this.divideScalar( this.length() || 1 );
  640. }
  641. angle() {
  642. // computes the angle in radians with respect to the positive x-axis
  643. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  644. return angle;
  645. }
  646. angleTo( v ) {
  647. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  648. if ( denominator === 0 ) return Math.PI / 2;
  649. const theta = this.dot( v ) / denominator;
  650. // clamp, to handle numerical problems
  651. return Math.acos( clamp( theta, - 1, 1 ) );
  652. }
  653. distanceTo( v ) {
  654. return Math.sqrt( this.distanceToSquared( v ) );
  655. }
  656. distanceToSquared( v ) {
  657. const dx = this.x - v.x, dy = this.y - v.y;
  658. return dx * dx + dy * dy;
  659. }
  660. manhattanDistanceTo( v ) {
  661. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  662. }
  663. setLength( length ) {
  664. return this.normalize().multiplyScalar( length );
  665. }
  666. lerp( v, alpha ) {
  667. this.x += ( v.x - this.x ) * alpha;
  668. this.y += ( v.y - this.y ) * alpha;
  669. return this;
  670. }
  671. lerpVectors( v1, v2, alpha ) {
  672. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  673. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  674. return this;
  675. }
  676. equals( v ) {
  677. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  678. }
  679. fromArray( array, offset = 0 ) {
  680. this.x = array[ offset ];
  681. this.y = array[ offset + 1 ];
  682. return this;
  683. }
  684. toArray( array = [], offset = 0 ) {
  685. array[ offset ] = this.x;
  686. array[ offset + 1 ] = this.y;
  687. return array;
  688. }
  689. fromBufferAttribute( attribute, index ) {
  690. this.x = attribute.getX( index );
  691. this.y = attribute.getY( index );
  692. return this;
  693. }
  694. rotateAround( center, angle ) {
  695. const c = Math.cos( angle ), s = Math.sin( angle );
  696. const x = this.x - center.x;
  697. const y = this.y - center.y;
  698. this.x = x * c - y * s + center.x;
  699. this.y = x * s + y * c + center.y;
  700. return this;
  701. }
  702. random() {
  703. this.x = Math.random();
  704. this.y = Math.random();
  705. return this;
  706. }
  707. *[ Symbol.iterator ]() {
  708. yield this.x;
  709. yield this.y;
  710. }
  711. }
  712. class Matrix3 {
  713. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  714. Matrix3.prototype.isMatrix3 = true;
  715. this.elements = [
  716. 1, 0, 0,
  717. 0, 1, 0,
  718. 0, 0, 1
  719. ];
  720. if ( n11 !== undefined ) {
  721. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  722. }
  723. }
  724. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  725. const te = this.elements;
  726. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  727. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  728. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  729. return this;
  730. }
  731. identity() {
  732. this.set(
  733. 1, 0, 0,
  734. 0, 1, 0,
  735. 0, 0, 1
  736. );
  737. return this;
  738. }
  739. copy( m ) {
  740. const te = this.elements;
  741. const me = m.elements;
  742. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  743. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  744. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  745. return this;
  746. }
  747. extractBasis( xAxis, yAxis, zAxis ) {
  748. xAxis.setFromMatrix3Column( this, 0 );
  749. yAxis.setFromMatrix3Column( this, 1 );
  750. zAxis.setFromMatrix3Column( this, 2 );
  751. return this;
  752. }
  753. setFromMatrix4( m ) {
  754. const me = m.elements;
  755. this.set(
  756. me[ 0 ], me[ 4 ], me[ 8 ],
  757. me[ 1 ], me[ 5 ], me[ 9 ],
  758. me[ 2 ], me[ 6 ], me[ 10 ]
  759. );
  760. return this;
  761. }
  762. multiply( m ) {
  763. return this.multiplyMatrices( this, m );
  764. }
  765. premultiply( m ) {
  766. return this.multiplyMatrices( m, this );
  767. }
  768. multiplyMatrices( a, b ) {
  769. const ae = a.elements;
  770. const be = b.elements;
  771. const te = this.elements;
  772. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  773. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  774. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  775. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  776. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  777. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  778. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  779. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  780. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  781. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  782. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  783. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  784. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  785. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  786. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  787. return this;
  788. }
  789. multiplyScalar( s ) {
  790. const te = this.elements;
  791. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  792. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  793. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  794. return this;
  795. }
  796. determinant() {
  797. const te = this.elements;
  798. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  799. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  800. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  801. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  802. }
  803. invert() {
  804. const te = this.elements,
  805. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  806. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  807. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  808. t11 = n33 * n22 - n32 * n23,
  809. t12 = n32 * n13 - n33 * n12,
  810. t13 = n23 * n12 - n22 * n13,
  811. det = n11 * t11 + n21 * t12 + n31 * t13;
  812. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  813. const detInv = 1 / det;
  814. te[ 0 ] = t11 * detInv;
  815. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  816. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  817. te[ 3 ] = t12 * detInv;
  818. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  819. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  820. te[ 6 ] = t13 * detInv;
  821. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  822. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  823. return this;
  824. }
  825. transpose() {
  826. let tmp;
  827. const m = this.elements;
  828. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  829. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  830. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  831. return this;
  832. }
  833. getNormalMatrix( matrix4 ) {
  834. return this.setFromMatrix4( matrix4 ).invert().transpose();
  835. }
  836. transposeIntoArray( r ) {
  837. const m = this.elements;
  838. r[ 0 ] = m[ 0 ];
  839. r[ 1 ] = m[ 3 ];
  840. r[ 2 ] = m[ 6 ];
  841. r[ 3 ] = m[ 1 ];
  842. r[ 4 ] = m[ 4 ];
  843. r[ 5 ] = m[ 7 ];
  844. r[ 6 ] = m[ 2 ];
  845. r[ 7 ] = m[ 5 ];
  846. r[ 8 ] = m[ 8 ];
  847. return this;
  848. }
  849. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  850. const c = Math.cos( rotation );
  851. const s = Math.sin( rotation );
  852. this.set(
  853. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  854. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  855. 0, 0, 1
  856. );
  857. return this;
  858. }
  859. //
  860. scale( sx, sy ) {
  861. this.premultiply( _m3.makeScale( sx, sy ) );
  862. return this;
  863. }
  864. rotate( theta ) {
  865. this.premultiply( _m3.makeRotation( - theta ) );
  866. return this;
  867. }
  868. translate( tx, ty ) {
  869. this.premultiply( _m3.makeTranslation( tx, ty ) );
  870. return this;
  871. }
  872. // for 2D Transforms
  873. makeTranslation( x, y ) {
  874. if ( x.isVector2 ) {
  875. this.set(
  876. 1, 0, x.x,
  877. 0, 1, x.y,
  878. 0, 0, 1
  879. );
  880. } else {
  881. this.set(
  882. 1, 0, x,
  883. 0, 1, y,
  884. 0, 0, 1
  885. );
  886. }
  887. return this;
  888. }
  889. makeRotation( theta ) {
  890. // counterclockwise
  891. const c = Math.cos( theta );
  892. const s = Math.sin( theta );
  893. this.set(
  894. c, - s, 0,
  895. s, c, 0,
  896. 0, 0, 1
  897. );
  898. return this;
  899. }
  900. makeScale( x, y ) {
  901. this.set(
  902. x, 0, 0,
  903. 0, y, 0,
  904. 0, 0, 1
  905. );
  906. return this;
  907. }
  908. //
  909. equals( matrix ) {
  910. const te = this.elements;
  911. const me = matrix.elements;
  912. for ( let i = 0; i < 9; i ++ ) {
  913. if ( te[ i ] !== me[ i ] ) return false;
  914. }
  915. return true;
  916. }
  917. fromArray( array, offset = 0 ) {
  918. for ( let i = 0; i < 9; i ++ ) {
  919. this.elements[ i ] = array[ i + offset ];
  920. }
  921. return this;
  922. }
  923. toArray( array = [], offset = 0 ) {
  924. const te = this.elements;
  925. array[ offset ] = te[ 0 ];
  926. array[ offset + 1 ] = te[ 1 ];
  927. array[ offset + 2 ] = te[ 2 ];
  928. array[ offset + 3 ] = te[ 3 ];
  929. array[ offset + 4 ] = te[ 4 ];
  930. array[ offset + 5 ] = te[ 5 ];
  931. array[ offset + 6 ] = te[ 6 ];
  932. array[ offset + 7 ] = te[ 7 ];
  933. array[ offset + 8 ] = te[ 8 ];
  934. return array;
  935. }
  936. clone() {
  937. return new this.constructor().fromArray( this.elements );
  938. }
  939. }
  940. const _m3 = /*@__PURE__*/ new Matrix3();
  941. function arrayNeedsUint32( array ) {
  942. // assumes larger values usually on last
  943. for ( let i = array.length - 1; i >= 0; -- i ) {
  944. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  945. }
  946. return false;
  947. }
  948. const TYPED_ARRAYS = {
  949. Int8Array: Int8Array,
  950. Uint8Array: Uint8Array,
  951. Uint8ClampedArray: Uint8ClampedArray,
  952. Int16Array: Int16Array,
  953. Uint16Array: Uint16Array,
  954. Int32Array: Int32Array,
  955. Uint32Array: Uint32Array,
  956. Float32Array: Float32Array,
  957. Float64Array: Float64Array
  958. };
  959. function getTypedArray( type, buffer ) {
  960. return new TYPED_ARRAYS[ type ]( buffer );
  961. }
  962. function createElementNS( name ) {
  963. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  964. }
  965. function createCanvasElement() {
  966. const canvas = createElementNS( 'canvas' );
  967. canvas.style.display = 'block';
  968. return canvas;
  969. }
  970. const _cache = {};
  971. function warnOnce( message ) {
  972. if ( message in _cache ) return;
  973. _cache[ message ] = true;
  974. console.warn( message );
  975. }
  976. function probeAsync( gl, sync, interval ) {
  977. return new Promise( function ( resolve, reject ) {
  978. function probe() {
  979. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  980. case gl.WAIT_FAILED:
  981. reject();
  982. break;
  983. case gl.TIMEOUT_EXPIRED:
  984. setTimeout( probe, interval );
  985. break;
  986. default:
  987. resolve();
  988. }
  989. }
  990. setTimeout( probe, interval );
  991. } );
  992. }
  993. /**
  994. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  995. * or clipping. Based on W3C specifications for sRGB and Display P3,
  996. * and ICC specifications for the D50 connection space. Values in/out
  997. * are _linear_ sRGB and _linear_ Display P3.
  998. *
  999. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  1000. *
  1001. * Reference:
  1002. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  1003. */
  1004. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  1005. 0.8224621, 0.177538, 0.0,
  1006. 0.0331941, 0.9668058, 0.0,
  1007. 0.0170827, 0.0723974, 0.9105199,
  1008. );
  1009. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  1010. 1.2249401, - 0.2249404, 0.0,
  1011. - 0.0420569, 1.0420571, 0.0,
  1012. - 0.0196376, - 0.0786361, 1.0982735
  1013. );
  1014. /**
  1015. * Defines supported color spaces by transfer function and primaries,
  1016. * and provides conversions to/from the Linear-sRGB reference space.
  1017. */
  1018. const COLOR_SPACES = {
  1019. [ LinearSRGBColorSpace ]: {
  1020. transfer: LinearTransfer,
  1021. primaries: Rec709Primaries,
  1022. toReference: ( color ) => color,
  1023. fromReference: ( color ) => color,
  1024. },
  1025. [ SRGBColorSpace ]: {
  1026. transfer: SRGBTransfer,
  1027. primaries: Rec709Primaries,
  1028. toReference: ( color ) => color.convertSRGBToLinear(),
  1029. fromReference: ( color ) => color.convertLinearToSRGB(),
  1030. },
  1031. [ LinearDisplayP3ColorSpace ]: {
  1032. transfer: LinearTransfer,
  1033. primaries: P3Primaries,
  1034. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1035. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1036. },
  1037. [ DisplayP3ColorSpace ]: {
  1038. transfer: SRGBTransfer,
  1039. primaries: P3Primaries,
  1040. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1041. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1042. },
  1043. };
  1044. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1045. const ColorManagement = {
  1046. enabled: true,
  1047. _workingColorSpace: LinearSRGBColorSpace,
  1048. get workingColorSpace() {
  1049. return this._workingColorSpace;
  1050. },
  1051. set workingColorSpace( colorSpace ) {
  1052. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1053. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1054. }
  1055. this._workingColorSpace = colorSpace;
  1056. },
  1057. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1058. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1059. return color;
  1060. }
  1061. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1062. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1063. return targetFromReference( sourceToReference( color ) );
  1064. },
  1065. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1066. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1067. },
  1068. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1069. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1070. },
  1071. getPrimaries: function ( colorSpace ) {
  1072. return COLOR_SPACES[ colorSpace ].primaries;
  1073. },
  1074. getTransfer: function ( colorSpace ) {
  1075. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1076. return COLOR_SPACES[ colorSpace ].transfer;
  1077. },
  1078. };
  1079. function SRGBToLinear( c ) {
  1080. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1081. }
  1082. function LinearToSRGB( c ) {
  1083. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1084. }
  1085. let _canvas;
  1086. class ImageUtils {
  1087. static getDataURL( image ) {
  1088. if ( /^data:/i.test( image.src ) ) {
  1089. return image.src;
  1090. }
  1091. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1092. return image.src;
  1093. }
  1094. let canvas;
  1095. if ( image instanceof HTMLCanvasElement ) {
  1096. canvas = image;
  1097. } else {
  1098. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1099. _canvas.width = image.width;
  1100. _canvas.height = image.height;
  1101. const context = _canvas.getContext( '2d' );
  1102. if ( image instanceof ImageData ) {
  1103. context.putImageData( image, 0, 0 );
  1104. } else {
  1105. context.drawImage( image, 0, 0, image.width, image.height );
  1106. }
  1107. canvas = _canvas;
  1108. }
  1109. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1110. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1111. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1112. } else {
  1113. return canvas.toDataURL( 'image/png' );
  1114. }
  1115. }
  1116. static sRGBToLinear( image ) {
  1117. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1118. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1119. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1120. const canvas = createElementNS( 'canvas' );
  1121. canvas.width = image.width;
  1122. canvas.height = image.height;
  1123. const context = canvas.getContext( '2d' );
  1124. context.drawImage( image, 0, 0, image.width, image.height );
  1125. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1126. const data = imageData.data;
  1127. for ( let i = 0; i < data.length; i ++ ) {
  1128. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1129. }
  1130. context.putImageData( imageData, 0, 0 );
  1131. return canvas;
  1132. } else if ( image.data ) {
  1133. const data = image.data.slice( 0 );
  1134. for ( let i = 0; i < data.length; i ++ ) {
  1135. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1136. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1137. } else {
  1138. // assuming float
  1139. data[ i ] = SRGBToLinear( data[ i ] );
  1140. }
  1141. }
  1142. return {
  1143. data: data,
  1144. width: image.width,
  1145. height: image.height
  1146. };
  1147. } else {
  1148. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1149. return image;
  1150. }
  1151. }
  1152. }
  1153. let _sourceId = 0;
  1154. class Source {
  1155. constructor( data = null ) {
  1156. this.isSource = true;
  1157. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1158. this.uuid = generateUUID();
  1159. this.data = data;
  1160. this.dataReady = true;
  1161. this.version = 0;
  1162. }
  1163. set needsUpdate( value ) {
  1164. if ( value === true ) this.version ++;
  1165. }
  1166. toJSON( meta ) {
  1167. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1168. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1169. return meta.images[ this.uuid ];
  1170. }
  1171. const output = {
  1172. uuid: this.uuid,
  1173. url: ''
  1174. };
  1175. const data = this.data;
  1176. if ( data !== null ) {
  1177. let url;
  1178. if ( Array.isArray( data ) ) {
  1179. // cube texture
  1180. url = [];
  1181. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1182. if ( data[ i ].isDataTexture ) {
  1183. url.push( serializeImage( data[ i ].image ) );
  1184. } else {
  1185. url.push( serializeImage( data[ i ] ) );
  1186. }
  1187. }
  1188. } else {
  1189. // texture
  1190. url = serializeImage( data );
  1191. }
  1192. output.url = url;
  1193. }
  1194. if ( ! isRootObject ) {
  1195. meta.images[ this.uuid ] = output;
  1196. }
  1197. return output;
  1198. }
  1199. }
  1200. function serializeImage( image ) {
  1201. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1202. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1203. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1204. // default images
  1205. return ImageUtils.getDataURL( image );
  1206. } else {
  1207. if ( image.data ) {
  1208. // images of DataTexture
  1209. return {
  1210. data: Array.from( image.data ),
  1211. width: image.width,
  1212. height: image.height,
  1213. type: image.data.constructor.name
  1214. };
  1215. } else {
  1216. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1217. return {};
  1218. }
  1219. }
  1220. }
  1221. let _textureId = 0;
  1222. class Texture extends EventDispatcher {
  1223. 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 ) {
  1224. super();
  1225. this.isTexture = true;
  1226. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1227. this.uuid = generateUUID();
  1228. this.name = '';
  1229. this.source = new Source( image );
  1230. this.mipmaps = [];
  1231. this.mapping = mapping;
  1232. this.channel = 0;
  1233. this.wrapS = wrapS;
  1234. this.wrapT = wrapT;
  1235. this.magFilter = magFilter;
  1236. this.minFilter = minFilter;
  1237. this.anisotropy = anisotropy;
  1238. this.format = format;
  1239. this.internalFormat = null;
  1240. this.type = type;
  1241. this.offset = new Vector2( 0, 0 );
  1242. this.repeat = new Vector2( 1, 1 );
  1243. this.center = new Vector2( 0, 0 );
  1244. this.rotation = 0;
  1245. this.matrixAutoUpdate = true;
  1246. this.matrix = new Matrix3();
  1247. this.generateMipmaps = true;
  1248. this.premultiplyAlpha = false;
  1249. this.flipY = true;
  1250. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1251. this.colorSpace = colorSpace;
  1252. this.userData = {};
  1253. this.version = 0;
  1254. this.onUpdate = null;
  1255. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1256. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1257. }
  1258. get image() {
  1259. return this.source.data;
  1260. }
  1261. set image( value = null ) {
  1262. this.source.data = value;
  1263. }
  1264. updateMatrix() {
  1265. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1266. }
  1267. clone() {
  1268. return new this.constructor().copy( this );
  1269. }
  1270. copy( source ) {
  1271. this.name = source.name;
  1272. this.source = source.source;
  1273. this.mipmaps = source.mipmaps.slice( 0 );
  1274. this.mapping = source.mapping;
  1275. this.channel = source.channel;
  1276. this.wrapS = source.wrapS;
  1277. this.wrapT = source.wrapT;
  1278. this.magFilter = source.magFilter;
  1279. this.minFilter = source.minFilter;
  1280. this.anisotropy = source.anisotropy;
  1281. this.format = source.format;
  1282. this.internalFormat = source.internalFormat;
  1283. this.type = source.type;
  1284. this.offset.copy( source.offset );
  1285. this.repeat.copy( source.repeat );
  1286. this.center.copy( source.center );
  1287. this.rotation = source.rotation;
  1288. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1289. this.matrix.copy( source.matrix );
  1290. this.generateMipmaps = source.generateMipmaps;
  1291. this.premultiplyAlpha = source.premultiplyAlpha;
  1292. this.flipY = source.flipY;
  1293. this.unpackAlignment = source.unpackAlignment;
  1294. this.colorSpace = source.colorSpace;
  1295. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1296. this.needsUpdate = true;
  1297. return this;
  1298. }
  1299. toJSON( meta ) {
  1300. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1301. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1302. return meta.textures[ this.uuid ];
  1303. }
  1304. const output = {
  1305. metadata: {
  1306. version: 4.6,
  1307. type: 'Texture',
  1308. generator: 'Texture.toJSON'
  1309. },
  1310. uuid: this.uuid,
  1311. name: this.name,
  1312. image: this.source.toJSON( meta ).uuid,
  1313. mapping: this.mapping,
  1314. channel: this.channel,
  1315. repeat: [ this.repeat.x, this.repeat.y ],
  1316. offset: [ this.offset.x, this.offset.y ],
  1317. center: [ this.center.x, this.center.y ],
  1318. rotation: this.rotation,
  1319. wrap: [ this.wrapS, this.wrapT ],
  1320. format: this.format,
  1321. internalFormat: this.internalFormat,
  1322. type: this.type,
  1323. colorSpace: this.colorSpace,
  1324. minFilter: this.minFilter,
  1325. magFilter: this.magFilter,
  1326. anisotropy: this.anisotropy,
  1327. flipY: this.flipY,
  1328. generateMipmaps: this.generateMipmaps,
  1329. premultiplyAlpha: this.premultiplyAlpha,
  1330. unpackAlignment: this.unpackAlignment
  1331. };
  1332. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1333. if ( ! isRootObject ) {
  1334. meta.textures[ this.uuid ] = output;
  1335. }
  1336. return output;
  1337. }
  1338. dispose() {
  1339. this.dispatchEvent( { type: 'dispose' } );
  1340. }
  1341. transformUv( uv ) {
  1342. if ( this.mapping !== UVMapping ) return uv;
  1343. uv.applyMatrix3( this.matrix );
  1344. if ( uv.x < 0 || uv.x > 1 ) {
  1345. switch ( this.wrapS ) {
  1346. case RepeatWrapping:
  1347. uv.x = uv.x - Math.floor( uv.x );
  1348. break;
  1349. case ClampToEdgeWrapping:
  1350. uv.x = uv.x < 0 ? 0 : 1;
  1351. break;
  1352. case MirroredRepeatWrapping:
  1353. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1354. uv.x = Math.ceil( uv.x ) - uv.x;
  1355. } else {
  1356. uv.x = uv.x - Math.floor( uv.x );
  1357. }
  1358. break;
  1359. }
  1360. }
  1361. if ( uv.y < 0 || uv.y > 1 ) {
  1362. switch ( this.wrapT ) {
  1363. case RepeatWrapping:
  1364. uv.y = uv.y - Math.floor( uv.y );
  1365. break;
  1366. case ClampToEdgeWrapping:
  1367. uv.y = uv.y < 0 ? 0 : 1;
  1368. break;
  1369. case MirroredRepeatWrapping:
  1370. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1371. uv.y = Math.ceil( uv.y ) - uv.y;
  1372. } else {
  1373. uv.y = uv.y - Math.floor( uv.y );
  1374. }
  1375. break;
  1376. }
  1377. }
  1378. if ( this.flipY ) {
  1379. uv.y = 1 - uv.y;
  1380. }
  1381. return uv;
  1382. }
  1383. set needsUpdate( value ) {
  1384. if ( value === true ) {
  1385. this.version ++;
  1386. this.source.needsUpdate = true;
  1387. }
  1388. }
  1389. set needsPMREMUpdate( value ) {
  1390. if ( value === true ) {
  1391. this.pmremVersion ++;
  1392. }
  1393. }
  1394. }
  1395. Texture.DEFAULT_IMAGE = null;
  1396. Texture.DEFAULT_MAPPING = UVMapping;
  1397. Texture.DEFAULT_ANISOTROPY = 1;
  1398. class Vector4 {
  1399. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1400. Vector4.prototype.isVector4 = true;
  1401. this.x = x;
  1402. this.y = y;
  1403. this.z = z;
  1404. this.w = w;
  1405. }
  1406. get width() {
  1407. return this.z;
  1408. }
  1409. set width( value ) {
  1410. this.z = value;
  1411. }
  1412. get height() {
  1413. return this.w;
  1414. }
  1415. set height( value ) {
  1416. this.w = value;
  1417. }
  1418. set( x, y, z, w ) {
  1419. this.x = x;
  1420. this.y = y;
  1421. this.z = z;
  1422. this.w = w;
  1423. return this;
  1424. }
  1425. setScalar( scalar ) {
  1426. this.x = scalar;
  1427. this.y = scalar;
  1428. this.z = scalar;
  1429. this.w = scalar;
  1430. return this;
  1431. }
  1432. setX( x ) {
  1433. this.x = x;
  1434. return this;
  1435. }
  1436. setY( y ) {
  1437. this.y = y;
  1438. return this;
  1439. }
  1440. setZ( z ) {
  1441. this.z = z;
  1442. return this;
  1443. }
  1444. setW( w ) {
  1445. this.w = w;
  1446. return this;
  1447. }
  1448. setComponent( index, value ) {
  1449. switch ( index ) {
  1450. case 0: this.x = value; break;
  1451. case 1: this.y = value; break;
  1452. case 2: this.z = value; break;
  1453. case 3: this.w = value; break;
  1454. default: throw new Error( 'index is out of range: ' + index );
  1455. }
  1456. return this;
  1457. }
  1458. getComponent( index ) {
  1459. switch ( index ) {
  1460. case 0: return this.x;
  1461. case 1: return this.y;
  1462. case 2: return this.z;
  1463. case 3: return this.w;
  1464. default: throw new Error( 'index is out of range: ' + index );
  1465. }
  1466. }
  1467. clone() {
  1468. return new this.constructor( this.x, this.y, this.z, this.w );
  1469. }
  1470. copy( v ) {
  1471. this.x = v.x;
  1472. this.y = v.y;
  1473. this.z = v.z;
  1474. this.w = ( v.w !== undefined ) ? v.w : 1;
  1475. return this;
  1476. }
  1477. add( v ) {
  1478. this.x += v.x;
  1479. this.y += v.y;
  1480. this.z += v.z;
  1481. this.w += v.w;
  1482. return this;
  1483. }
  1484. addScalar( s ) {
  1485. this.x += s;
  1486. this.y += s;
  1487. this.z += s;
  1488. this.w += s;
  1489. return this;
  1490. }
  1491. addVectors( a, b ) {
  1492. this.x = a.x + b.x;
  1493. this.y = a.y + b.y;
  1494. this.z = a.z + b.z;
  1495. this.w = a.w + b.w;
  1496. return this;
  1497. }
  1498. addScaledVector( v, s ) {
  1499. this.x += v.x * s;
  1500. this.y += v.y * s;
  1501. this.z += v.z * s;
  1502. this.w += v.w * s;
  1503. return this;
  1504. }
  1505. sub( v ) {
  1506. this.x -= v.x;
  1507. this.y -= v.y;
  1508. this.z -= v.z;
  1509. this.w -= v.w;
  1510. return this;
  1511. }
  1512. subScalar( s ) {
  1513. this.x -= s;
  1514. this.y -= s;
  1515. this.z -= s;
  1516. this.w -= s;
  1517. return this;
  1518. }
  1519. subVectors( a, b ) {
  1520. this.x = a.x - b.x;
  1521. this.y = a.y - b.y;
  1522. this.z = a.z - b.z;
  1523. this.w = a.w - b.w;
  1524. return this;
  1525. }
  1526. multiply( v ) {
  1527. this.x *= v.x;
  1528. this.y *= v.y;
  1529. this.z *= v.z;
  1530. this.w *= v.w;
  1531. return this;
  1532. }
  1533. multiplyScalar( scalar ) {
  1534. this.x *= scalar;
  1535. this.y *= scalar;
  1536. this.z *= scalar;
  1537. this.w *= scalar;
  1538. return this;
  1539. }
  1540. applyMatrix4( m ) {
  1541. const x = this.x, y = this.y, z = this.z, w = this.w;
  1542. const e = m.elements;
  1543. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1544. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1545. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1546. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1547. return this;
  1548. }
  1549. divideScalar( scalar ) {
  1550. return this.multiplyScalar( 1 / scalar );
  1551. }
  1552. setAxisAngleFromQuaternion( q ) {
  1553. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1554. // q is assumed to be normalized
  1555. this.w = 2 * Math.acos( q.w );
  1556. const s = Math.sqrt( 1 - q.w * q.w );
  1557. if ( s < 0.0001 ) {
  1558. this.x = 1;
  1559. this.y = 0;
  1560. this.z = 0;
  1561. } else {
  1562. this.x = q.x / s;
  1563. this.y = q.y / s;
  1564. this.z = q.z / s;
  1565. }
  1566. return this;
  1567. }
  1568. setAxisAngleFromRotationMatrix( m ) {
  1569. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1570. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1571. let angle, x, y, z; // variables for result
  1572. const epsilon = 0.01, // margin to allow for rounding errors
  1573. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1574. te = m.elements,
  1575. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1576. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1577. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1578. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1579. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1580. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1581. // singularity found
  1582. // first check for identity matrix which must have +1 for all terms
  1583. // in leading diagonal and zero in other terms
  1584. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1585. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1586. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1587. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1588. // this singularity is identity matrix so angle = 0
  1589. this.set( 1, 0, 0, 0 );
  1590. return this; // zero angle, arbitrary axis
  1591. }
  1592. // otherwise this singularity is angle = 180
  1593. angle = Math.PI;
  1594. const xx = ( m11 + 1 ) / 2;
  1595. const yy = ( m22 + 1 ) / 2;
  1596. const zz = ( m33 + 1 ) / 2;
  1597. const xy = ( m12 + m21 ) / 4;
  1598. const xz = ( m13 + m31 ) / 4;
  1599. const yz = ( m23 + m32 ) / 4;
  1600. if ( ( xx > yy ) && ( xx > zz ) ) {
  1601. // m11 is the largest diagonal term
  1602. if ( xx < epsilon ) {
  1603. x = 0;
  1604. y = 0.707106781;
  1605. z = 0.707106781;
  1606. } else {
  1607. x = Math.sqrt( xx );
  1608. y = xy / x;
  1609. z = xz / x;
  1610. }
  1611. } else if ( yy > zz ) {
  1612. // m22 is the largest diagonal term
  1613. if ( yy < epsilon ) {
  1614. x = 0.707106781;
  1615. y = 0;
  1616. z = 0.707106781;
  1617. } else {
  1618. y = Math.sqrt( yy );
  1619. x = xy / y;
  1620. z = yz / y;
  1621. }
  1622. } else {
  1623. // m33 is the largest diagonal term so base result on this
  1624. if ( zz < epsilon ) {
  1625. x = 0.707106781;
  1626. y = 0.707106781;
  1627. z = 0;
  1628. } else {
  1629. z = Math.sqrt( zz );
  1630. x = xz / z;
  1631. y = yz / z;
  1632. }
  1633. }
  1634. this.set( x, y, z, angle );
  1635. return this; // return 180 deg rotation
  1636. }
  1637. // as we have reached here there are no singularities so we can handle normally
  1638. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1639. ( m13 - m31 ) * ( m13 - m31 ) +
  1640. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1641. if ( Math.abs( s ) < 0.001 ) s = 1;
  1642. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1643. // caught by singularity test above, but I've left it in just in case
  1644. this.x = ( m32 - m23 ) / s;
  1645. this.y = ( m13 - m31 ) / s;
  1646. this.z = ( m21 - m12 ) / s;
  1647. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1648. return this;
  1649. }
  1650. min( v ) {
  1651. this.x = Math.min( this.x, v.x );
  1652. this.y = Math.min( this.y, v.y );
  1653. this.z = Math.min( this.z, v.z );
  1654. this.w = Math.min( this.w, v.w );
  1655. return this;
  1656. }
  1657. max( v ) {
  1658. this.x = Math.max( this.x, v.x );
  1659. this.y = Math.max( this.y, v.y );
  1660. this.z = Math.max( this.z, v.z );
  1661. this.w = Math.max( this.w, v.w );
  1662. return this;
  1663. }
  1664. clamp( min, max ) {
  1665. // assumes min < max, componentwise
  1666. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1667. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1668. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1669. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1670. return this;
  1671. }
  1672. clampScalar( minVal, maxVal ) {
  1673. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1674. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1675. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1676. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1677. return this;
  1678. }
  1679. clampLength( min, max ) {
  1680. const length = this.length();
  1681. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1682. }
  1683. floor() {
  1684. this.x = Math.floor( this.x );
  1685. this.y = Math.floor( this.y );
  1686. this.z = Math.floor( this.z );
  1687. this.w = Math.floor( this.w );
  1688. return this;
  1689. }
  1690. ceil() {
  1691. this.x = Math.ceil( this.x );
  1692. this.y = Math.ceil( this.y );
  1693. this.z = Math.ceil( this.z );
  1694. this.w = Math.ceil( this.w );
  1695. return this;
  1696. }
  1697. round() {
  1698. this.x = Math.round( this.x );
  1699. this.y = Math.round( this.y );
  1700. this.z = Math.round( this.z );
  1701. this.w = Math.round( this.w );
  1702. return this;
  1703. }
  1704. roundToZero() {
  1705. this.x = Math.trunc( this.x );
  1706. this.y = Math.trunc( this.y );
  1707. this.z = Math.trunc( this.z );
  1708. this.w = Math.trunc( this.w );
  1709. return this;
  1710. }
  1711. negate() {
  1712. this.x = - this.x;
  1713. this.y = - this.y;
  1714. this.z = - this.z;
  1715. this.w = - this.w;
  1716. return this;
  1717. }
  1718. dot( v ) {
  1719. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1720. }
  1721. lengthSq() {
  1722. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1723. }
  1724. length() {
  1725. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1726. }
  1727. manhattanLength() {
  1728. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1729. }
  1730. normalize() {
  1731. return this.divideScalar( this.length() || 1 );
  1732. }
  1733. setLength( length ) {
  1734. return this.normalize().multiplyScalar( length );
  1735. }
  1736. lerp( v, alpha ) {
  1737. this.x += ( v.x - this.x ) * alpha;
  1738. this.y += ( v.y - this.y ) * alpha;
  1739. this.z += ( v.z - this.z ) * alpha;
  1740. this.w += ( v.w - this.w ) * alpha;
  1741. return this;
  1742. }
  1743. lerpVectors( v1, v2, alpha ) {
  1744. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1745. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1746. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1747. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1748. return this;
  1749. }
  1750. equals( v ) {
  1751. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1752. }
  1753. fromArray( array, offset = 0 ) {
  1754. this.x = array[ offset ];
  1755. this.y = array[ offset + 1 ];
  1756. this.z = array[ offset + 2 ];
  1757. this.w = array[ offset + 3 ];
  1758. return this;
  1759. }
  1760. toArray( array = [], offset = 0 ) {
  1761. array[ offset ] = this.x;
  1762. array[ offset + 1 ] = this.y;
  1763. array[ offset + 2 ] = this.z;
  1764. array[ offset + 3 ] = this.w;
  1765. return array;
  1766. }
  1767. fromBufferAttribute( attribute, index ) {
  1768. this.x = attribute.getX( index );
  1769. this.y = attribute.getY( index );
  1770. this.z = attribute.getZ( index );
  1771. this.w = attribute.getW( index );
  1772. return this;
  1773. }
  1774. random() {
  1775. this.x = Math.random();
  1776. this.y = Math.random();
  1777. this.z = Math.random();
  1778. this.w = Math.random();
  1779. return this;
  1780. }
  1781. *[ Symbol.iterator ]() {
  1782. yield this.x;
  1783. yield this.y;
  1784. yield this.z;
  1785. yield this.w;
  1786. }
  1787. }
  1788. /*
  1789. In options, we can specify:
  1790. * Texture parameters for an auto-generated target texture
  1791. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1792. */
  1793. class RenderTarget extends EventDispatcher {
  1794. constructor( width = 1, height = 1, options = {} ) {
  1795. super();
  1796. this.isRenderTarget = true;
  1797. this.width = width;
  1798. this.height = height;
  1799. this.depth = 1;
  1800. this.scissor = new Vector4( 0, 0, width, height );
  1801. this.scissorTest = false;
  1802. this.viewport = new Vector4( 0, 0, width, height );
  1803. const image = { width: width, height: height, depth: 1 };
  1804. options = Object.assign( {
  1805. generateMipmaps: false,
  1806. internalFormat: null,
  1807. minFilter: LinearFilter,
  1808. depthBuffer: true,
  1809. stencilBuffer: false,
  1810. resolveDepthBuffer: true,
  1811. resolveStencilBuffer: true,
  1812. depthTexture: null,
  1813. samples: 0,
  1814. count: 1
  1815. }, options );
  1816. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1817. texture.flipY = false;
  1818. texture.generateMipmaps = options.generateMipmaps;
  1819. texture.internalFormat = options.internalFormat;
  1820. this.textures = [];
  1821. const count = options.count;
  1822. for ( let i = 0; i < count; i ++ ) {
  1823. this.textures[ i ] = texture.clone();
  1824. this.textures[ i ].isRenderTargetTexture = true;
  1825. }
  1826. this.depthBuffer = options.depthBuffer;
  1827. this.stencilBuffer = options.stencilBuffer;
  1828. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1829. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1830. this.depthTexture = options.depthTexture;
  1831. this.samples = options.samples;
  1832. }
  1833. get texture() {
  1834. return this.textures[ 0 ];
  1835. }
  1836. set texture( value ) {
  1837. this.textures[ 0 ] = value;
  1838. }
  1839. setSize( width, height, depth = 1 ) {
  1840. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1841. this.width = width;
  1842. this.height = height;
  1843. this.depth = depth;
  1844. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1845. this.textures[ i ].image.width = width;
  1846. this.textures[ i ].image.height = height;
  1847. this.textures[ i ].image.depth = depth;
  1848. }
  1849. this.dispose();
  1850. }
  1851. this.viewport.set( 0, 0, width, height );
  1852. this.scissor.set( 0, 0, width, height );
  1853. }
  1854. clone() {
  1855. return new this.constructor().copy( this );
  1856. }
  1857. copy( source ) {
  1858. this.width = source.width;
  1859. this.height = source.height;
  1860. this.depth = source.depth;
  1861. this.scissor.copy( source.scissor );
  1862. this.scissorTest = source.scissorTest;
  1863. this.viewport.copy( source.viewport );
  1864. this.textures.length = 0;
  1865. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1866. this.textures[ i ] = source.textures[ i ].clone();
  1867. this.textures[ i ].isRenderTargetTexture = true;
  1868. }
  1869. // ensure image object is not shared, see #20328
  1870. const image = Object.assign( {}, source.texture.image );
  1871. this.texture.source = new Source( image );
  1872. this.depthBuffer = source.depthBuffer;
  1873. this.stencilBuffer = source.stencilBuffer;
  1874. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1875. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1876. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1877. this.samples = source.samples;
  1878. return this;
  1879. }
  1880. dispose() {
  1881. this.dispatchEvent( { type: 'dispose' } );
  1882. }
  1883. }
  1884. class WebGLRenderTarget extends RenderTarget {
  1885. constructor( width = 1, height = 1, options = {} ) {
  1886. super( width, height, options );
  1887. this.isWebGLRenderTarget = true;
  1888. }
  1889. }
  1890. class DataArrayTexture extends Texture {
  1891. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1892. super( null );
  1893. this.isDataArrayTexture = true;
  1894. this.image = { data, width, height, depth };
  1895. this.magFilter = NearestFilter;
  1896. this.minFilter = NearestFilter;
  1897. this.wrapR = ClampToEdgeWrapping;
  1898. this.generateMipmaps = false;
  1899. this.flipY = false;
  1900. this.unpackAlignment = 1;
  1901. this.layerUpdates = new Set();
  1902. }
  1903. addLayerUpdate( layerIndex ) {
  1904. this.layerUpdates.add( layerIndex );
  1905. }
  1906. clearLayerUpdates() {
  1907. this.layerUpdates.clear();
  1908. }
  1909. }
  1910. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1911. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1912. super( width, height, options );
  1913. this.isWebGLArrayRenderTarget = true;
  1914. this.depth = depth;
  1915. this.texture = new DataArrayTexture( null, width, height, depth );
  1916. this.texture.isRenderTargetTexture = true;
  1917. }
  1918. }
  1919. class Data3DTexture extends Texture {
  1920. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1921. // We're going to add .setXXX() methods for setting properties later.
  1922. // Users can still set in DataTexture3D directly.
  1923. //
  1924. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1925. // texture.anisotropy = 16;
  1926. //
  1927. // See #14839
  1928. super( null );
  1929. this.isData3DTexture = true;
  1930. this.image = { data, width, height, depth };
  1931. this.magFilter = NearestFilter;
  1932. this.minFilter = NearestFilter;
  1933. this.wrapR = ClampToEdgeWrapping;
  1934. this.generateMipmaps = false;
  1935. this.flipY = false;
  1936. this.unpackAlignment = 1;
  1937. }
  1938. }
  1939. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1940. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1941. super( width, height, options );
  1942. this.isWebGL3DRenderTarget = true;
  1943. this.depth = depth;
  1944. this.texture = new Data3DTexture( null, width, height, depth );
  1945. this.texture.isRenderTargetTexture = true;
  1946. }
  1947. }
  1948. class Quaternion {
  1949. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1950. this.isQuaternion = true;
  1951. this._x = x;
  1952. this._y = y;
  1953. this._z = z;
  1954. this._w = w;
  1955. }
  1956. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1957. // fuzz-free, array-based Quaternion SLERP operation
  1958. let x0 = src0[ srcOffset0 + 0 ],
  1959. y0 = src0[ srcOffset0 + 1 ],
  1960. z0 = src0[ srcOffset0 + 2 ],
  1961. w0 = src0[ srcOffset0 + 3 ];
  1962. const x1 = src1[ srcOffset1 + 0 ],
  1963. y1 = src1[ srcOffset1 + 1 ],
  1964. z1 = src1[ srcOffset1 + 2 ],
  1965. w1 = src1[ srcOffset1 + 3 ];
  1966. if ( t === 0 ) {
  1967. dst[ dstOffset + 0 ] = x0;
  1968. dst[ dstOffset + 1 ] = y0;
  1969. dst[ dstOffset + 2 ] = z0;
  1970. dst[ dstOffset + 3 ] = w0;
  1971. return;
  1972. }
  1973. if ( t === 1 ) {
  1974. dst[ dstOffset + 0 ] = x1;
  1975. dst[ dstOffset + 1 ] = y1;
  1976. dst[ dstOffset + 2 ] = z1;
  1977. dst[ dstOffset + 3 ] = w1;
  1978. return;
  1979. }
  1980. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1981. let s = 1 - t;
  1982. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1983. dir = ( cos >= 0 ? 1 : - 1 ),
  1984. sqrSin = 1 - cos * cos;
  1985. // Skip the Slerp for tiny steps to avoid numeric problems:
  1986. if ( sqrSin > Number.EPSILON ) {
  1987. const sin = Math.sqrt( sqrSin ),
  1988. len = Math.atan2( sin, cos * dir );
  1989. s = Math.sin( s * len ) / sin;
  1990. t = Math.sin( t * len ) / sin;
  1991. }
  1992. const tDir = t * dir;
  1993. x0 = x0 * s + x1 * tDir;
  1994. y0 = y0 * s + y1 * tDir;
  1995. z0 = z0 * s + z1 * tDir;
  1996. w0 = w0 * s + w1 * tDir;
  1997. // Normalize in case we just did a lerp:
  1998. if ( s === 1 - t ) {
  1999. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2000. x0 *= f;
  2001. y0 *= f;
  2002. z0 *= f;
  2003. w0 *= f;
  2004. }
  2005. }
  2006. dst[ dstOffset ] = x0;
  2007. dst[ dstOffset + 1 ] = y0;
  2008. dst[ dstOffset + 2 ] = z0;
  2009. dst[ dstOffset + 3 ] = w0;
  2010. }
  2011. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2012. const x0 = src0[ srcOffset0 ];
  2013. const y0 = src0[ srcOffset0 + 1 ];
  2014. const z0 = src0[ srcOffset0 + 2 ];
  2015. const w0 = src0[ srcOffset0 + 3 ];
  2016. const x1 = src1[ srcOffset1 ];
  2017. const y1 = src1[ srcOffset1 + 1 ];
  2018. const z1 = src1[ srcOffset1 + 2 ];
  2019. const w1 = src1[ srcOffset1 + 3 ];
  2020. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2021. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2022. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2023. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2024. return dst;
  2025. }
  2026. get x() {
  2027. return this._x;
  2028. }
  2029. set x( value ) {
  2030. this._x = value;
  2031. this._onChangeCallback();
  2032. }
  2033. get y() {
  2034. return this._y;
  2035. }
  2036. set y( value ) {
  2037. this._y = value;
  2038. this._onChangeCallback();
  2039. }
  2040. get z() {
  2041. return this._z;
  2042. }
  2043. set z( value ) {
  2044. this._z = value;
  2045. this._onChangeCallback();
  2046. }
  2047. get w() {
  2048. return this._w;
  2049. }
  2050. set w( value ) {
  2051. this._w = value;
  2052. this._onChangeCallback();
  2053. }
  2054. set( x, y, z, w ) {
  2055. this._x = x;
  2056. this._y = y;
  2057. this._z = z;
  2058. this._w = w;
  2059. this._onChangeCallback();
  2060. return this;
  2061. }
  2062. clone() {
  2063. return new this.constructor( this._x, this._y, this._z, this._w );
  2064. }
  2065. copy( quaternion ) {
  2066. this._x = quaternion.x;
  2067. this._y = quaternion.y;
  2068. this._z = quaternion.z;
  2069. this._w = quaternion.w;
  2070. this._onChangeCallback();
  2071. return this;
  2072. }
  2073. setFromEuler( euler, update = true ) {
  2074. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2075. // http://www.mathworks.com/matlabcentral/fileexchange/
  2076. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2077. // content/SpinCalc.m
  2078. const cos = Math.cos;
  2079. const sin = Math.sin;
  2080. const c1 = cos( x / 2 );
  2081. const c2 = cos( y / 2 );
  2082. const c3 = cos( z / 2 );
  2083. const s1 = sin( x / 2 );
  2084. const s2 = sin( y / 2 );
  2085. const s3 = sin( z / 2 );
  2086. switch ( order ) {
  2087. case 'XYZ':
  2088. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2089. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2090. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2091. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2092. break;
  2093. case 'YXZ':
  2094. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2095. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2096. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2097. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2098. break;
  2099. case 'ZXY':
  2100. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2101. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2102. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2103. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2104. break;
  2105. case 'ZYX':
  2106. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2107. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2108. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2109. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2110. break;
  2111. case 'YZX':
  2112. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2113. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2114. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2115. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2116. break;
  2117. case 'XZY':
  2118. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2119. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2120. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2121. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2122. break;
  2123. default:
  2124. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2125. }
  2126. if ( update === true ) this._onChangeCallback();
  2127. return this;
  2128. }
  2129. setFromAxisAngle( axis, angle ) {
  2130. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2131. // assumes axis is normalized
  2132. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2133. this._x = axis.x * s;
  2134. this._y = axis.y * s;
  2135. this._z = axis.z * s;
  2136. this._w = Math.cos( halfAngle );
  2137. this._onChangeCallback();
  2138. return this;
  2139. }
  2140. setFromRotationMatrix( m ) {
  2141. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2142. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2143. const te = m.elements,
  2144. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2145. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2146. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2147. trace = m11 + m22 + m33;
  2148. if ( trace > 0 ) {
  2149. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2150. this._w = 0.25 / s;
  2151. this._x = ( m32 - m23 ) * s;
  2152. this._y = ( m13 - m31 ) * s;
  2153. this._z = ( m21 - m12 ) * s;
  2154. } else if ( m11 > m22 && m11 > m33 ) {
  2155. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2156. this._w = ( m32 - m23 ) / s;
  2157. this._x = 0.25 * s;
  2158. this._y = ( m12 + m21 ) / s;
  2159. this._z = ( m13 + m31 ) / s;
  2160. } else if ( m22 > m33 ) {
  2161. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2162. this._w = ( m13 - m31 ) / s;
  2163. this._x = ( m12 + m21 ) / s;
  2164. this._y = 0.25 * s;
  2165. this._z = ( m23 + m32 ) / s;
  2166. } else {
  2167. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2168. this._w = ( m21 - m12 ) / s;
  2169. this._x = ( m13 + m31 ) / s;
  2170. this._y = ( m23 + m32 ) / s;
  2171. this._z = 0.25 * s;
  2172. }
  2173. this._onChangeCallback();
  2174. return this;
  2175. }
  2176. setFromUnitVectors( vFrom, vTo ) {
  2177. // assumes direction vectors vFrom and vTo are normalized
  2178. let r = vFrom.dot( vTo ) + 1;
  2179. if ( r < Number.EPSILON ) {
  2180. // vFrom and vTo point in opposite directions
  2181. r = 0;
  2182. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2183. this._x = - vFrom.y;
  2184. this._y = vFrom.x;
  2185. this._z = 0;
  2186. this._w = r;
  2187. } else {
  2188. this._x = 0;
  2189. this._y = - vFrom.z;
  2190. this._z = vFrom.y;
  2191. this._w = r;
  2192. }
  2193. } else {
  2194. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2195. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2196. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2197. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2198. this._w = r;
  2199. }
  2200. return this.normalize();
  2201. }
  2202. angleTo( q ) {
  2203. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2204. }
  2205. rotateTowards( q, step ) {
  2206. const angle = this.angleTo( q );
  2207. if ( angle === 0 ) return this;
  2208. const t = Math.min( 1, step / angle );
  2209. this.slerp( q, t );
  2210. return this;
  2211. }
  2212. identity() {
  2213. return this.set( 0, 0, 0, 1 );
  2214. }
  2215. invert() {
  2216. // quaternion is assumed to have unit length
  2217. return this.conjugate();
  2218. }
  2219. conjugate() {
  2220. this._x *= - 1;
  2221. this._y *= - 1;
  2222. this._z *= - 1;
  2223. this._onChangeCallback();
  2224. return this;
  2225. }
  2226. dot( v ) {
  2227. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2228. }
  2229. lengthSq() {
  2230. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2231. }
  2232. length() {
  2233. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2234. }
  2235. normalize() {
  2236. let l = this.length();
  2237. if ( l === 0 ) {
  2238. this._x = 0;
  2239. this._y = 0;
  2240. this._z = 0;
  2241. this._w = 1;
  2242. } else {
  2243. l = 1 / l;
  2244. this._x = this._x * l;
  2245. this._y = this._y * l;
  2246. this._z = this._z * l;
  2247. this._w = this._w * l;
  2248. }
  2249. this._onChangeCallback();
  2250. return this;
  2251. }
  2252. multiply( q ) {
  2253. return this.multiplyQuaternions( this, q );
  2254. }
  2255. premultiply( q ) {
  2256. return this.multiplyQuaternions( q, this );
  2257. }
  2258. multiplyQuaternions( a, b ) {
  2259. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2260. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2261. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2262. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2263. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2264. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2265. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2266. this._onChangeCallback();
  2267. return this;
  2268. }
  2269. slerp( qb, t ) {
  2270. if ( t === 0 ) return this;
  2271. if ( t === 1 ) return this.copy( qb );
  2272. const x = this._x, y = this._y, z = this._z, w = this._w;
  2273. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2274. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2275. if ( cosHalfTheta < 0 ) {
  2276. this._w = - qb._w;
  2277. this._x = - qb._x;
  2278. this._y = - qb._y;
  2279. this._z = - qb._z;
  2280. cosHalfTheta = - cosHalfTheta;
  2281. } else {
  2282. this.copy( qb );
  2283. }
  2284. if ( cosHalfTheta >= 1.0 ) {
  2285. this._w = w;
  2286. this._x = x;
  2287. this._y = y;
  2288. this._z = z;
  2289. return this;
  2290. }
  2291. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2292. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2293. const s = 1 - t;
  2294. this._w = s * w + t * this._w;
  2295. this._x = s * x + t * this._x;
  2296. this._y = s * y + t * this._y;
  2297. this._z = s * z + t * this._z;
  2298. this.normalize(); // normalize calls _onChangeCallback()
  2299. return this;
  2300. }
  2301. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2302. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2303. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2304. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2305. this._w = ( w * ratioA + this._w * ratioB );
  2306. this._x = ( x * ratioA + this._x * ratioB );
  2307. this._y = ( y * ratioA + this._y * ratioB );
  2308. this._z = ( z * ratioA + this._z * ratioB );
  2309. this._onChangeCallback();
  2310. return this;
  2311. }
  2312. slerpQuaternions( qa, qb, t ) {
  2313. return this.copy( qa ).slerp( qb, t );
  2314. }
  2315. random() {
  2316. // sets this quaternion to a uniform random unit quaternnion
  2317. // Ken Shoemake
  2318. // Uniform random rotations
  2319. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2320. const theta1 = 2 * Math.PI * Math.random();
  2321. const theta2 = 2 * Math.PI * Math.random();
  2322. const x0 = Math.random();
  2323. const r1 = Math.sqrt( 1 - x0 );
  2324. const r2 = Math.sqrt( x0 );
  2325. return this.set(
  2326. r1 * Math.sin( theta1 ),
  2327. r1 * Math.cos( theta1 ),
  2328. r2 * Math.sin( theta2 ),
  2329. r2 * Math.cos( theta2 ),
  2330. );
  2331. }
  2332. equals( quaternion ) {
  2333. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2334. }
  2335. fromArray( array, offset = 0 ) {
  2336. this._x = array[ offset ];
  2337. this._y = array[ offset + 1 ];
  2338. this._z = array[ offset + 2 ];
  2339. this._w = array[ offset + 3 ];
  2340. this._onChangeCallback();
  2341. return this;
  2342. }
  2343. toArray( array = [], offset = 0 ) {
  2344. array[ offset ] = this._x;
  2345. array[ offset + 1 ] = this._y;
  2346. array[ offset + 2 ] = this._z;
  2347. array[ offset + 3 ] = this._w;
  2348. return array;
  2349. }
  2350. fromBufferAttribute( attribute, index ) {
  2351. this._x = attribute.getX( index );
  2352. this._y = attribute.getY( index );
  2353. this._z = attribute.getZ( index );
  2354. this._w = attribute.getW( index );
  2355. this._onChangeCallback();
  2356. return this;
  2357. }
  2358. toJSON() {
  2359. return this.toArray();
  2360. }
  2361. _onChange( callback ) {
  2362. this._onChangeCallback = callback;
  2363. return this;
  2364. }
  2365. _onChangeCallback() {}
  2366. *[ Symbol.iterator ]() {
  2367. yield this._x;
  2368. yield this._y;
  2369. yield this._z;
  2370. yield this._w;
  2371. }
  2372. }
  2373. class Vector3 {
  2374. constructor( x = 0, y = 0, z = 0 ) {
  2375. Vector3.prototype.isVector3 = true;
  2376. this.x = x;
  2377. this.y = y;
  2378. this.z = z;
  2379. }
  2380. set( x, y, z ) {
  2381. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2382. this.x = x;
  2383. this.y = y;
  2384. this.z = z;
  2385. return this;
  2386. }
  2387. setScalar( scalar ) {
  2388. this.x = scalar;
  2389. this.y = scalar;
  2390. this.z = scalar;
  2391. return this;
  2392. }
  2393. setX( x ) {
  2394. this.x = x;
  2395. return this;
  2396. }
  2397. setY( y ) {
  2398. this.y = y;
  2399. return this;
  2400. }
  2401. setZ( z ) {
  2402. this.z = z;
  2403. return this;
  2404. }
  2405. setComponent( index, value ) {
  2406. switch ( index ) {
  2407. case 0: this.x = value; break;
  2408. case 1: this.y = value; break;
  2409. case 2: this.z = value; break;
  2410. default: throw new Error( 'index is out of range: ' + index );
  2411. }
  2412. return this;
  2413. }
  2414. getComponent( index ) {
  2415. switch ( index ) {
  2416. case 0: return this.x;
  2417. case 1: return this.y;
  2418. case 2: return this.z;
  2419. default: throw new Error( 'index is out of range: ' + index );
  2420. }
  2421. }
  2422. clone() {
  2423. return new this.constructor( this.x, this.y, this.z );
  2424. }
  2425. copy( v ) {
  2426. this.x = v.x;
  2427. this.y = v.y;
  2428. this.z = v.z;
  2429. return this;
  2430. }
  2431. add( v ) {
  2432. this.x += v.x;
  2433. this.y += v.y;
  2434. this.z += v.z;
  2435. return this;
  2436. }
  2437. addScalar( s ) {
  2438. this.x += s;
  2439. this.y += s;
  2440. this.z += s;
  2441. return this;
  2442. }
  2443. addVectors( a, b ) {
  2444. this.x = a.x + b.x;
  2445. this.y = a.y + b.y;
  2446. this.z = a.z + b.z;
  2447. return this;
  2448. }
  2449. addScaledVector( v, s ) {
  2450. this.x += v.x * s;
  2451. this.y += v.y * s;
  2452. this.z += v.z * s;
  2453. return this;
  2454. }
  2455. sub( v ) {
  2456. this.x -= v.x;
  2457. this.y -= v.y;
  2458. this.z -= v.z;
  2459. return this;
  2460. }
  2461. subScalar( s ) {
  2462. this.x -= s;
  2463. this.y -= s;
  2464. this.z -= s;
  2465. return this;
  2466. }
  2467. subVectors( a, b ) {
  2468. this.x = a.x - b.x;
  2469. this.y = a.y - b.y;
  2470. this.z = a.z - b.z;
  2471. return this;
  2472. }
  2473. multiply( v ) {
  2474. this.x *= v.x;
  2475. this.y *= v.y;
  2476. this.z *= v.z;
  2477. return this;
  2478. }
  2479. multiplyScalar( scalar ) {
  2480. this.x *= scalar;
  2481. this.y *= scalar;
  2482. this.z *= scalar;
  2483. return this;
  2484. }
  2485. multiplyVectors( a, b ) {
  2486. this.x = a.x * b.x;
  2487. this.y = a.y * b.y;
  2488. this.z = a.z * b.z;
  2489. return this;
  2490. }
  2491. applyEuler( euler ) {
  2492. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2493. }
  2494. applyAxisAngle( axis, angle ) {
  2495. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2496. }
  2497. applyMatrix3( m ) {
  2498. const x = this.x, y = this.y, z = this.z;
  2499. const e = m.elements;
  2500. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2501. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2502. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2503. return this;
  2504. }
  2505. applyNormalMatrix( m ) {
  2506. return this.applyMatrix3( m ).normalize();
  2507. }
  2508. applyMatrix4( m ) {
  2509. const x = this.x, y = this.y, z = this.z;
  2510. const e = m.elements;
  2511. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2512. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2513. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2514. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2515. return this;
  2516. }
  2517. applyQuaternion( q ) {
  2518. // quaternion q is assumed to have unit length
  2519. const vx = this.x, vy = this.y, vz = this.z;
  2520. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2521. // t = 2 * cross( q.xyz, v );
  2522. const tx = 2 * ( qy * vz - qz * vy );
  2523. const ty = 2 * ( qz * vx - qx * vz );
  2524. const tz = 2 * ( qx * vy - qy * vx );
  2525. // v + q.w * t + cross( q.xyz, t );
  2526. this.x = vx + qw * tx + qy * tz - qz * ty;
  2527. this.y = vy + qw * ty + qz * tx - qx * tz;
  2528. this.z = vz + qw * tz + qx * ty - qy * tx;
  2529. return this;
  2530. }
  2531. project( camera ) {
  2532. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2533. }
  2534. unproject( camera ) {
  2535. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2536. }
  2537. transformDirection( m ) {
  2538. // input: THREE.Matrix4 affine matrix
  2539. // vector interpreted as a direction
  2540. const x = this.x, y = this.y, z = this.z;
  2541. const e = m.elements;
  2542. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2543. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2544. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2545. return this.normalize();
  2546. }
  2547. divide( v ) {
  2548. this.x /= v.x;
  2549. this.y /= v.y;
  2550. this.z /= v.z;
  2551. return this;
  2552. }
  2553. divideScalar( scalar ) {
  2554. return this.multiplyScalar( 1 / scalar );
  2555. }
  2556. min( v ) {
  2557. this.x = Math.min( this.x, v.x );
  2558. this.y = Math.min( this.y, v.y );
  2559. this.z = Math.min( this.z, v.z );
  2560. return this;
  2561. }
  2562. max( v ) {
  2563. this.x = Math.max( this.x, v.x );
  2564. this.y = Math.max( this.y, v.y );
  2565. this.z = Math.max( this.z, v.z );
  2566. return this;
  2567. }
  2568. clamp( min, max ) {
  2569. // assumes min < max, componentwise
  2570. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2571. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2572. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2573. return this;
  2574. }
  2575. clampScalar( minVal, maxVal ) {
  2576. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2577. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2578. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2579. return this;
  2580. }
  2581. clampLength( min, max ) {
  2582. const length = this.length();
  2583. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2584. }
  2585. floor() {
  2586. this.x = Math.floor( this.x );
  2587. this.y = Math.floor( this.y );
  2588. this.z = Math.floor( this.z );
  2589. return this;
  2590. }
  2591. ceil() {
  2592. this.x = Math.ceil( this.x );
  2593. this.y = Math.ceil( this.y );
  2594. this.z = Math.ceil( this.z );
  2595. return this;
  2596. }
  2597. round() {
  2598. this.x = Math.round( this.x );
  2599. this.y = Math.round( this.y );
  2600. this.z = Math.round( this.z );
  2601. return this;
  2602. }
  2603. roundToZero() {
  2604. this.x = Math.trunc( this.x );
  2605. this.y = Math.trunc( this.y );
  2606. this.z = Math.trunc( this.z );
  2607. return this;
  2608. }
  2609. negate() {
  2610. this.x = - this.x;
  2611. this.y = - this.y;
  2612. this.z = - this.z;
  2613. return this;
  2614. }
  2615. dot( v ) {
  2616. return this.x * v.x + this.y * v.y + this.z * v.z;
  2617. }
  2618. // TODO lengthSquared?
  2619. lengthSq() {
  2620. return this.x * this.x + this.y * this.y + this.z * this.z;
  2621. }
  2622. length() {
  2623. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2624. }
  2625. manhattanLength() {
  2626. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2627. }
  2628. normalize() {
  2629. return this.divideScalar( this.length() || 1 );
  2630. }
  2631. setLength( length ) {
  2632. return this.normalize().multiplyScalar( length );
  2633. }
  2634. lerp( v, alpha ) {
  2635. this.x += ( v.x - this.x ) * alpha;
  2636. this.y += ( v.y - this.y ) * alpha;
  2637. this.z += ( v.z - this.z ) * alpha;
  2638. return this;
  2639. }
  2640. lerpVectors( v1, v2, alpha ) {
  2641. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2642. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2643. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2644. return this;
  2645. }
  2646. cross( v ) {
  2647. return this.crossVectors( this, v );
  2648. }
  2649. crossVectors( a, b ) {
  2650. const ax = a.x, ay = a.y, az = a.z;
  2651. const bx = b.x, by = b.y, bz = b.z;
  2652. this.x = ay * bz - az * by;
  2653. this.y = az * bx - ax * bz;
  2654. this.z = ax * by - ay * bx;
  2655. return this;
  2656. }
  2657. projectOnVector( v ) {
  2658. const denominator = v.lengthSq();
  2659. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2660. const scalar = v.dot( this ) / denominator;
  2661. return this.copy( v ).multiplyScalar( scalar );
  2662. }
  2663. projectOnPlane( planeNormal ) {
  2664. _vector$c.copy( this ).projectOnVector( planeNormal );
  2665. return this.sub( _vector$c );
  2666. }
  2667. reflect( normal ) {
  2668. // reflect incident vector off plane orthogonal to normal
  2669. // normal is assumed to have unit length
  2670. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2671. }
  2672. angleTo( v ) {
  2673. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2674. if ( denominator === 0 ) return Math.PI / 2;
  2675. const theta = this.dot( v ) / denominator;
  2676. // clamp, to handle numerical problems
  2677. return Math.acos( clamp( theta, - 1, 1 ) );
  2678. }
  2679. distanceTo( v ) {
  2680. return Math.sqrt( this.distanceToSquared( v ) );
  2681. }
  2682. distanceToSquared( v ) {
  2683. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2684. return dx * dx + dy * dy + dz * dz;
  2685. }
  2686. manhattanDistanceTo( v ) {
  2687. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2688. }
  2689. setFromSpherical( s ) {
  2690. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2691. }
  2692. setFromSphericalCoords( radius, phi, theta ) {
  2693. const sinPhiRadius = Math.sin( phi ) * radius;
  2694. this.x = sinPhiRadius * Math.sin( theta );
  2695. this.y = Math.cos( phi ) * radius;
  2696. this.z = sinPhiRadius * Math.cos( theta );
  2697. return this;
  2698. }
  2699. setFromCylindrical( c ) {
  2700. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2701. }
  2702. setFromCylindricalCoords( radius, theta, y ) {
  2703. this.x = radius * Math.sin( theta );
  2704. this.y = y;
  2705. this.z = radius * Math.cos( theta );
  2706. return this;
  2707. }
  2708. setFromMatrixPosition( m ) {
  2709. const e = m.elements;
  2710. this.x = e[ 12 ];
  2711. this.y = e[ 13 ];
  2712. this.z = e[ 14 ];
  2713. return this;
  2714. }
  2715. setFromMatrixScale( m ) {
  2716. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2717. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2718. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2719. this.x = sx;
  2720. this.y = sy;
  2721. this.z = sz;
  2722. return this;
  2723. }
  2724. setFromMatrixColumn( m, index ) {
  2725. return this.fromArray( m.elements, index * 4 );
  2726. }
  2727. setFromMatrix3Column( m, index ) {
  2728. return this.fromArray( m.elements, index * 3 );
  2729. }
  2730. setFromEuler( e ) {
  2731. this.x = e._x;
  2732. this.y = e._y;
  2733. this.z = e._z;
  2734. return this;
  2735. }
  2736. setFromColor( c ) {
  2737. this.x = c.r;
  2738. this.y = c.g;
  2739. this.z = c.b;
  2740. return this;
  2741. }
  2742. equals( v ) {
  2743. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2744. }
  2745. fromArray( array, offset = 0 ) {
  2746. this.x = array[ offset ];
  2747. this.y = array[ offset + 1 ];
  2748. this.z = array[ offset + 2 ];
  2749. return this;
  2750. }
  2751. toArray( array = [], offset = 0 ) {
  2752. array[ offset ] = this.x;
  2753. array[ offset + 1 ] = this.y;
  2754. array[ offset + 2 ] = this.z;
  2755. return array;
  2756. }
  2757. fromBufferAttribute( attribute, index ) {
  2758. this.x = attribute.getX( index );
  2759. this.y = attribute.getY( index );
  2760. this.z = attribute.getZ( index );
  2761. return this;
  2762. }
  2763. random() {
  2764. this.x = Math.random();
  2765. this.y = Math.random();
  2766. this.z = Math.random();
  2767. return this;
  2768. }
  2769. randomDirection() {
  2770. // https://mathworld.wolfram.com/SpherePointPicking.html
  2771. const theta = Math.random() * Math.PI * 2;
  2772. const u = Math.random() * 2 - 1;
  2773. const c = Math.sqrt( 1 - u * u );
  2774. this.x = c * Math.cos( theta );
  2775. this.y = u;
  2776. this.z = c * Math.sin( theta );
  2777. return this;
  2778. }
  2779. *[ Symbol.iterator ]() {
  2780. yield this.x;
  2781. yield this.y;
  2782. yield this.z;
  2783. }
  2784. }
  2785. const _vector$c = /*@__PURE__*/ new Vector3();
  2786. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2787. class Box3 {
  2788. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2789. this.isBox3 = true;
  2790. this.min = min;
  2791. this.max = max;
  2792. }
  2793. set( min, max ) {
  2794. this.min.copy( min );
  2795. this.max.copy( max );
  2796. return this;
  2797. }
  2798. setFromArray( array ) {
  2799. this.makeEmpty();
  2800. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2801. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2802. }
  2803. return this;
  2804. }
  2805. setFromBufferAttribute( attribute ) {
  2806. this.makeEmpty();
  2807. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2808. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2809. }
  2810. return this;
  2811. }
  2812. setFromPoints( points ) {
  2813. this.makeEmpty();
  2814. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2815. this.expandByPoint( points[ i ] );
  2816. }
  2817. return this;
  2818. }
  2819. setFromCenterAndSize( center, size ) {
  2820. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2821. this.min.copy( center ).sub( halfSize );
  2822. this.max.copy( center ).add( halfSize );
  2823. return this;
  2824. }
  2825. setFromObject( object, precise = false ) {
  2826. this.makeEmpty();
  2827. return this.expandByObject( object, precise );
  2828. }
  2829. clone() {
  2830. return new this.constructor().copy( this );
  2831. }
  2832. copy( box ) {
  2833. this.min.copy( box.min );
  2834. this.max.copy( box.max );
  2835. return this;
  2836. }
  2837. makeEmpty() {
  2838. this.min.x = this.min.y = this.min.z = + Infinity;
  2839. this.max.x = this.max.y = this.max.z = - Infinity;
  2840. return this;
  2841. }
  2842. isEmpty() {
  2843. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2844. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2845. }
  2846. getCenter( target ) {
  2847. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2848. }
  2849. getSize( target ) {
  2850. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2851. }
  2852. expandByPoint( point ) {
  2853. this.min.min( point );
  2854. this.max.max( point );
  2855. return this;
  2856. }
  2857. expandByVector( vector ) {
  2858. this.min.sub( vector );
  2859. this.max.add( vector );
  2860. return this;
  2861. }
  2862. expandByScalar( scalar ) {
  2863. this.min.addScalar( - scalar );
  2864. this.max.addScalar( scalar );
  2865. return this;
  2866. }
  2867. expandByObject( object, precise = false ) {
  2868. // Computes the world-axis-aligned bounding box of an object (including its children),
  2869. // accounting for both the object's, and children's, world transforms
  2870. object.updateWorldMatrix( false, false );
  2871. const geometry = object.geometry;
  2872. if ( geometry !== undefined ) {
  2873. const positionAttribute = geometry.getAttribute( 'position' );
  2874. // precise AABB computation based on vertex data requires at least a position attribute.
  2875. // instancing isn't supported so far and uses the normal (conservative) code path.
  2876. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2877. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2878. if ( object.isMesh === true ) {
  2879. object.getVertexPosition( i, _vector$b );
  2880. } else {
  2881. _vector$b.fromBufferAttribute( positionAttribute, i );
  2882. }
  2883. _vector$b.applyMatrix4( object.matrixWorld );
  2884. this.expandByPoint( _vector$b );
  2885. }
  2886. } else {
  2887. if ( object.boundingBox !== undefined ) {
  2888. // object-level bounding box
  2889. if ( object.boundingBox === null ) {
  2890. object.computeBoundingBox();
  2891. }
  2892. _box$4.copy( object.boundingBox );
  2893. } else {
  2894. // geometry-level bounding box
  2895. if ( geometry.boundingBox === null ) {
  2896. geometry.computeBoundingBox();
  2897. }
  2898. _box$4.copy( geometry.boundingBox );
  2899. }
  2900. _box$4.applyMatrix4( object.matrixWorld );
  2901. this.union( _box$4 );
  2902. }
  2903. }
  2904. const children = object.children;
  2905. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2906. this.expandByObject( children[ i ], precise );
  2907. }
  2908. return this;
  2909. }
  2910. containsPoint( point ) {
  2911. return point.x < this.min.x || point.x > this.max.x ||
  2912. point.y < this.min.y || point.y > this.max.y ||
  2913. point.z < this.min.z || point.z > this.max.z ? false : true;
  2914. }
  2915. containsBox( box ) {
  2916. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2917. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2918. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2919. }
  2920. getParameter( point, target ) {
  2921. // This can potentially have a divide by zero if the box
  2922. // has a size dimension of 0.
  2923. return target.set(
  2924. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2925. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2926. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2927. );
  2928. }
  2929. intersectsBox( box ) {
  2930. // using 6 splitting planes to rule out intersections.
  2931. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2932. box.max.y < this.min.y || box.min.y > this.max.y ||
  2933. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2934. }
  2935. intersectsSphere( sphere ) {
  2936. // Find the point on the AABB closest to the sphere center.
  2937. this.clampPoint( sphere.center, _vector$b );
  2938. // If that point is inside the sphere, the AABB and sphere intersect.
  2939. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2940. }
  2941. intersectsPlane( plane ) {
  2942. // We compute the minimum and maximum dot product values. If those values
  2943. // are on the same side (back or front) of the plane, then there is no intersection.
  2944. let min, max;
  2945. if ( plane.normal.x > 0 ) {
  2946. min = plane.normal.x * this.min.x;
  2947. max = plane.normal.x * this.max.x;
  2948. } else {
  2949. min = plane.normal.x * this.max.x;
  2950. max = plane.normal.x * this.min.x;
  2951. }
  2952. if ( plane.normal.y > 0 ) {
  2953. min += plane.normal.y * this.min.y;
  2954. max += plane.normal.y * this.max.y;
  2955. } else {
  2956. min += plane.normal.y * this.max.y;
  2957. max += plane.normal.y * this.min.y;
  2958. }
  2959. if ( plane.normal.z > 0 ) {
  2960. min += plane.normal.z * this.min.z;
  2961. max += plane.normal.z * this.max.z;
  2962. } else {
  2963. min += plane.normal.z * this.max.z;
  2964. max += plane.normal.z * this.min.z;
  2965. }
  2966. return ( min <= - plane.constant && max >= - plane.constant );
  2967. }
  2968. intersectsTriangle( triangle ) {
  2969. if ( this.isEmpty() ) {
  2970. return false;
  2971. }
  2972. // compute box center and extents
  2973. this.getCenter( _center );
  2974. _extents.subVectors( this.max, _center );
  2975. // translate triangle to aabb origin
  2976. _v0$2.subVectors( triangle.a, _center );
  2977. _v1$7.subVectors( triangle.b, _center );
  2978. _v2$4.subVectors( triangle.c, _center );
  2979. // compute edge vectors for triangle
  2980. _f0.subVectors( _v1$7, _v0$2 );
  2981. _f1.subVectors( _v2$4, _v1$7 );
  2982. _f2.subVectors( _v0$2, _v2$4 );
  2983. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2984. // 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
  2985. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2986. let axes = [
  2987. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2988. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2989. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2990. ];
  2991. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2992. return false;
  2993. }
  2994. // test 3 face normals from the aabb
  2995. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2996. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2997. return false;
  2998. }
  2999. // finally testing the face normal of the triangle
  3000. // use already existing triangle edge vectors here
  3001. _triangleNormal.crossVectors( _f0, _f1 );
  3002. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3003. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3004. }
  3005. clampPoint( point, target ) {
  3006. return target.copy( point ).clamp( this.min, this.max );
  3007. }
  3008. distanceToPoint( point ) {
  3009. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3010. }
  3011. getBoundingSphere( target ) {
  3012. if ( this.isEmpty() ) {
  3013. target.makeEmpty();
  3014. } else {
  3015. this.getCenter( target.center );
  3016. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3017. }
  3018. return target;
  3019. }
  3020. intersect( box ) {
  3021. this.min.max( box.min );
  3022. this.max.min( box.max );
  3023. // 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.
  3024. if ( this.isEmpty() ) this.makeEmpty();
  3025. return this;
  3026. }
  3027. union( box ) {
  3028. this.min.min( box.min );
  3029. this.max.max( box.max );
  3030. return this;
  3031. }
  3032. applyMatrix4( matrix ) {
  3033. // transform of empty box is an empty box.
  3034. if ( this.isEmpty() ) return this;
  3035. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3036. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3037. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3038. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3039. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3040. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3041. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3042. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3043. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3044. this.setFromPoints( _points );
  3045. return this;
  3046. }
  3047. translate( offset ) {
  3048. this.min.add( offset );
  3049. this.max.add( offset );
  3050. return this;
  3051. }
  3052. equals( box ) {
  3053. return box.min.equals( this.min ) && box.max.equals( this.max );
  3054. }
  3055. }
  3056. const _points = [
  3057. /*@__PURE__*/ new Vector3(),
  3058. /*@__PURE__*/ new Vector3(),
  3059. /*@__PURE__*/ new Vector3(),
  3060. /*@__PURE__*/ new Vector3(),
  3061. /*@__PURE__*/ new Vector3(),
  3062. /*@__PURE__*/ new Vector3(),
  3063. /*@__PURE__*/ new Vector3(),
  3064. /*@__PURE__*/ new Vector3()
  3065. ];
  3066. const _vector$b = /*@__PURE__*/ new Vector3();
  3067. const _box$4 = /*@__PURE__*/ new Box3();
  3068. // triangle centered vertices
  3069. const _v0$2 = /*@__PURE__*/ new Vector3();
  3070. const _v1$7 = /*@__PURE__*/ new Vector3();
  3071. const _v2$4 = /*@__PURE__*/ new Vector3();
  3072. // triangle edge vectors
  3073. const _f0 = /*@__PURE__*/ new Vector3();
  3074. const _f1 = /*@__PURE__*/ new Vector3();
  3075. const _f2 = /*@__PURE__*/ new Vector3();
  3076. const _center = /*@__PURE__*/ new Vector3();
  3077. const _extents = /*@__PURE__*/ new Vector3();
  3078. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3079. const _testAxis = /*@__PURE__*/ new Vector3();
  3080. function satForAxes( axes, v0, v1, v2, extents ) {
  3081. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3082. _testAxis.fromArray( axes, i );
  3083. // project the aabb onto the separating axis
  3084. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3085. // project all 3 vertices of the triangle onto the separating axis
  3086. const p0 = v0.dot( _testAxis );
  3087. const p1 = v1.dot( _testAxis );
  3088. const p2 = v2.dot( _testAxis );
  3089. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3090. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3091. // points of the projected triangle are outside the projected half-length of the aabb
  3092. // the axis is separating and we can exit
  3093. return false;
  3094. }
  3095. }
  3096. return true;
  3097. }
  3098. const _box$3 = /*@__PURE__*/ new Box3();
  3099. const _v1$6 = /*@__PURE__*/ new Vector3();
  3100. const _v2$3 = /*@__PURE__*/ new Vector3();
  3101. class Sphere {
  3102. constructor( center = new Vector3(), radius = - 1 ) {
  3103. this.isSphere = true;
  3104. this.center = center;
  3105. this.radius = radius;
  3106. }
  3107. set( center, radius ) {
  3108. this.center.copy( center );
  3109. this.radius = radius;
  3110. return this;
  3111. }
  3112. setFromPoints( points, optionalCenter ) {
  3113. const center = this.center;
  3114. if ( optionalCenter !== undefined ) {
  3115. center.copy( optionalCenter );
  3116. } else {
  3117. _box$3.setFromPoints( points ).getCenter( center );
  3118. }
  3119. let maxRadiusSq = 0;
  3120. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3121. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3122. }
  3123. this.radius = Math.sqrt( maxRadiusSq );
  3124. return this;
  3125. }
  3126. copy( sphere ) {
  3127. this.center.copy( sphere.center );
  3128. this.radius = sphere.radius;
  3129. return this;
  3130. }
  3131. isEmpty() {
  3132. return ( this.radius < 0 );
  3133. }
  3134. makeEmpty() {
  3135. this.center.set( 0, 0, 0 );
  3136. this.radius = - 1;
  3137. return this;
  3138. }
  3139. containsPoint( point ) {
  3140. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3141. }
  3142. distanceToPoint( point ) {
  3143. return ( point.distanceTo( this.center ) - this.radius );
  3144. }
  3145. intersectsSphere( sphere ) {
  3146. const radiusSum = this.radius + sphere.radius;
  3147. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3148. }
  3149. intersectsBox( box ) {
  3150. return box.intersectsSphere( this );
  3151. }
  3152. intersectsPlane( plane ) {
  3153. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3154. }
  3155. clampPoint( point, target ) {
  3156. const deltaLengthSq = this.center.distanceToSquared( point );
  3157. target.copy( point );
  3158. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3159. target.sub( this.center ).normalize();
  3160. target.multiplyScalar( this.radius ).add( this.center );
  3161. }
  3162. return target;
  3163. }
  3164. getBoundingBox( target ) {
  3165. if ( this.isEmpty() ) {
  3166. // Empty sphere produces empty bounding box
  3167. target.makeEmpty();
  3168. return target;
  3169. }
  3170. target.set( this.center, this.center );
  3171. target.expandByScalar( this.radius );
  3172. return target;
  3173. }
  3174. applyMatrix4( matrix ) {
  3175. this.center.applyMatrix4( matrix );
  3176. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3177. return this;
  3178. }
  3179. translate( offset ) {
  3180. this.center.add( offset );
  3181. return this;
  3182. }
  3183. expandByPoint( point ) {
  3184. if ( this.isEmpty() ) {
  3185. this.center.copy( point );
  3186. this.radius = 0;
  3187. return this;
  3188. }
  3189. _v1$6.subVectors( point, this.center );
  3190. const lengthSq = _v1$6.lengthSq();
  3191. if ( lengthSq > ( this.radius * this.radius ) ) {
  3192. // calculate the minimal sphere
  3193. const length = Math.sqrt( lengthSq );
  3194. const delta = ( length - this.radius ) * 0.5;
  3195. this.center.addScaledVector( _v1$6, delta / length );
  3196. this.radius += delta;
  3197. }
  3198. return this;
  3199. }
  3200. union( sphere ) {
  3201. if ( sphere.isEmpty() ) {
  3202. return this;
  3203. }
  3204. if ( this.isEmpty() ) {
  3205. this.copy( sphere );
  3206. return this;
  3207. }
  3208. if ( this.center.equals( sphere.center ) === true ) {
  3209. this.radius = Math.max( this.radius, sphere.radius );
  3210. } else {
  3211. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3212. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3213. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3214. }
  3215. return this;
  3216. }
  3217. equals( sphere ) {
  3218. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3219. }
  3220. clone() {
  3221. return new this.constructor().copy( this );
  3222. }
  3223. }
  3224. const _vector$a = /*@__PURE__*/ new Vector3();
  3225. const _segCenter = /*@__PURE__*/ new Vector3();
  3226. const _segDir = /*@__PURE__*/ new Vector3();
  3227. const _diff = /*@__PURE__*/ new Vector3();
  3228. const _edge1 = /*@__PURE__*/ new Vector3();
  3229. const _edge2 = /*@__PURE__*/ new Vector3();
  3230. const _normal$1 = /*@__PURE__*/ new Vector3();
  3231. class Ray {
  3232. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3233. this.origin = origin;
  3234. this.direction = direction;
  3235. }
  3236. set( origin, direction ) {
  3237. this.origin.copy( origin );
  3238. this.direction.copy( direction );
  3239. return this;
  3240. }
  3241. copy( ray ) {
  3242. this.origin.copy( ray.origin );
  3243. this.direction.copy( ray.direction );
  3244. return this;
  3245. }
  3246. at( t, target ) {
  3247. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3248. }
  3249. lookAt( v ) {
  3250. this.direction.copy( v ).sub( this.origin ).normalize();
  3251. return this;
  3252. }
  3253. recast( t ) {
  3254. this.origin.copy( this.at( t, _vector$a ) );
  3255. return this;
  3256. }
  3257. closestPointToPoint( point, target ) {
  3258. target.subVectors( point, this.origin );
  3259. const directionDistance = target.dot( this.direction );
  3260. if ( directionDistance < 0 ) {
  3261. return target.copy( this.origin );
  3262. }
  3263. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3264. }
  3265. distanceToPoint( point ) {
  3266. return Math.sqrt( this.distanceSqToPoint( point ) );
  3267. }
  3268. distanceSqToPoint( point ) {
  3269. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3270. // point behind the ray
  3271. if ( directionDistance < 0 ) {
  3272. return this.origin.distanceToSquared( point );
  3273. }
  3274. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3275. return _vector$a.distanceToSquared( point );
  3276. }
  3277. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3278. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3279. // It returns the min distance between the ray and the segment
  3280. // defined by v0 and v1
  3281. // It can also set two optional targets :
  3282. // - The closest point on the ray
  3283. // - The closest point on the segment
  3284. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3285. _segDir.copy( v1 ).sub( v0 ).normalize();
  3286. _diff.copy( this.origin ).sub( _segCenter );
  3287. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3288. const a01 = - this.direction.dot( _segDir );
  3289. const b0 = _diff.dot( this.direction );
  3290. const b1 = - _diff.dot( _segDir );
  3291. const c = _diff.lengthSq();
  3292. const det = Math.abs( 1 - a01 * a01 );
  3293. let s0, s1, sqrDist, extDet;
  3294. if ( det > 0 ) {
  3295. // The ray and segment are not parallel.
  3296. s0 = a01 * b1 - b0;
  3297. s1 = a01 * b0 - b1;
  3298. extDet = segExtent * det;
  3299. if ( s0 >= 0 ) {
  3300. if ( s1 >= - extDet ) {
  3301. if ( s1 <= extDet ) {
  3302. // region 0
  3303. // Minimum at interior points of ray and segment.
  3304. const invDet = 1 / det;
  3305. s0 *= invDet;
  3306. s1 *= invDet;
  3307. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3308. } else {
  3309. // region 1
  3310. s1 = segExtent;
  3311. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3312. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3313. }
  3314. } else {
  3315. // region 5
  3316. s1 = - segExtent;
  3317. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3318. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3319. }
  3320. } else {
  3321. if ( s1 <= - extDet ) {
  3322. // region 4
  3323. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3324. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3325. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3326. } else if ( s1 <= extDet ) {
  3327. // region 3
  3328. s0 = 0;
  3329. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3330. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3331. } else {
  3332. // region 2
  3333. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3334. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3335. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3336. }
  3337. }
  3338. } else {
  3339. // Ray and segment are parallel.
  3340. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3341. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3342. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3343. }
  3344. if ( optionalPointOnRay ) {
  3345. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3346. }
  3347. if ( optionalPointOnSegment ) {
  3348. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3349. }
  3350. return sqrDist;
  3351. }
  3352. intersectSphere( sphere, target ) {
  3353. _vector$a.subVectors( sphere.center, this.origin );
  3354. const tca = _vector$a.dot( this.direction );
  3355. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3356. const radius2 = sphere.radius * sphere.radius;
  3357. if ( d2 > radius2 ) return null;
  3358. const thc = Math.sqrt( radius2 - d2 );
  3359. // t0 = first intersect point - entrance on front of sphere
  3360. const t0 = tca - thc;
  3361. // t1 = second intersect point - exit point on back of sphere
  3362. const t1 = tca + thc;
  3363. // test to see if t1 is behind the ray - if so, return null
  3364. if ( t1 < 0 ) return null;
  3365. // test to see if t0 is behind the ray:
  3366. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3367. // in order to always return an intersect point that is in front of the ray.
  3368. if ( t0 < 0 ) return this.at( t1, target );
  3369. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3370. return this.at( t0, target );
  3371. }
  3372. intersectsSphere( sphere ) {
  3373. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3374. }
  3375. distanceToPlane( plane ) {
  3376. const denominator = plane.normal.dot( this.direction );
  3377. if ( denominator === 0 ) {
  3378. // line is coplanar, return origin
  3379. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3380. return 0;
  3381. }
  3382. // Null is preferable to undefined since undefined means.... it is undefined
  3383. return null;
  3384. }
  3385. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3386. // Return if the ray never intersects the plane
  3387. return t >= 0 ? t : null;
  3388. }
  3389. intersectPlane( plane, target ) {
  3390. const t = this.distanceToPlane( plane );
  3391. if ( t === null ) {
  3392. return null;
  3393. }
  3394. return this.at( t, target );
  3395. }
  3396. intersectsPlane( plane ) {
  3397. // check if the ray lies on the plane first
  3398. const distToPoint = plane.distanceToPoint( this.origin );
  3399. if ( distToPoint === 0 ) {
  3400. return true;
  3401. }
  3402. const denominator = plane.normal.dot( this.direction );
  3403. if ( denominator * distToPoint < 0 ) {
  3404. return true;
  3405. }
  3406. // ray origin is behind the plane (and is pointing behind it)
  3407. return false;
  3408. }
  3409. intersectBox( box, target ) {
  3410. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3411. const invdirx = 1 / this.direction.x,
  3412. invdiry = 1 / this.direction.y,
  3413. invdirz = 1 / this.direction.z;
  3414. const origin = this.origin;
  3415. if ( invdirx >= 0 ) {
  3416. tmin = ( box.min.x - origin.x ) * invdirx;
  3417. tmax = ( box.max.x - origin.x ) * invdirx;
  3418. } else {
  3419. tmin = ( box.max.x - origin.x ) * invdirx;
  3420. tmax = ( box.min.x - origin.x ) * invdirx;
  3421. }
  3422. if ( invdiry >= 0 ) {
  3423. tymin = ( box.min.y - origin.y ) * invdiry;
  3424. tymax = ( box.max.y - origin.y ) * invdiry;
  3425. } else {
  3426. tymin = ( box.max.y - origin.y ) * invdiry;
  3427. tymax = ( box.min.y - origin.y ) * invdiry;
  3428. }
  3429. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3430. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3431. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3432. if ( invdirz >= 0 ) {
  3433. tzmin = ( box.min.z - origin.z ) * invdirz;
  3434. tzmax = ( box.max.z - origin.z ) * invdirz;
  3435. } else {
  3436. tzmin = ( box.max.z - origin.z ) * invdirz;
  3437. tzmax = ( box.min.z - origin.z ) * invdirz;
  3438. }
  3439. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3440. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3441. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3442. //return point closest to the ray (positive side)
  3443. if ( tmax < 0 ) return null;
  3444. return this.at( tmin >= 0 ? tmin : tmax, target );
  3445. }
  3446. intersectsBox( box ) {
  3447. return this.intersectBox( box, _vector$a ) !== null;
  3448. }
  3449. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3450. // Compute the offset origin, edges, and normal.
  3451. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3452. _edge1.subVectors( b, a );
  3453. _edge2.subVectors( c, a );
  3454. _normal$1.crossVectors( _edge1, _edge2 );
  3455. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3456. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3457. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3458. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3459. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3460. let DdN = this.direction.dot( _normal$1 );
  3461. let sign;
  3462. if ( DdN > 0 ) {
  3463. if ( backfaceCulling ) return null;
  3464. sign = 1;
  3465. } else if ( DdN < 0 ) {
  3466. sign = - 1;
  3467. DdN = - DdN;
  3468. } else {
  3469. return null;
  3470. }
  3471. _diff.subVectors( this.origin, a );
  3472. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3473. // b1 < 0, no intersection
  3474. if ( DdQxE2 < 0 ) {
  3475. return null;
  3476. }
  3477. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3478. // b2 < 0, no intersection
  3479. if ( DdE1xQ < 0 ) {
  3480. return null;
  3481. }
  3482. // b1+b2 > 1, no intersection
  3483. if ( DdQxE2 + DdE1xQ > DdN ) {
  3484. return null;
  3485. }
  3486. // Line intersects triangle, check if ray does.
  3487. const QdN = - sign * _diff.dot( _normal$1 );
  3488. // t < 0, no intersection
  3489. if ( QdN < 0 ) {
  3490. return null;
  3491. }
  3492. // Ray intersects triangle.
  3493. return this.at( QdN / DdN, target );
  3494. }
  3495. applyMatrix4( matrix4 ) {
  3496. this.origin.applyMatrix4( matrix4 );
  3497. this.direction.transformDirection( matrix4 );
  3498. return this;
  3499. }
  3500. equals( ray ) {
  3501. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3502. }
  3503. clone() {
  3504. return new this.constructor().copy( this );
  3505. }
  3506. }
  3507. class Matrix4 {
  3508. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3509. Matrix4.prototype.isMatrix4 = true;
  3510. this.elements = [
  3511. 1, 0, 0, 0,
  3512. 0, 1, 0, 0,
  3513. 0, 0, 1, 0,
  3514. 0, 0, 0, 1
  3515. ];
  3516. if ( n11 !== undefined ) {
  3517. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3518. }
  3519. }
  3520. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3521. const te = this.elements;
  3522. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3523. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3524. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3525. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3526. return this;
  3527. }
  3528. identity() {
  3529. this.set(
  3530. 1, 0, 0, 0,
  3531. 0, 1, 0, 0,
  3532. 0, 0, 1, 0,
  3533. 0, 0, 0, 1
  3534. );
  3535. return this;
  3536. }
  3537. clone() {
  3538. return new Matrix4().fromArray( this.elements );
  3539. }
  3540. copy( m ) {
  3541. const te = this.elements;
  3542. const me = m.elements;
  3543. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3544. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3545. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3546. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3547. return this;
  3548. }
  3549. copyPosition( m ) {
  3550. const te = this.elements, me = m.elements;
  3551. te[ 12 ] = me[ 12 ];
  3552. te[ 13 ] = me[ 13 ];
  3553. te[ 14 ] = me[ 14 ];
  3554. return this;
  3555. }
  3556. setFromMatrix3( m ) {
  3557. const me = m.elements;
  3558. this.set(
  3559. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3560. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3561. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3562. 0, 0, 0, 1
  3563. );
  3564. return this;
  3565. }
  3566. extractBasis( xAxis, yAxis, zAxis ) {
  3567. xAxis.setFromMatrixColumn( this, 0 );
  3568. yAxis.setFromMatrixColumn( this, 1 );
  3569. zAxis.setFromMatrixColumn( this, 2 );
  3570. return this;
  3571. }
  3572. makeBasis( xAxis, yAxis, zAxis ) {
  3573. this.set(
  3574. xAxis.x, yAxis.x, zAxis.x, 0,
  3575. xAxis.y, yAxis.y, zAxis.y, 0,
  3576. xAxis.z, yAxis.z, zAxis.z, 0,
  3577. 0, 0, 0, 1
  3578. );
  3579. return this;
  3580. }
  3581. extractRotation( m ) {
  3582. // this method does not support reflection matrices
  3583. const te = this.elements;
  3584. const me = m.elements;
  3585. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3586. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3587. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3588. te[ 0 ] = me[ 0 ] * scaleX;
  3589. te[ 1 ] = me[ 1 ] * scaleX;
  3590. te[ 2 ] = me[ 2 ] * scaleX;
  3591. te[ 3 ] = 0;
  3592. te[ 4 ] = me[ 4 ] * scaleY;
  3593. te[ 5 ] = me[ 5 ] * scaleY;
  3594. te[ 6 ] = me[ 6 ] * scaleY;
  3595. te[ 7 ] = 0;
  3596. te[ 8 ] = me[ 8 ] * scaleZ;
  3597. te[ 9 ] = me[ 9 ] * scaleZ;
  3598. te[ 10 ] = me[ 10 ] * scaleZ;
  3599. te[ 11 ] = 0;
  3600. te[ 12 ] = 0;
  3601. te[ 13 ] = 0;
  3602. te[ 14 ] = 0;
  3603. te[ 15 ] = 1;
  3604. return this;
  3605. }
  3606. makeRotationFromEuler( euler ) {
  3607. const te = this.elements;
  3608. const x = euler.x, y = euler.y, z = euler.z;
  3609. const a = Math.cos( x ), b = Math.sin( x );
  3610. const c = Math.cos( y ), d = Math.sin( y );
  3611. const e = Math.cos( z ), f = Math.sin( z );
  3612. if ( euler.order === 'XYZ' ) {
  3613. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3614. te[ 0 ] = c * e;
  3615. te[ 4 ] = - c * f;
  3616. te[ 8 ] = d;
  3617. te[ 1 ] = af + be * d;
  3618. te[ 5 ] = ae - bf * d;
  3619. te[ 9 ] = - b * c;
  3620. te[ 2 ] = bf - ae * d;
  3621. te[ 6 ] = be + af * d;
  3622. te[ 10 ] = a * c;
  3623. } else if ( euler.order === 'YXZ' ) {
  3624. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3625. te[ 0 ] = ce + df * b;
  3626. te[ 4 ] = de * b - cf;
  3627. te[ 8 ] = a * d;
  3628. te[ 1 ] = a * f;
  3629. te[ 5 ] = a * e;
  3630. te[ 9 ] = - b;
  3631. te[ 2 ] = cf * b - de;
  3632. te[ 6 ] = df + ce * b;
  3633. te[ 10 ] = a * c;
  3634. } else if ( euler.order === 'ZXY' ) {
  3635. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3636. te[ 0 ] = ce - df * b;
  3637. te[ 4 ] = - a * f;
  3638. te[ 8 ] = de + cf * b;
  3639. te[ 1 ] = cf + de * b;
  3640. te[ 5 ] = a * e;
  3641. te[ 9 ] = df - ce * b;
  3642. te[ 2 ] = - a * d;
  3643. te[ 6 ] = b;
  3644. te[ 10 ] = a * c;
  3645. } else if ( euler.order === 'ZYX' ) {
  3646. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3647. te[ 0 ] = c * e;
  3648. te[ 4 ] = be * d - af;
  3649. te[ 8 ] = ae * d + bf;
  3650. te[ 1 ] = c * f;
  3651. te[ 5 ] = bf * d + ae;
  3652. te[ 9 ] = af * d - be;
  3653. te[ 2 ] = - d;
  3654. te[ 6 ] = b * c;
  3655. te[ 10 ] = a * c;
  3656. } else if ( euler.order === 'YZX' ) {
  3657. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3658. te[ 0 ] = c * e;
  3659. te[ 4 ] = bd - ac * f;
  3660. te[ 8 ] = bc * f + ad;
  3661. te[ 1 ] = f;
  3662. te[ 5 ] = a * e;
  3663. te[ 9 ] = - b * e;
  3664. te[ 2 ] = - d * e;
  3665. te[ 6 ] = ad * f + bc;
  3666. te[ 10 ] = ac - bd * f;
  3667. } else if ( euler.order === 'XZY' ) {
  3668. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3669. te[ 0 ] = c * e;
  3670. te[ 4 ] = - f;
  3671. te[ 8 ] = d * e;
  3672. te[ 1 ] = ac * f + bd;
  3673. te[ 5 ] = a * e;
  3674. te[ 9 ] = ad * f - bc;
  3675. te[ 2 ] = bc * f - ad;
  3676. te[ 6 ] = b * e;
  3677. te[ 10 ] = bd * f + ac;
  3678. }
  3679. // bottom row
  3680. te[ 3 ] = 0;
  3681. te[ 7 ] = 0;
  3682. te[ 11 ] = 0;
  3683. // last column
  3684. te[ 12 ] = 0;
  3685. te[ 13 ] = 0;
  3686. te[ 14 ] = 0;
  3687. te[ 15 ] = 1;
  3688. return this;
  3689. }
  3690. makeRotationFromQuaternion( q ) {
  3691. return this.compose( _zero, q, _one );
  3692. }
  3693. lookAt( eye, target, up ) {
  3694. const te = this.elements;
  3695. _z.subVectors( eye, target );
  3696. if ( _z.lengthSq() === 0 ) {
  3697. // eye and target are in the same position
  3698. _z.z = 1;
  3699. }
  3700. _z.normalize();
  3701. _x.crossVectors( up, _z );
  3702. if ( _x.lengthSq() === 0 ) {
  3703. // up and z are parallel
  3704. if ( Math.abs( up.z ) === 1 ) {
  3705. _z.x += 0.0001;
  3706. } else {
  3707. _z.z += 0.0001;
  3708. }
  3709. _z.normalize();
  3710. _x.crossVectors( up, _z );
  3711. }
  3712. _x.normalize();
  3713. _y.crossVectors( _z, _x );
  3714. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3715. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3716. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3717. return this;
  3718. }
  3719. multiply( m ) {
  3720. return this.multiplyMatrices( this, m );
  3721. }
  3722. premultiply( m ) {
  3723. return this.multiplyMatrices( m, this );
  3724. }
  3725. multiplyMatrices( a, b ) {
  3726. const ae = a.elements;
  3727. const be = b.elements;
  3728. const te = this.elements;
  3729. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3730. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3731. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3732. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3733. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3734. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3735. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3736. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3737. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3738. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3739. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3740. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3741. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3742. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3743. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3744. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3745. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3746. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3747. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3748. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3749. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3750. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3751. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3752. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3753. return this;
  3754. }
  3755. multiplyScalar( s ) {
  3756. const te = this.elements;
  3757. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3758. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3759. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3760. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3761. return this;
  3762. }
  3763. determinant() {
  3764. const te = this.elements;
  3765. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3766. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3767. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3768. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3769. //TODO: make this more efficient
  3770. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3771. return (
  3772. n41 * (
  3773. + n14 * n23 * n32
  3774. - n13 * n24 * n32
  3775. - n14 * n22 * n33
  3776. + n12 * n24 * n33
  3777. + n13 * n22 * n34
  3778. - n12 * n23 * n34
  3779. ) +
  3780. n42 * (
  3781. + n11 * n23 * n34
  3782. - n11 * n24 * n33
  3783. + n14 * n21 * n33
  3784. - n13 * n21 * n34
  3785. + n13 * n24 * n31
  3786. - n14 * n23 * n31
  3787. ) +
  3788. n43 * (
  3789. + n11 * n24 * n32
  3790. - n11 * n22 * n34
  3791. - n14 * n21 * n32
  3792. + n12 * n21 * n34
  3793. + n14 * n22 * n31
  3794. - n12 * n24 * n31
  3795. ) +
  3796. n44 * (
  3797. - n13 * n22 * n31
  3798. - n11 * n23 * n32
  3799. + n11 * n22 * n33
  3800. + n13 * n21 * n32
  3801. - n12 * n21 * n33
  3802. + n12 * n23 * n31
  3803. )
  3804. );
  3805. }
  3806. transpose() {
  3807. const te = this.elements;
  3808. let tmp;
  3809. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3810. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3811. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3812. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3813. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3814. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3815. return this;
  3816. }
  3817. setPosition( x, y, z ) {
  3818. const te = this.elements;
  3819. if ( x.isVector3 ) {
  3820. te[ 12 ] = x.x;
  3821. te[ 13 ] = x.y;
  3822. te[ 14 ] = x.z;
  3823. } else {
  3824. te[ 12 ] = x;
  3825. te[ 13 ] = y;
  3826. te[ 14 ] = z;
  3827. }
  3828. return this;
  3829. }
  3830. invert() {
  3831. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3832. const te = this.elements,
  3833. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3834. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3835. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3836. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3837. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3838. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3839. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3840. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3841. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3842. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3843. const detInv = 1 / det;
  3844. te[ 0 ] = t11 * detInv;
  3845. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3846. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3847. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3848. te[ 4 ] = t12 * detInv;
  3849. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3850. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3851. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3852. te[ 8 ] = t13 * detInv;
  3853. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3854. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3855. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3856. te[ 12 ] = t14 * detInv;
  3857. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3858. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3859. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3860. return this;
  3861. }
  3862. scale( v ) {
  3863. const te = this.elements;
  3864. const x = v.x, y = v.y, z = v.z;
  3865. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3866. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3867. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3868. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3869. return this;
  3870. }
  3871. getMaxScaleOnAxis() {
  3872. const te = this.elements;
  3873. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3874. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3875. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3876. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3877. }
  3878. makeTranslation( x, y, z ) {
  3879. if ( x.isVector3 ) {
  3880. this.set(
  3881. 1, 0, 0, x.x,
  3882. 0, 1, 0, x.y,
  3883. 0, 0, 1, x.z,
  3884. 0, 0, 0, 1
  3885. );
  3886. } else {
  3887. this.set(
  3888. 1, 0, 0, x,
  3889. 0, 1, 0, y,
  3890. 0, 0, 1, z,
  3891. 0, 0, 0, 1
  3892. );
  3893. }
  3894. return this;
  3895. }
  3896. makeRotationX( theta ) {
  3897. const c = Math.cos( theta ), s = Math.sin( theta );
  3898. this.set(
  3899. 1, 0, 0, 0,
  3900. 0, c, - s, 0,
  3901. 0, s, c, 0,
  3902. 0, 0, 0, 1
  3903. );
  3904. return this;
  3905. }
  3906. makeRotationY( theta ) {
  3907. const c = Math.cos( theta ), s = Math.sin( theta );
  3908. this.set(
  3909. c, 0, s, 0,
  3910. 0, 1, 0, 0,
  3911. - s, 0, c, 0,
  3912. 0, 0, 0, 1
  3913. );
  3914. return this;
  3915. }
  3916. makeRotationZ( theta ) {
  3917. const c = Math.cos( theta ), s = Math.sin( theta );
  3918. this.set(
  3919. c, - s, 0, 0,
  3920. s, c, 0, 0,
  3921. 0, 0, 1, 0,
  3922. 0, 0, 0, 1
  3923. );
  3924. return this;
  3925. }
  3926. makeRotationAxis( axis, angle ) {
  3927. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3928. const c = Math.cos( angle );
  3929. const s = Math.sin( angle );
  3930. const t = 1 - c;
  3931. const x = axis.x, y = axis.y, z = axis.z;
  3932. const tx = t * x, ty = t * y;
  3933. this.set(
  3934. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3935. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3936. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3937. 0, 0, 0, 1
  3938. );
  3939. return this;
  3940. }
  3941. makeScale( x, y, z ) {
  3942. this.set(
  3943. x, 0, 0, 0,
  3944. 0, y, 0, 0,
  3945. 0, 0, z, 0,
  3946. 0, 0, 0, 1
  3947. );
  3948. return this;
  3949. }
  3950. makeShear( xy, xz, yx, yz, zx, zy ) {
  3951. this.set(
  3952. 1, yx, zx, 0,
  3953. xy, 1, zy, 0,
  3954. xz, yz, 1, 0,
  3955. 0, 0, 0, 1
  3956. );
  3957. return this;
  3958. }
  3959. compose( position, quaternion, scale ) {
  3960. const te = this.elements;
  3961. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3962. const x2 = x + x, y2 = y + y, z2 = z + z;
  3963. const xx = x * x2, xy = x * y2, xz = x * z2;
  3964. const yy = y * y2, yz = y * z2, zz = z * z2;
  3965. const wx = w * x2, wy = w * y2, wz = w * z2;
  3966. const sx = scale.x, sy = scale.y, sz = scale.z;
  3967. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3968. te[ 1 ] = ( xy + wz ) * sx;
  3969. te[ 2 ] = ( xz - wy ) * sx;
  3970. te[ 3 ] = 0;
  3971. te[ 4 ] = ( xy - wz ) * sy;
  3972. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3973. te[ 6 ] = ( yz + wx ) * sy;
  3974. te[ 7 ] = 0;
  3975. te[ 8 ] = ( xz + wy ) * sz;
  3976. te[ 9 ] = ( yz - wx ) * sz;
  3977. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3978. te[ 11 ] = 0;
  3979. te[ 12 ] = position.x;
  3980. te[ 13 ] = position.y;
  3981. te[ 14 ] = position.z;
  3982. te[ 15 ] = 1;
  3983. return this;
  3984. }
  3985. decompose( position, quaternion, scale ) {
  3986. const te = this.elements;
  3987. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3988. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3989. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3990. // if determine is negative, we need to invert one scale
  3991. const det = this.determinant();
  3992. if ( det < 0 ) sx = - sx;
  3993. position.x = te[ 12 ];
  3994. position.y = te[ 13 ];
  3995. position.z = te[ 14 ];
  3996. // scale the rotation part
  3997. _m1$4.copy( this );
  3998. const invSX = 1 / sx;
  3999. const invSY = 1 / sy;
  4000. const invSZ = 1 / sz;
  4001. _m1$4.elements[ 0 ] *= invSX;
  4002. _m1$4.elements[ 1 ] *= invSX;
  4003. _m1$4.elements[ 2 ] *= invSX;
  4004. _m1$4.elements[ 4 ] *= invSY;
  4005. _m1$4.elements[ 5 ] *= invSY;
  4006. _m1$4.elements[ 6 ] *= invSY;
  4007. _m1$4.elements[ 8 ] *= invSZ;
  4008. _m1$4.elements[ 9 ] *= invSZ;
  4009. _m1$4.elements[ 10 ] *= invSZ;
  4010. quaternion.setFromRotationMatrix( _m1$4 );
  4011. scale.x = sx;
  4012. scale.y = sy;
  4013. scale.z = sz;
  4014. return this;
  4015. }
  4016. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4017. const te = this.elements;
  4018. const x = 2 * near / ( right - left );
  4019. const y = 2 * near / ( top - bottom );
  4020. const a = ( right + left ) / ( right - left );
  4021. const b = ( top + bottom ) / ( top - bottom );
  4022. let c, d;
  4023. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4024. c = - ( far + near ) / ( far - near );
  4025. d = ( - 2 * far * near ) / ( far - near );
  4026. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4027. c = - far / ( far - near );
  4028. d = ( - far * near ) / ( far - near );
  4029. } else {
  4030. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4031. }
  4032. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4033. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4034. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4035. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4036. return this;
  4037. }
  4038. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4039. const te = this.elements;
  4040. const w = 1.0 / ( right - left );
  4041. const h = 1.0 / ( top - bottom );
  4042. const p = 1.0 / ( far - near );
  4043. const x = ( right + left ) * w;
  4044. const y = ( top + bottom ) * h;
  4045. let z, zInv;
  4046. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4047. z = ( far + near ) * p;
  4048. zInv = - 2 * p;
  4049. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4050. z = near * p;
  4051. zInv = - 1 * p;
  4052. } else {
  4053. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4054. }
  4055. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4056. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4057. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4058. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4059. return this;
  4060. }
  4061. equals( matrix ) {
  4062. const te = this.elements;
  4063. const me = matrix.elements;
  4064. for ( let i = 0; i < 16; i ++ ) {
  4065. if ( te[ i ] !== me[ i ] ) return false;
  4066. }
  4067. return true;
  4068. }
  4069. fromArray( array, offset = 0 ) {
  4070. for ( let i = 0; i < 16; i ++ ) {
  4071. this.elements[ i ] = array[ i + offset ];
  4072. }
  4073. return this;
  4074. }
  4075. toArray( array = [], offset = 0 ) {
  4076. const te = this.elements;
  4077. array[ offset ] = te[ 0 ];
  4078. array[ offset + 1 ] = te[ 1 ];
  4079. array[ offset + 2 ] = te[ 2 ];
  4080. array[ offset + 3 ] = te[ 3 ];
  4081. array[ offset + 4 ] = te[ 4 ];
  4082. array[ offset + 5 ] = te[ 5 ];
  4083. array[ offset + 6 ] = te[ 6 ];
  4084. array[ offset + 7 ] = te[ 7 ];
  4085. array[ offset + 8 ] = te[ 8 ];
  4086. array[ offset + 9 ] = te[ 9 ];
  4087. array[ offset + 10 ] = te[ 10 ];
  4088. array[ offset + 11 ] = te[ 11 ];
  4089. array[ offset + 12 ] = te[ 12 ];
  4090. array[ offset + 13 ] = te[ 13 ];
  4091. array[ offset + 14 ] = te[ 14 ];
  4092. array[ offset + 15 ] = te[ 15 ];
  4093. return array;
  4094. }
  4095. }
  4096. const _v1$5 = /*@__PURE__*/ new Vector3();
  4097. const _m1$4 = /*@__PURE__*/ new Matrix4();
  4098. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4099. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4100. const _x = /*@__PURE__*/ new Vector3();
  4101. const _y = /*@__PURE__*/ new Vector3();
  4102. const _z = /*@__PURE__*/ new Vector3();
  4103. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4104. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4105. class Euler {
  4106. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4107. this.isEuler = true;
  4108. this._x = x;
  4109. this._y = y;
  4110. this._z = z;
  4111. this._order = order;
  4112. }
  4113. get x() {
  4114. return this._x;
  4115. }
  4116. set x( value ) {
  4117. this._x = value;
  4118. this._onChangeCallback();
  4119. }
  4120. get y() {
  4121. return this._y;
  4122. }
  4123. set y( value ) {
  4124. this._y = value;
  4125. this._onChangeCallback();
  4126. }
  4127. get z() {
  4128. return this._z;
  4129. }
  4130. set z( value ) {
  4131. this._z = value;
  4132. this._onChangeCallback();
  4133. }
  4134. get order() {
  4135. return this._order;
  4136. }
  4137. set order( value ) {
  4138. this._order = value;
  4139. this._onChangeCallback();
  4140. }
  4141. set( x, y, z, order = this._order ) {
  4142. this._x = x;
  4143. this._y = y;
  4144. this._z = z;
  4145. this._order = order;
  4146. this._onChangeCallback();
  4147. return this;
  4148. }
  4149. clone() {
  4150. return new this.constructor( this._x, this._y, this._z, this._order );
  4151. }
  4152. copy( euler ) {
  4153. this._x = euler._x;
  4154. this._y = euler._y;
  4155. this._z = euler._z;
  4156. this._order = euler._order;
  4157. this._onChangeCallback();
  4158. return this;
  4159. }
  4160. setFromRotationMatrix( m, order = this._order, update = true ) {
  4161. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4162. const te = m.elements;
  4163. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4164. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4165. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4166. switch ( order ) {
  4167. case 'XYZ':
  4168. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4169. if ( Math.abs( m13 ) < 0.9999999 ) {
  4170. this._x = Math.atan2( - m23, m33 );
  4171. this._z = Math.atan2( - m12, m11 );
  4172. } else {
  4173. this._x = Math.atan2( m32, m22 );
  4174. this._z = 0;
  4175. }
  4176. break;
  4177. case 'YXZ':
  4178. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4179. if ( Math.abs( m23 ) < 0.9999999 ) {
  4180. this._y = Math.atan2( m13, m33 );
  4181. this._z = Math.atan2( m21, m22 );
  4182. } else {
  4183. this._y = Math.atan2( - m31, m11 );
  4184. this._z = 0;
  4185. }
  4186. break;
  4187. case 'ZXY':
  4188. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4189. if ( Math.abs( m32 ) < 0.9999999 ) {
  4190. this._y = Math.atan2( - m31, m33 );
  4191. this._z = Math.atan2( - m12, m22 );
  4192. } else {
  4193. this._y = 0;
  4194. this._z = Math.atan2( m21, m11 );
  4195. }
  4196. break;
  4197. case 'ZYX':
  4198. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4199. if ( Math.abs( m31 ) < 0.9999999 ) {
  4200. this._x = Math.atan2( m32, m33 );
  4201. this._z = Math.atan2( m21, m11 );
  4202. } else {
  4203. this._x = 0;
  4204. this._z = Math.atan2( - m12, m22 );
  4205. }
  4206. break;
  4207. case 'YZX':
  4208. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4209. if ( Math.abs( m21 ) < 0.9999999 ) {
  4210. this._x = Math.atan2( - m23, m22 );
  4211. this._y = Math.atan2( - m31, m11 );
  4212. } else {
  4213. this._x = 0;
  4214. this._y = Math.atan2( m13, m33 );
  4215. }
  4216. break;
  4217. case 'XZY':
  4218. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4219. if ( Math.abs( m12 ) < 0.9999999 ) {
  4220. this._x = Math.atan2( m32, m22 );
  4221. this._y = Math.atan2( m13, m11 );
  4222. } else {
  4223. this._x = Math.atan2( - m23, m33 );
  4224. this._y = 0;
  4225. }
  4226. break;
  4227. default:
  4228. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4229. }
  4230. this._order = order;
  4231. if ( update === true ) this._onChangeCallback();
  4232. return this;
  4233. }
  4234. setFromQuaternion( q, order, update ) {
  4235. _matrix$2.makeRotationFromQuaternion( q );
  4236. return this.setFromRotationMatrix( _matrix$2, order, update );
  4237. }
  4238. setFromVector3( v, order = this._order ) {
  4239. return this.set( v.x, v.y, v.z, order );
  4240. }
  4241. reorder( newOrder ) {
  4242. // WARNING: this discards revolution information -bhouston
  4243. _quaternion$3.setFromEuler( this );
  4244. return this.setFromQuaternion( _quaternion$3, newOrder );
  4245. }
  4246. equals( euler ) {
  4247. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4248. }
  4249. fromArray( array ) {
  4250. this._x = array[ 0 ];
  4251. this._y = array[ 1 ];
  4252. this._z = array[ 2 ];
  4253. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4254. this._onChangeCallback();
  4255. return this;
  4256. }
  4257. toArray( array = [], offset = 0 ) {
  4258. array[ offset ] = this._x;
  4259. array[ offset + 1 ] = this._y;
  4260. array[ offset + 2 ] = this._z;
  4261. array[ offset + 3 ] = this._order;
  4262. return array;
  4263. }
  4264. _onChange( callback ) {
  4265. this._onChangeCallback = callback;
  4266. return this;
  4267. }
  4268. _onChangeCallback() {}
  4269. *[ Symbol.iterator ]() {
  4270. yield this._x;
  4271. yield this._y;
  4272. yield this._z;
  4273. yield this._order;
  4274. }
  4275. }
  4276. Euler.DEFAULT_ORDER = 'XYZ';
  4277. class Layers {
  4278. constructor() {
  4279. this.mask = 1 | 0;
  4280. }
  4281. set( channel ) {
  4282. this.mask = ( 1 << channel | 0 ) >>> 0;
  4283. }
  4284. enable( channel ) {
  4285. this.mask |= 1 << channel | 0;
  4286. }
  4287. enableAll() {
  4288. this.mask = 0xffffffff | 0;
  4289. }
  4290. toggle( channel ) {
  4291. this.mask ^= 1 << channel | 0;
  4292. }
  4293. disable( channel ) {
  4294. this.mask &= ~ ( 1 << channel | 0 );
  4295. }
  4296. disableAll() {
  4297. this.mask = 0;
  4298. }
  4299. test( layers ) {
  4300. return ( this.mask & layers.mask ) !== 0;
  4301. }
  4302. isEnabled( channel ) {
  4303. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4304. }
  4305. }
  4306. let _object3DId = 0;
  4307. const _v1$4 = /*@__PURE__*/ new Vector3();
  4308. const _q1 = /*@__PURE__*/ new Quaternion();
  4309. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4310. const _target = /*@__PURE__*/ new Vector3();
  4311. const _position$3 = /*@__PURE__*/ new Vector3();
  4312. const _scale$2 = /*@__PURE__*/ new Vector3();
  4313. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4314. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4315. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4316. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4317. const _addedEvent = { type: 'added' };
  4318. const _removedEvent = { type: 'removed' };
  4319. const _childaddedEvent = { type: 'childadded', child: null };
  4320. const _childremovedEvent = { type: 'childremoved', child: null };
  4321. class Object3D extends EventDispatcher {
  4322. constructor() {
  4323. super();
  4324. this.isObject3D = true;
  4325. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4326. this.uuid = generateUUID();
  4327. this.name = '';
  4328. this.type = 'Object3D';
  4329. this.parent = null;
  4330. this.children = [];
  4331. this.up = Object3D.DEFAULT_UP.clone();
  4332. const position = new Vector3();
  4333. const rotation = new Euler();
  4334. const quaternion = new Quaternion();
  4335. const scale = new Vector3( 1, 1, 1 );
  4336. function onRotationChange() {
  4337. quaternion.setFromEuler( rotation, false );
  4338. }
  4339. function onQuaternionChange() {
  4340. rotation.setFromQuaternion( quaternion, undefined, false );
  4341. }
  4342. rotation._onChange( onRotationChange );
  4343. quaternion._onChange( onQuaternionChange );
  4344. Object.defineProperties( this, {
  4345. position: {
  4346. configurable: true,
  4347. enumerable: true,
  4348. value: position
  4349. },
  4350. rotation: {
  4351. configurable: true,
  4352. enumerable: true,
  4353. value: rotation
  4354. },
  4355. quaternion: {
  4356. configurable: true,
  4357. enumerable: true,
  4358. value: quaternion
  4359. },
  4360. scale: {
  4361. configurable: true,
  4362. enumerable: true,
  4363. value: scale
  4364. },
  4365. modelViewMatrix: {
  4366. value: new Matrix4()
  4367. },
  4368. normalMatrix: {
  4369. value: new Matrix3()
  4370. }
  4371. } );
  4372. this.matrix = new Matrix4();
  4373. this.matrixWorld = new Matrix4();
  4374. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4375. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4376. this.matrixWorldNeedsUpdate = false;
  4377. this.layers = new Layers();
  4378. this.visible = true;
  4379. this.castShadow = false;
  4380. this.receiveShadow = false;
  4381. this.frustumCulled = true;
  4382. this.renderOrder = 0;
  4383. this.animations = [];
  4384. this.userData = {};
  4385. }
  4386. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4387. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4388. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4389. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4390. applyMatrix4( matrix ) {
  4391. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4392. this.matrix.premultiply( matrix );
  4393. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4394. }
  4395. applyQuaternion( q ) {
  4396. this.quaternion.premultiply( q );
  4397. return this;
  4398. }
  4399. setRotationFromAxisAngle( axis, angle ) {
  4400. // assumes axis is normalized
  4401. this.quaternion.setFromAxisAngle( axis, angle );
  4402. }
  4403. setRotationFromEuler( euler ) {
  4404. this.quaternion.setFromEuler( euler, true );
  4405. }
  4406. setRotationFromMatrix( m ) {
  4407. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4408. this.quaternion.setFromRotationMatrix( m );
  4409. }
  4410. setRotationFromQuaternion( q ) {
  4411. // assumes q is normalized
  4412. this.quaternion.copy( q );
  4413. }
  4414. rotateOnAxis( axis, angle ) {
  4415. // rotate object on axis in object space
  4416. // axis is assumed to be normalized
  4417. _q1.setFromAxisAngle( axis, angle );
  4418. this.quaternion.multiply( _q1 );
  4419. return this;
  4420. }
  4421. rotateOnWorldAxis( axis, angle ) {
  4422. // rotate object on axis in world space
  4423. // axis is assumed to be normalized
  4424. // method assumes no rotated parent
  4425. _q1.setFromAxisAngle( axis, angle );
  4426. this.quaternion.premultiply( _q1 );
  4427. return this;
  4428. }
  4429. rotateX( angle ) {
  4430. return this.rotateOnAxis( _xAxis, angle );
  4431. }
  4432. rotateY( angle ) {
  4433. return this.rotateOnAxis( _yAxis, angle );
  4434. }
  4435. rotateZ( angle ) {
  4436. return this.rotateOnAxis( _zAxis, angle );
  4437. }
  4438. translateOnAxis( axis, distance ) {
  4439. // translate object by distance along axis in object space
  4440. // axis is assumed to be normalized
  4441. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4442. this.position.add( _v1$4.multiplyScalar( distance ) );
  4443. return this;
  4444. }
  4445. translateX( distance ) {
  4446. return this.translateOnAxis( _xAxis, distance );
  4447. }
  4448. translateY( distance ) {
  4449. return this.translateOnAxis( _yAxis, distance );
  4450. }
  4451. translateZ( distance ) {
  4452. return this.translateOnAxis( _zAxis, distance );
  4453. }
  4454. localToWorld( vector ) {
  4455. this.updateWorldMatrix( true, false );
  4456. return vector.applyMatrix4( this.matrixWorld );
  4457. }
  4458. worldToLocal( vector ) {
  4459. this.updateWorldMatrix( true, false );
  4460. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  4461. }
  4462. lookAt( x, y, z ) {
  4463. // This method does not support objects having non-uniformly-scaled parent(s)
  4464. if ( x.isVector3 ) {
  4465. _target.copy( x );
  4466. } else {
  4467. _target.set( x, y, z );
  4468. }
  4469. const parent = this.parent;
  4470. this.updateWorldMatrix( true, false );
  4471. _position$3.setFromMatrixPosition( this.matrixWorld );
  4472. if ( this.isCamera || this.isLight ) {
  4473. _m1$3.lookAt( _position$3, _target, this.up );
  4474. } else {
  4475. _m1$3.lookAt( _target, _position$3, this.up );
  4476. }
  4477. this.quaternion.setFromRotationMatrix( _m1$3 );
  4478. if ( parent ) {
  4479. _m1$3.extractRotation( parent.matrixWorld );
  4480. _q1.setFromRotationMatrix( _m1$3 );
  4481. this.quaternion.premultiply( _q1.invert() );
  4482. }
  4483. }
  4484. add( object ) {
  4485. if ( arguments.length > 1 ) {
  4486. for ( let i = 0; i < arguments.length; i ++ ) {
  4487. this.add( arguments[ i ] );
  4488. }
  4489. return this;
  4490. }
  4491. if ( object === this ) {
  4492. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4493. return this;
  4494. }
  4495. if ( object && object.isObject3D ) {
  4496. object.removeFromParent();
  4497. object.parent = this;
  4498. this.children.push( object );
  4499. object.dispatchEvent( _addedEvent );
  4500. _childaddedEvent.child = object;
  4501. this.dispatchEvent( _childaddedEvent );
  4502. _childaddedEvent.child = null;
  4503. } else {
  4504. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4505. }
  4506. return this;
  4507. }
  4508. remove( object ) {
  4509. if ( arguments.length > 1 ) {
  4510. for ( let i = 0; i < arguments.length; i ++ ) {
  4511. this.remove( arguments[ i ] );
  4512. }
  4513. return this;
  4514. }
  4515. const index = this.children.indexOf( object );
  4516. if ( index !== - 1 ) {
  4517. object.parent = null;
  4518. this.children.splice( index, 1 );
  4519. object.dispatchEvent( _removedEvent );
  4520. _childremovedEvent.child = object;
  4521. this.dispatchEvent( _childremovedEvent );
  4522. _childremovedEvent.child = null;
  4523. }
  4524. return this;
  4525. }
  4526. removeFromParent() {
  4527. const parent = this.parent;
  4528. if ( parent !== null ) {
  4529. parent.remove( this );
  4530. }
  4531. return this;
  4532. }
  4533. clear() {
  4534. return this.remove( ... this.children );
  4535. }
  4536. attach( object ) {
  4537. // adds object as a child of this, while maintaining the object's world transform
  4538. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4539. this.updateWorldMatrix( true, false );
  4540. _m1$3.copy( this.matrixWorld ).invert();
  4541. if ( object.parent !== null ) {
  4542. object.parent.updateWorldMatrix( true, false );
  4543. _m1$3.multiply( object.parent.matrixWorld );
  4544. }
  4545. object.applyMatrix4( _m1$3 );
  4546. object.removeFromParent();
  4547. object.parent = this;
  4548. this.children.push( object );
  4549. object.updateWorldMatrix( false, true );
  4550. object.dispatchEvent( _addedEvent );
  4551. _childaddedEvent.child = object;
  4552. this.dispatchEvent( _childaddedEvent );
  4553. _childaddedEvent.child = null;
  4554. return this;
  4555. }
  4556. getObjectById( id ) {
  4557. return this.getObjectByProperty( 'id', id );
  4558. }
  4559. getObjectByName( name ) {
  4560. return this.getObjectByProperty( 'name', name );
  4561. }
  4562. getObjectByProperty( name, value ) {
  4563. if ( this[ name ] === value ) return this;
  4564. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4565. const child = this.children[ i ];
  4566. const object = child.getObjectByProperty( name, value );
  4567. if ( object !== undefined ) {
  4568. return object;
  4569. }
  4570. }
  4571. return undefined;
  4572. }
  4573. getObjectsByProperty( name, value, result = [] ) {
  4574. if ( this[ name ] === value ) result.push( this );
  4575. const children = this.children;
  4576. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4577. children[ i ].getObjectsByProperty( name, value, result );
  4578. }
  4579. return result;
  4580. }
  4581. getWorldPosition( target ) {
  4582. this.updateWorldMatrix( true, false );
  4583. return target.setFromMatrixPosition( this.matrixWorld );
  4584. }
  4585. getWorldQuaternion( target ) {
  4586. this.updateWorldMatrix( true, false );
  4587. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4588. return target;
  4589. }
  4590. getWorldScale( target ) {
  4591. this.updateWorldMatrix( true, false );
  4592. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4593. return target;
  4594. }
  4595. getWorldDirection( target ) {
  4596. this.updateWorldMatrix( true, false );
  4597. const e = this.matrixWorld.elements;
  4598. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4599. }
  4600. raycast( /* raycaster, intersects */ ) {}
  4601. traverse( callback ) {
  4602. callback( this );
  4603. const children = this.children;
  4604. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4605. children[ i ].traverse( callback );
  4606. }
  4607. }
  4608. traverseVisible( callback ) {
  4609. if ( this.visible === false ) return;
  4610. callback( this );
  4611. const children = this.children;
  4612. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4613. children[ i ].traverseVisible( callback );
  4614. }
  4615. }
  4616. traverseAncestors( callback ) {
  4617. const parent = this.parent;
  4618. if ( parent !== null ) {
  4619. callback( parent );
  4620. parent.traverseAncestors( callback );
  4621. }
  4622. }
  4623. updateMatrix() {
  4624. this.matrix.compose( this.position, this.quaternion, this.scale );
  4625. this.matrixWorldNeedsUpdate = true;
  4626. }
  4627. updateMatrixWorld( force ) {
  4628. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4629. if ( this.matrixWorldNeedsUpdate || force ) {
  4630. if ( this.parent === null ) {
  4631. this.matrixWorld.copy( this.matrix );
  4632. } else {
  4633. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4634. }
  4635. this.matrixWorldNeedsUpdate = false;
  4636. force = true;
  4637. }
  4638. // update children
  4639. const children = this.children;
  4640. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4641. const child = children[ i ];
  4642. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4643. child.updateMatrixWorld( force );
  4644. }
  4645. }
  4646. }
  4647. updateWorldMatrix( updateParents, updateChildren ) {
  4648. const parent = this.parent;
  4649. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4650. parent.updateWorldMatrix( true, false );
  4651. }
  4652. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4653. if ( this.parent === null ) {
  4654. this.matrixWorld.copy( this.matrix );
  4655. } else {
  4656. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4657. }
  4658. // update children
  4659. if ( updateChildren === true ) {
  4660. const children = this.children;
  4661. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4662. const child = children[ i ];
  4663. if ( child.matrixWorldAutoUpdate === true ) {
  4664. child.updateWorldMatrix( false, true );
  4665. }
  4666. }
  4667. }
  4668. }
  4669. toJSON( meta ) {
  4670. // meta is a string when called from JSON.stringify
  4671. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4672. const output = {};
  4673. // meta is a hash used to collect geometries, materials.
  4674. // not providing it implies that this is the root object
  4675. // being serialized.
  4676. if ( isRootObject ) {
  4677. // initialize meta obj
  4678. meta = {
  4679. geometries: {},
  4680. materials: {},
  4681. textures: {},
  4682. images: {},
  4683. shapes: {},
  4684. skeletons: {},
  4685. animations: {},
  4686. nodes: {}
  4687. };
  4688. output.metadata = {
  4689. version: 4.6,
  4690. type: 'Object',
  4691. generator: 'Object3D.toJSON'
  4692. };
  4693. }
  4694. // standard Object3D serialization
  4695. const object = {};
  4696. object.uuid = this.uuid;
  4697. object.type = this.type;
  4698. if ( this.name !== '' ) object.name = this.name;
  4699. if ( this.castShadow === true ) object.castShadow = true;
  4700. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4701. if ( this.visible === false ) object.visible = false;
  4702. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4703. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4704. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4705. object.layers = this.layers.mask;
  4706. object.matrix = this.matrix.toArray();
  4707. object.up = this.up.toArray();
  4708. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4709. // object specific properties
  4710. if ( this.isInstancedMesh ) {
  4711. object.type = 'InstancedMesh';
  4712. object.count = this.count;
  4713. object.instanceMatrix = this.instanceMatrix.toJSON();
  4714. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4715. }
  4716. if ( this.isBatchedMesh ) {
  4717. object.type = 'BatchedMesh';
  4718. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4719. object.sortObjects = this.sortObjects;
  4720. object.drawRanges = this._drawRanges;
  4721. object.reservedRanges = this._reservedRanges;
  4722. object.visibility = this._visibility;
  4723. object.active = this._active;
  4724. object.bounds = this._bounds.map( bound => ( {
  4725. boxInitialized: bound.boxInitialized,
  4726. boxMin: bound.box.min.toArray(),
  4727. boxMax: bound.box.max.toArray(),
  4728. sphereInitialized: bound.sphereInitialized,
  4729. sphereRadius: bound.sphere.radius,
  4730. sphereCenter: bound.sphere.center.toArray()
  4731. } ) );
  4732. object.maxGeometryCount = this._maxGeometryCount;
  4733. object.maxVertexCount = this._maxVertexCount;
  4734. object.maxIndexCount = this._maxIndexCount;
  4735. object.geometryInitialized = this._geometryInitialized;
  4736. object.geometryCount = this._geometryCount;
  4737. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4738. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4739. if ( this.boundingSphere !== null ) {
  4740. object.boundingSphere = {
  4741. center: object.boundingSphere.center.toArray(),
  4742. radius: object.boundingSphere.radius
  4743. };
  4744. }
  4745. if ( this.boundingBox !== null ) {
  4746. object.boundingBox = {
  4747. min: object.boundingBox.min.toArray(),
  4748. max: object.boundingBox.max.toArray()
  4749. };
  4750. }
  4751. }
  4752. //
  4753. function serialize( library, element ) {
  4754. if ( library[ element.uuid ] === undefined ) {
  4755. library[ element.uuid ] = element.toJSON( meta );
  4756. }
  4757. return element.uuid;
  4758. }
  4759. if ( this.isScene ) {
  4760. if ( this.background ) {
  4761. if ( this.background.isColor ) {
  4762. object.background = this.background.toJSON();
  4763. } else if ( this.background.isTexture ) {
  4764. object.background = this.background.toJSON( meta ).uuid;
  4765. }
  4766. }
  4767. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4768. object.environment = this.environment.toJSON( meta ).uuid;
  4769. }
  4770. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4771. object.geometry = serialize( meta.geometries, this.geometry );
  4772. const parameters = this.geometry.parameters;
  4773. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4774. const shapes = parameters.shapes;
  4775. if ( Array.isArray( shapes ) ) {
  4776. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4777. const shape = shapes[ i ];
  4778. serialize( meta.shapes, shape );
  4779. }
  4780. } else {
  4781. serialize( meta.shapes, shapes );
  4782. }
  4783. }
  4784. }
  4785. if ( this.isSkinnedMesh ) {
  4786. object.bindMode = this.bindMode;
  4787. object.bindMatrix = this.bindMatrix.toArray();
  4788. if ( this.skeleton !== undefined ) {
  4789. serialize( meta.skeletons, this.skeleton );
  4790. object.skeleton = this.skeleton.uuid;
  4791. }
  4792. }
  4793. if ( this.material !== undefined ) {
  4794. if ( Array.isArray( this.material ) ) {
  4795. const uuids = [];
  4796. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4797. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4798. }
  4799. object.material = uuids;
  4800. } else {
  4801. object.material = serialize( meta.materials, this.material );
  4802. }
  4803. }
  4804. //
  4805. if ( this.children.length > 0 ) {
  4806. object.children = [];
  4807. for ( let i = 0; i < this.children.length; i ++ ) {
  4808. object.children.push( this.children[ i ].toJSON( meta ).object );
  4809. }
  4810. }
  4811. //
  4812. if ( this.animations.length > 0 ) {
  4813. object.animations = [];
  4814. for ( let i = 0; i < this.animations.length; i ++ ) {
  4815. const animation = this.animations[ i ];
  4816. object.animations.push( serialize( meta.animations, animation ) );
  4817. }
  4818. }
  4819. if ( isRootObject ) {
  4820. const geometries = extractFromCache( meta.geometries );
  4821. const materials = extractFromCache( meta.materials );
  4822. const textures = extractFromCache( meta.textures );
  4823. const images = extractFromCache( meta.images );
  4824. const shapes = extractFromCache( meta.shapes );
  4825. const skeletons = extractFromCache( meta.skeletons );
  4826. const animations = extractFromCache( meta.animations );
  4827. const nodes = extractFromCache( meta.nodes );
  4828. if ( geometries.length > 0 ) output.geometries = geometries;
  4829. if ( materials.length > 0 ) output.materials = materials;
  4830. if ( textures.length > 0 ) output.textures = textures;
  4831. if ( images.length > 0 ) output.images = images;
  4832. if ( shapes.length > 0 ) output.shapes = shapes;
  4833. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4834. if ( animations.length > 0 ) output.animations = animations;
  4835. if ( nodes.length > 0 ) output.nodes = nodes;
  4836. }
  4837. output.object = object;
  4838. return output;
  4839. // extract data from the cache hash
  4840. // remove metadata on each item
  4841. // and return as array
  4842. function extractFromCache( cache ) {
  4843. const values = [];
  4844. for ( const key in cache ) {
  4845. const data = cache[ key ];
  4846. delete data.metadata;
  4847. values.push( data );
  4848. }
  4849. return values;
  4850. }
  4851. }
  4852. clone( recursive ) {
  4853. return new this.constructor().copy( this, recursive );
  4854. }
  4855. copy( source, recursive = true ) {
  4856. this.name = source.name;
  4857. this.up.copy( source.up );
  4858. this.position.copy( source.position );
  4859. this.rotation.order = source.rotation.order;
  4860. this.quaternion.copy( source.quaternion );
  4861. this.scale.copy( source.scale );
  4862. this.matrix.copy( source.matrix );
  4863. this.matrixWorld.copy( source.matrixWorld );
  4864. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4865. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4866. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4867. this.layers.mask = source.layers.mask;
  4868. this.visible = source.visible;
  4869. this.castShadow = source.castShadow;
  4870. this.receiveShadow = source.receiveShadow;
  4871. this.frustumCulled = source.frustumCulled;
  4872. this.renderOrder = source.renderOrder;
  4873. this.animations = source.animations.slice();
  4874. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4875. if ( recursive === true ) {
  4876. for ( let i = 0; i < source.children.length; i ++ ) {
  4877. const child = source.children[ i ];
  4878. this.add( child.clone() );
  4879. }
  4880. }
  4881. return this;
  4882. }
  4883. }
  4884. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4885. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4886. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4887. const _v0$1 = /*@__PURE__*/ new Vector3();
  4888. const _v1$3 = /*@__PURE__*/ new Vector3();
  4889. const _v2$2 = /*@__PURE__*/ new Vector3();
  4890. const _v3$2 = /*@__PURE__*/ new Vector3();
  4891. const _vab = /*@__PURE__*/ new Vector3();
  4892. const _vac = /*@__PURE__*/ new Vector3();
  4893. const _vbc = /*@__PURE__*/ new Vector3();
  4894. const _vap = /*@__PURE__*/ new Vector3();
  4895. const _vbp = /*@__PURE__*/ new Vector3();
  4896. const _vcp = /*@__PURE__*/ new Vector3();
  4897. class Triangle {
  4898. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4899. this.a = a;
  4900. this.b = b;
  4901. this.c = c;
  4902. }
  4903. static getNormal( a, b, c, target ) {
  4904. target.subVectors( c, b );
  4905. _v0$1.subVectors( a, b );
  4906. target.cross( _v0$1 );
  4907. const targetLengthSq = target.lengthSq();
  4908. if ( targetLengthSq > 0 ) {
  4909. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4910. }
  4911. return target.set( 0, 0, 0 );
  4912. }
  4913. // static/instance method to calculate barycentric coordinates
  4914. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4915. static getBarycoord( point, a, b, c, target ) {
  4916. _v0$1.subVectors( c, a );
  4917. _v1$3.subVectors( b, a );
  4918. _v2$2.subVectors( point, a );
  4919. const dot00 = _v0$1.dot( _v0$1 );
  4920. const dot01 = _v0$1.dot( _v1$3 );
  4921. const dot02 = _v0$1.dot( _v2$2 );
  4922. const dot11 = _v1$3.dot( _v1$3 );
  4923. const dot12 = _v1$3.dot( _v2$2 );
  4924. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4925. // collinear or singular triangle
  4926. if ( denom === 0 ) {
  4927. target.set( 0, 0, 0 );
  4928. return null;
  4929. }
  4930. const invDenom = 1 / denom;
  4931. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4932. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4933. // barycentric coordinates must always sum to 1
  4934. return target.set( 1 - u - v, v, u );
  4935. }
  4936. static containsPoint( point, a, b, c ) {
  4937. // if the triangle is degenerate then we can't contain a point
  4938. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4939. return false;
  4940. }
  4941. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4942. }
  4943. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4944. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4945. target.x = 0;
  4946. target.y = 0;
  4947. if ( 'z' in target ) target.z = 0;
  4948. if ( 'w' in target ) target.w = 0;
  4949. return null;
  4950. }
  4951. target.setScalar( 0 );
  4952. target.addScaledVector( v1, _v3$2.x );
  4953. target.addScaledVector( v2, _v3$2.y );
  4954. target.addScaledVector( v3, _v3$2.z );
  4955. return target;
  4956. }
  4957. static isFrontFacing( a, b, c, direction ) {
  4958. _v0$1.subVectors( c, b );
  4959. _v1$3.subVectors( a, b );
  4960. // strictly front facing
  4961. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4962. }
  4963. set( a, b, c ) {
  4964. this.a.copy( a );
  4965. this.b.copy( b );
  4966. this.c.copy( c );
  4967. return this;
  4968. }
  4969. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4970. this.a.copy( points[ i0 ] );
  4971. this.b.copy( points[ i1 ] );
  4972. this.c.copy( points[ i2 ] );
  4973. return this;
  4974. }
  4975. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4976. this.a.fromBufferAttribute( attribute, i0 );
  4977. this.b.fromBufferAttribute( attribute, i1 );
  4978. this.c.fromBufferAttribute( attribute, i2 );
  4979. return this;
  4980. }
  4981. clone() {
  4982. return new this.constructor().copy( this );
  4983. }
  4984. copy( triangle ) {
  4985. this.a.copy( triangle.a );
  4986. this.b.copy( triangle.b );
  4987. this.c.copy( triangle.c );
  4988. return this;
  4989. }
  4990. getArea() {
  4991. _v0$1.subVectors( this.c, this.b );
  4992. _v1$3.subVectors( this.a, this.b );
  4993. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4994. }
  4995. getMidpoint( target ) {
  4996. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4997. }
  4998. getNormal( target ) {
  4999. return Triangle.getNormal( this.a, this.b, this.c, target );
  5000. }
  5001. getPlane( target ) {
  5002. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5003. }
  5004. getBarycoord( point, target ) {
  5005. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5006. }
  5007. getInterpolation( point, v1, v2, v3, target ) {
  5008. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5009. }
  5010. containsPoint( point ) {
  5011. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5012. }
  5013. isFrontFacing( direction ) {
  5014. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5015. }
  5016. intersectsBox( box ) {
  5017. return box.intersectsTriangle( this );
  5018. }
  5019. closestPointToPoint( p, target ) {
  5020. const a = this.a, b = this.b, c = this.c;
  5021. let v, w;
  5022. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5023. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5024. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5025. // basically, we're distinguishing which of the voronoi regions of the triangle
  5026. // the point lies in with the minimum amount of redundant computation.
  5027. _vab.subVectors( b, a );
  5028. _vac.subVectors( c, a );
  5029. _vap.subVectors( p, a );
  5030. const d1 = _vab.dot( _vap );
  5031. const d2 = _vac.dot( _vap );
  5032. if ( d1 <= 0 && d2 <= 0 ) {
  5033. // vertex region of A; barycentric coords (1, 0, 0)
  5034. return target.copy( a );
  5035. }
  5036. _vbp.subVectors( p, b );
  5037. const d3 = _vab.dot( _vbp );
  5038. const d4 = _vac.dot( _vbp );
  5039. if ( d3 >= 0 && d4 <= d3 ) {
  5040. // vertex region of B; barycentric coords (0, 1, 0)
  5041. return target.copy( b );
  5042. }
  5043. const vc = d1 * d4 - d3 * d2;
  5044. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5045. v = d1 / ( d1 - d3 );
  5046. // edge region of AB; barycentric coords (1-v, v, 0)
  5047. return target.copy( a ).addScaledVector( _vab, v );
  5048. }
  5049. _vcp.subVectors( p, c );
  5050. const d5 = _vab.dot( _vcp );
  5051. const d6 = _vac.dot( _vcp );
  5052. if ( d6 >= 0 && d5 <= d6 ) {
  5053. // vertex region of C; barycentric coords (0, 0, 1)
  5054. return target.copy( c );
  5055. }
  5056. const vb = d5 * d2 - d1 * d6;
  5057. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5058. w = d2 / ( d2 - d6 );
  5059. // edge region of AC; barycentric coords (1-w, 0, w)
  5060. return target.copy( a ).addScaledVector( _vac, w );
  5061. }
  5062. const va = d3 * d6 - d5 * d4;
  5063. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5064. _vbc.subVectors( c, b );
  5065. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5066. // edge region of BC; barycentric coords (0, 1-w, w)
  5067. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5068. }
  5069. // face region
  5070. const denom = 1 / ( va + vb + vc );
  5071. // u = va * denom
  5072. v = vb * denom;
  5073. w = vc * denom;
  5074. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5075. }
  5076. equals( triangle ) {
  5077. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5078. }
  5079. }
  5080. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5081. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5082. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5083. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5084. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5085. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5086. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5087. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5088. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5089. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5090. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5091. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5092. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5093. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5094. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5095. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5096. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5097. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5098. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5099. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5100. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5101. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5102. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5103. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5104. const _hslA = { h: 0, s: 0, l: 0 };
  5105. const _hslB = { h: 0, s: 0, l: 0 };
  5106. function hue2rgb( p, q, t ) {
  5107. if ( t < 0 ) t += 1;
  5108. if ( t > 1 ) t -= 1;
  5109. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5110. if ( t < 1 / 2 ) return q;
  5111. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5112. return p;
  5113. }
  5114. class Color {
  5115. constructor( r, g, b ) {
  5116. this.isColor = true;
  5117. this.r = 1;
  5118. this.g = 1;
  5119. this.b = 1;
  5120. return this.set( r, g, b );
  5121. }
  5122. set( r, g, b ) {
  5123. if ( g === undefined && b === undefined ) {
  5124. // r is THREE.Color, hex or string
  5125. const value = r;
  5126. if ( value && value.isColor ) {
  5127. this.copy( value );
  5128. } else if ( typeof value === 'number' ) {
  5129. this.setHex( value );
  5130. } else if ( typeof value === 'string' ) {
  5131. this.setStyle( value );
  5132. }
  5133. } else {
  5134. this.setRGB( r, g, b );
  5135. }
  5136. return this;
  5137. }
  5138. setScalar( scalar ) {
  5139. this.r = scalar;
  5140. this.g = scalar;
  5141. this.b = scalar;
  5142. return this;
  5143. }
  5144. setHex( hex, colorSpace = SRGBColorSpace ) {
  5145. hex = Math.floor( hex );
  5146. this.r = ( hex >> 16 & 255 ) / 255;
  5147. this.g = ( hex >> 8 & 255 ) / 255;
  5148. this.b = ( hex & 255 ) / 255;
  5149. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5150. return this;
  5151. }
  5152. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5153. this.r = r;
  5154. this.g = g;
  5155. this.b = b;
  5156. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5157. return this;
  5158. }
  5159. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5160. // h,s,l ranges are in 0.0 - 1.0
  5161. h = euclideanModulo( h, 1 );
  5162. s = clamp( s, 0, 1 );
  5163. l = clamp( l, 0, 1 );
  5164. if ( s === 0 ) {
  5165. this.r = this.g = this.b = l;
  5166. } else {
  5167. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5168. const q = ( 2 * l ) - p;
  5169. this.r = hue2rgb( q, p, h + 1 / 3 );
  5170. this.g = hue2rgb( q, p, h );
  5171. this.b = hue2rgb( q, p, h - 1 / 3 );
  5172. }
  5173. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5174. return this;
  5175. }
  5176. setStyle( style, colorSpace = SRGBColorSpace ) {
  5177. function handleAlpha( string ) {
  5178. if ( string === undefined ) return;
  5179. if ( parseFloat( string ) < 1 ) {
  5180. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5181. }
  5182. }
  5183. let m;
  5184. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5185. // rgb / hsl
  5186. let color;
  5187. const name = m[ 1 ];
  5188. const components = m[ 2 ];
  5189. switch ( name ) {
  5190. case 'rgb':
  5191. case 'rgba':
  5192. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5193. // rgb(255,0,0) rgba(255,0,0,0.5)
  5194. handleAlpha( color[ 4 ] );
  5195. return this.setRGB(
  5196. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5197. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5198. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5199. colorSpace
  5200. );
  5201. }
  5202. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5203. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5204. handleAlpha( color[ 4 ] );
  5205. return this.setRGB(
  5206. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5207. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5208. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5209. colorSpace
  5210. );
  5211. }
  5212. break;
  5213. case 'hsl':
  5214. case 'hsla':
  5215. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5216. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5217. handleAlpha( color[ 4 ] );
  5218. return this.setHSL(
  5219. parseFloat( color[ 1 ] ) / 360,
  5220. parseFloat( color[ 2 ] ) / 100,
  5221. parseFloat( color[ 3 ] ) / 100,
  5222. colorSpace
  5223. );
  5224. }
  5225. break;
  5226. default:
  5227. console.warn( 'THREE.Color: Unknown color model ' + style );
  5228. }
  5229. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5230. // hex color
  5231. const hex = m[ 1 ];
  5232. const size = hex.length;
  5233. if ( size === 3 ) {
  5234. // #ff0
  5235. return this.setRGB(
  5236. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5237. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5238. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5239. colorSpace
  5240. );
  5241. } else if ( size === 6 ) {
  5242. // #ff0000
  5243. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5244. } else {
  5245. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5246. }
  5247. } else if ( style && style.length > 0 ) {
  5248. return this.setColorName( style, colorSpace );
  5249. }
  5250. return this;
  5251. }
  5252. setColorName( style, colorSpace = SRGBColorSpace ) {
  5253. // color keywords
  5254. const hex = _colorKeywords[ style.toLowerCase() ];
  5255. if ( hex !== undefined ) {
  5256. // red
  5257. this.setHex( hex, colorSpace );
  5258. } else {
  5259. // unknown color
  5260. console.warn( 'THREE.Color: Unknown color ' + style );
  5261. }
  5262. return this;
  5263. }
  5264. clone() {
  5265. return new this.constructor( this.r, this.g, this.b );
  5266. }
  5267. copy( color ) {
  5268. this.r = color.r;
  5269. this.g = color.g;
  5270. this.b = color.b;
  5271. return this;
  5272. }
  5273. copySRGBToLinear( color ) {
  5274. this.r = SRGBToLinear( color.r );
  5275. this.g = SRGBToLinear( color.g );
  5276. this.b = SRGBToLinear( color.b );
  5277. return this;
  5278. }
  5279. copyLinearToSRGB( color ) {
  5280. this.r = LinearToSRGB( color.r );
  5281. this.g = LinearToSRGB( color.g );
  5282. this.b = LinearToSRGB( color.b );
  5283. return this;
  5284. }
  5285. convertSRGBToLinear() {
  5286. this.copySRGBToLinear( this );
  5287. return this;
  5288. }
  5289. convertLinearToSRGB() {
  5290. this.copyLinearToSRGB( this );
  5291. return this;
  5292. }
  5293. getHex( colorSpace = SRGBColorSpace ) {
  5294. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5295. 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 ) );
  5296. }
  5297. getHexString( colorSpace = SRGBColorSpace ) {
  5298. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5299. }
  5300. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5301. // h,s,l ranges are in 0.0 - 1.0
  5302. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5303. const r = _color.r, g = _color.g, b = _color.b;
  5304. const max = Math.max( r, g, b );
  5305. const min = Math.min( r, g, b );
  5306. let hue, saturation;
  5307. const lightness = ( min + max ) / 2.0;
  5308. if ( min === max ) {
  5309. hue = 0;
  5310. saturation = 0;
  5311. } else {
  5312. const delta = max - min;
  5313. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5314. switch ( max ) {
  5315. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5316. case g: hue = ( b - r ) / delta + 2; break;
  5317. case b: hue = ( r - g ) / delta + 4; break;
  5318. }
  5319. hue /= 6;
  5320. }
  5321. target.h = hue;
  5322. target.s = saturation;
  5323. target.l = lightness;
  5324. return target;
  5325. }
  5326. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5327. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5328. target.r = _color.r;
  5329. target.g = _color.g;
  5330. target.b = _color.b;
  5331. return target;
  5332. }
  5333. getStyle( colorSpace = SRGBColorSpace ) {
  5334. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5335. const r = _color.r, g = _color.g, b = _color.b;
  5336. if ( colorSpace !== SRGBColorSpace ) {
  5337. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5338. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5339. }
  5340. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5341. }
  5342. offsetHSL( h, s, l ) {
  5343. this.getHSL( _hslA );
  5344. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5345. }
  5346. add( color ) {
  5347. this.r += color.r;
  5348. this.g += color.g;
  5349. this.b += color.b;
  5350. return this;
  5351. }
  5352. addColors( color1, color2 ) {
  5353. this.r = color1.r + color2.r;
  5354. this.g = color1.g + color2.g;
  5355. this.b = color1.b + color2.b;
  5356. return this;
  5357. }
  5358. addScalar( s ) {
  5359. this.r += s;
  5360. this.g += s;
  5361. this.b += s;
  5362. return this;
  5363. }
  5364. sub( color ) {
  5365. this.r = Math.max( 0, this.r - color.r );
  5366. this.g = Math.max( 0, this.g - color.g );
  5367. this.b = Math.max( 0, this.b - color.b );
  5368. return this;
  5369. }
  5370. multiply( color ) {
  5371. this.r *= color.r;
  5372. this.g *= color.g;
  5373. this.b *= color.b;
  5374. return this;
  5375. }
  5376. multiplyScalar( s ) {
  5377. this.r *= s;
  5378. this.g *= s;
  5379. this.b *= s;
  5380. return this;
  5381. }
  5382. lerp( color, alpha ) {
  5383. this.r += ( color.r - this.r ) * alpha;
  5384. this.g += ( color.g - this.g ) * alpha;
  5385. this.b += ( color.b - this.b ) * alpha;
  5386. return this;
  5387. }
  5388. lerpColors( color1, color2, alpha ) {
  5389. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5390. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5391. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5392. return this;
  5393. }
  5394. lerpHSL( color, alpha ) {
  5395. this.getHSL( _hslA );
  5396. color.getHSL( _hslB );
  5397. const h = lerp( _hslA.h, _hslB.h, alpha );
  5398. const s = lerp( _hslA.s, _hslB.s, alpha );
  5399. const l = lerp( _hslA.l, _hslB.l, alpha );
  5400. this.setHSL( h, s, l );
  5401. return this;
  5402. }
  5403. setFromVector3( v ) {
  5404. this.r = v.x;
  5405. this.g = v.y;
  5406. this.b = v.z;
  5407. return this;
  5408. }
  5409. applyMatrix3( m ) {
  5410. const r = this.r, g = this.g, b = this.b;
  5411. const e = m.elements;
  5412. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5413. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5414. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5415. return this;
  5416. }
  5417. equals( c ) {
  5418. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5419. }
  5420. fromArray( array, offset = 0 ) {
  5421. this.r = array[ offset ];
  5422. this.g = array[ offset + 1 ];
  5423. this.b = array[ offset + 2 ];
  5424. return this;
  5425. }
  5426. toArray( array = [], offset = 0 ) {
  5427. array[ offset ] = this.r;
  5428. array[ offset + 1 ] = this.g;
  5429. array[ offset + 2 ] = this.b;
  5430. return array;
  5431. }
  5432. fromBufferAttribute( attribute, index ) {
  5433. this.r = attribute.getX( index );
  5434. this.g = attribute.getY( index );
  5435. this.b = attribute.getZ( index );
  5436. return this;
  5437. }
  5438. toJSON() {
  5439. return this.getHex();
  5440. }
  5441. *[ Symbol.iterator ]() {
  5442. yield this.r;
  5443. yield this.g;
  5444. yield this.b;
  5445. }
  5446. }
  5447. const _color = /*@__PURE__*/ new Color();
  5448. Color.NAMES = _colorKeywords;
  5449. let _materialId = 0;
  5450. class Material extends EventDispatcher {
  5451. constructor() {
  5452. super();
  5453. this.isMaterial = true;
  5454. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5455. this.uuid = generateUUID();
  5456. this.name = '';
  5457. this.type = 'Material';
  5458. this.blending = NormalBlending;
  5459. this.side = FrontSide;
  5460. this.vertexColors = false;
  5461. this.opacity = 1;
  5462. this.transparent = false;
  5463. this.alphaHash = false;
  5464. this.blendSrc = SrcAlphaFactor;
  5465. this.blendDst = OneMinusSrcAlphaFactor;
  5466. this.blendEquation = AddEquation;
  5467. this.blendSrcAlpha = null;
  5468. this.blendDstAlpha = null;
  5469. this.blendEquationAlpha = null;
  5470. this.blendColor = new Color( 0, 0, 0 );
  5471. this.blendAlpha = 0;
  5472. this.depthFunc = LessEqualDepth;
  5473. this.depthTest = true;
  5474. this.depthWrite = true;
  5475. this.stencilWriteMask = 0xff;
  5476. this.stencilFunc = AlwaysStencilFunc;
  5477. this.stencilRef = 0;
  5478. this.stencilFuncMask = 0xff;
  5479. this.stencilFail = KeepStencilOp;
  5480. this.stencilZFail = KeepStencilOp;
  5481. this.stencilZPass = KeepStencilOp;
  5482. this.stencilWrite = false;
  5483. this.clippingPlanes = null;
  5484. this.clipIntersection = false;
  5485. this.clipShadows = false;
  5486. this.shadowSide = null;
  5487. this.colorWrite = true;
  5488. this.precision = null; // override the renderer's default precision for this material
  5489. this.polygonOffset = false;
  5490. this.polygonOffsetFactor = 0;
  5491. this.polygonOffsetUnits = 0;
  5492. this.dithering = false;
  5493. this.alphaToCoverage = false;
  5494. this.premultipliedAlpha = false;
  5495. this.forceSinglePass = false;
  5496. this.visible = true;
  5497. this.toneMapped = true;
  5498. this.userData = {};
  5499. this.version = 0;
  5500. this._alphaTest = 0;
  5501. }
  5502. get alphaTest() {
  5503. return this._alphaTest;
  5504. }
  5505. set alphaTest( value ) {
  5506. if ( this._alphaTest > 0 !== value > 0 ) {
  5507. this.version ++;
  5508. }
  5509. this._alphaTest = value;
  5510. }
  5511. onBuild( /* shaderobject, renderer */ ) {}
  5512. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5513. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5514. customProgramCacheKey() {
  5515. return this.onBeforeCompile.toString();
  5516. }
  5517. setValues( values ) {
  5518. if ( values === undefined ) return;
  5519. for ( const key in values ) {
  5520. const newValue = values[ key ];
  5521. if ( newValue === undefined ) {
  5522. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5523. continue;
  5524. }
  5525. const currentValue = this[ key ];
  5526. if ( currentValue === undefined ) {
  5527. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5528. continue;
  5529. }
  5530. if ( currentValue && currentValue.isColor ) {
  5531. currentValue.set( newValue );
  5532. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5533. currentValue.copy( newValue );
  5534. } else {
  5535. this[ key ] = newValue;
  5536. }
  5537. }
  5538. }
  5539. toJSON( meta ) {
  5540. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5541. if ( isRootObject ) {
  5542. meta = {
  5543. textures: {},
  5544. images: {}
  5545. };
  5546. }
  5547. const data = {
  5548. metadata: {
  5549. version: 4.6,
  5550. type: 'Material',
  5551. generator: 'Material.toJSON'
  5552. }
  5553. };
  5554. // standard Material serialization
  5555. data.uuid = this.uuid;
  5556. data.type = this.type;
  5557. if ( this.name !== '' ) data.name = this.name;
  5558. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5559. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5560. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5561. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5562. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5563. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5564. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5565. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5566. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5567. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5568. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5569. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5570. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5571. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5572. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5573. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5574. }
  5575. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5576. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5577. }
  5578. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5579. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5580. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5581. }
  5582. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5583. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5584. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5585. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5586. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5587. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5588. }
  5589. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5590. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5591. }
  5592. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5593. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5594. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5595. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5596. }
  5597. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5598. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5599. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5600. if ( this.lightMap && this.lightMap.isTexture ) {
  5601. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5602. data.lightMapIntensity = this.lightMapIntensity;
  5603. }
  5604. if ( this.aoMap && this.aoMap.isTexture ) {
  5605. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5606. data.aoMapIntensity = this.aoMapIntensity;
  5607. }
  5608. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5609. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5610. data.bumpScale = this.bumpScale;
  5611. }
  5612. if ( this.normalMap && this.normalMap.isTexture ) {
  5613. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5614. data.normalMapType = this.normalMapType;
  5615. data.normalScale = this.normalScale.toArray();
  5616. }
  5617. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5618. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5619. data.displacementScale = this.displacementScale;
  5620. data.displacementBias = this.displacementBias;
  5621. }
  5622. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5623. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5624. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5625. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5626. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5627. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5628. if ( this.envMap && this.envMap.isTexture ) {
  5629. data.envMap = this.envMap.toJSON( meta ).uuid;
  5630. if ( this.combine !== undefined ) data.combine = this.combine;
  5631. }
  5632. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5633. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5634. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5635. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5636. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5637. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5638. }
  5639. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5640. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5641. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5642. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5643. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5644. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5645. if ( this.size !== undefined ) data.size = this.size;
  5646. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5647. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5648. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5649. if ( this.side !== FrontSide ) data.side = this.side;
  5650. if ( this.vertexColors === true ) data.vertexColors = true;
  5651. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5652. if ( this.transparent === true ) data.transparent = true;
  5653. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5654. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5655. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5656. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5657. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5658. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5659. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5660. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5661. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5662. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5663. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5664. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5665. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5666. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5667. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5668. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5669. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5670. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5671. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5672. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5673. // rotation (SpriteMaterial)
  5674. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5675. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5676. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5677. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5678. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5679. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5680. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5681. if ( this.scale !== undefined ) data.scale = this.scale;
  5682. if ( this.dithering === true ) data.dithering = true;
  5683. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5684. if ( this.alphaHash === true ) data.alphaHash = true;
  5685. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5686. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5687. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5688. if ( this.wireframe === true ) data.wireframe = true;
  5689. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5690. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5691. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5692. if ( this.flatShading === true ) data.flatShading = true;
  5693. if ( this.visible === false ) data.visible = false;
  5694. if ( this.toneMapped === false ) data.toneMapped = false;
  5695. if ( this.fog === false ) data.fog = false;
  5696. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5697. // TODO: Copied from Object3D.toJSON
  5698. function extractFromCache( cache ) {
  5699. const values = [];
  5700. for ( const key in cache ) {
  5701. const data = cache[ key ];
  5702. delete data.metadata;
  5703. values.push( data );
  5704. }
  5705. return values;
  5706. }
  5707. if ( isRootObject ) {
  5708. const textures = extractFromCache( meta.textures );
  5709. const images = extractFromCache( meta.images );
  5710. if ( textures.length > 0 ) data.textures = textures;
  5711. if ( images.length > 0 ) data.images = images;
  5712. }
  5713. return data;
  5714. }
  5715. clone() {
  5716. return new this.constructor().copy( this );
  5717. }
  5718. copy( source ) {
  5719. this.name = source.name;
  5720. this.blending = source.blending;
  5721. this.side = source.side;
  5722. this.vertexColors = source.vertexColors;
  5723. this.opacity = source.opacity;
  5724. this.transparent = source.transparent;
  5725. this.blendSrc = source.blendSrc;
  5726. this.blendDst = source.blendDst;
  5727. this.blendEquation = source.blendEquation;
  5728. this.blendSrcAlpha = source.blendSrcAlpha;
  5729. this.blendDstAlpha = source.blendDstAlpha;
  5730. this.blendEquationAlpha = source.blendEquationAlpha;
  5731. this.blendColor.copy( source.blendColor );
  5732. this.blendAlpha = source.blendAlpha;
  5733. this.depthFunc = source.depthFunc;
  5734. this.depthTest = source.depthTest;
  5735. this.depthWrite = source.depthWrite;
  5736. this.stencilWriteMask = source.stencilWriteMask;
  5737. this.stencilFunc = source.stencilFunc;
  5738. this.stencilRef = source.stencilRef;
  5739. this.stencilFuncMask = source.stencilFuncMask;
  5740. this.stencilFail = source.stencilFail;
  5741. this.stencilZFail = source.stencilZFail;
  5742. this.stencilZPass = source.stencilZPass;
  5743. this.stencilWrite = source.stencilWrite;
  5744. const srcPlanes = source.clippingPlanes;
  5745. let dstPlanes = null;
  5746. if ( srcPlanes !== null ) {
  5747. const n = srcPlanes.length;
  5748. dstPlanes = new Array( n );
  5749. for ( let i = 0; i !== n; ++ i ) {
  5750. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5751. }
  5752. }
  5753. this.clippingPlanes = dstPlanes;
  5754. this.clipIntersection = source.clipIntersection;
  5755. this.clipShadows = source.clipShadows;
  5756. this.shadowSide = source.shadowSide;
  5757. this.colorWrite = source.colorWrite;
  5758. this.precision = source.precision;
  5759. this.polygonOffset = source.polygonOffset;
  5760. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5761. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5762. this.dithering = source.dithering;
  5763. this.alphaTest = source.alphaTest;
  5764. this.alphaHash = source.alphaHash;
  5765. this.alphaToCoverage = source.alphaToCoverage;
  5766. this.premultipliedAlpha = source.premultipliedAlpha;
  5767. this.forceSinglePass = source.forceSinglePass;
  5768. this.visible = source.visible;
  5769. this.toneMapped = source.toneMapped;
  5770. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5771. return this;
  5772. }
  5773. dispose() {
  5774. this.dispatchEvent( { type: 'dispose' } );
  5775. }
  5776. set needsUpdate( value ) {
  5777. if ( value === true ) this.version ++;
  5778. }
  5779. }
  5780. class MeshBasicMaterial extends Material {
  5781. constructor( parameters ) {
  5782. super();
  5783. this.isMeshBasicMaterial = true;
  5784. this.type = 'MeshBasicMaterial';
  5785. this.color = new Color( 0xffffff ); // emissive
  5786. this.map = null;
  5787. this.lightMap = null;
  5788. this.lightMapIntensity = 1.0;
  5789. this.aoMap = null;
  5790. this.aoMapIntensity = 1.0;
  5791. this.specularMap = null;
  5792. this.alphaMap = null;
  5793. this.envMap = null;
  5794. this.envMapRotation = new Euler();
  5795. this.combine = MultiplyOperation;
  5796. this.reflectivity = 1;
  5797. this.refractionRatio = 0.98;
  5798. this.wireframe = false;
  5799. this.wireframeLinewidth = 1;
  5800. this.wireframeLinecap = 'round';
  5801. this.wireframeLinejoin = 'round';
  5802. this.fog = true;
  5803. this.setValues( parameters );
  5804. }
  5805. copy( source ) {
  5806. super.copy( source );
  5807. this.color.copy( source.color );
  5808. this.map = source.map;
  5809. this.lightMap = source.lightMap;
  5810. this.lightMapIntensity = source.lightMapIntensity;
  5811. this.aoMap = source.aoMap;
  5812. this.aoMapIntensity = source.aoMapIntensity;
  5813. this.specularMap = source.specularMap;
  5814. this.alphaMap = source.alphaMap;
  5815. this.envMap = source.envMap;
  5816. this.envMapRotation.copy( source.envMapRotation );
  5817. this.combine = source.combine;
  5818. this.reflectivity = source.reflectivity;
  5819. this.refractionRatio = source.refractionRatio;
  5820. this.wireframe = source.wireframe;
  5821. this.wireframeLinewidth = source.wireframeLinewidth;
  5822. this.wireframeLinecap = source.wireframeLinecap;
  5823. this.wireframeLinejoin = source.wireframeLinejoin;
  5824. this.fog = source.fog;
  5825. return this;
  5826. }
  5827. }
  5828. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5829. const _tables = /*@__PURE__*/ _generateTables();
  5830. function _generateTables() {
  5831. // float32 to float16 helpers
  5832. const buffer = new ArrayBuffer( 4 );
  5833. const floatView = new Float32Array( buffer );
  5834. const uint32View = new Uint32Array( buffer );
  5835. const baseTable = new Uint32Array( 512 );
  5836. const shiftTable = new Uint32Array( 512 );
  5837. for ( let i = 0; i < 256; ++ i ) {
  5838. const e = i - 127;
  5839. // very small number (0, -0)
  5840. if ( e < - 27 ) {
  5841. baseTable[ i ] = 0x0000;
  5842. baseTable[ i | 0x100 ] = 0x8000;
  5843. shiftTable[ i ] = 24;
  5844. shiftTable[ i | 0x100 ] = 24;
  5845. // small number (denorm)
  5846. } else if ( e < - 14 ) {
  5847. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5848. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5849. shiftTable[ i ] = - e - 1;
  5850. shiftTable[ i | 0x100 ] = - e - 1;
  5851. // normal number
  5852. } else if ( e <= 15 ) {
  5853. baseTable[ i ] = ( e + 15 ) << 10;
  5854. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5855. shiftTable[ i ] = 13;
  5856. shiftTable[ i | 0x100 ] = 13;
  5857. // large number (Infinity, -Infinity)
  5858. } else if ( e < 128 ) {
  5859. baseTable[ i ] = 0x7c00;
  5860. baseTable[ i | 0x100 ] = 0xfc00;
  5861. shiftTable[ i ] = 24;
  5862. shiftTable[ i | 0x100 ] = 24;
  5863. // stay (NaN, Infinity, -Infinity)
  5864. } else {
  5865. baseTable[ i ] = 0x7c00;
  5866. baseTable[ i | 0x100 ] = 0xfc00;
  5867. shiftTable[ i ] = 13;
  5868. shiftTable[ i | 0x100 ] = 13;
  5869. }
  5870. }
  5871. // float16 to float32 helpers
  5872. const mantissaTable = new Uint32Array( 2048 );
  5873. const exponentTable = new Uint32Array( 64 );
  5874. const offsetTable = new Uint32Array( 64 );
  5875. for ( let i = 1; i < 1024; ++ i ) {
  5876. let m = i << 13; // zero pad mantissa bits
  5877. let e = 0; // zero exponent
  5878. // normalized
  5879. while ( ( m & 0x00800000 ) === 0 ) {
  5880. m <<= 1;
  5881. e -= 0x00800000; // decrement exponent
  5882. }
  5883. m &= ~ 0x00800000; // clear leading 1 bit
  5884. e += 0x38800000; // adjust bias
  5885. mantissaTable[ i ] = m | e;
  5886. }
  5887. for ( let i = 1024; i < 2048; ++ i ) {
  5888. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5889. }
  5890. for ( let i = 1; i < 31; ++ i ) {
  5891. exponentTable[ i ] = i << 23;
  5892. }
  5893. exponentTable[ 31 ] = 0x47800000;
  5894. exponentTable[ 32 ] = 0x80000000;
  5895. for ( let i = 33; i < 63; ++ i ) {
  5896. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5897. }
  5898. exponentTable[ 63 ] = 0xc7800000;
  5899. for ( let i = 1; i < 64; ++ i ) {
  5900. if ( i !== 32 ) {
  5901. offsetTable[ i ] = 1024;
  5902. }
  5903. }
  5904. return {
  5905. floatView: floatView,
  5906. uint32View: uint32View,
  5907. baseTable: baseTable,
  5908. shiftTable: shiftTable,
  5909. mantissaTable: mantissaTable,
  5910. exponentTable: exponentTable,
  5911. offsetTable: offsetTable
  5912. };
  5913. }
  5914. // float32 to float16
  5915. function toHalfFloat( val ) {
  5916. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5917. val = clamp( val, - 65504, 65504 );
  5918. _tables.floatView[ 0 ] = val;
  5919. const f = _tables.uint32View[ 0 ];
  5920. const e = ( f >> 23 ) & 0x1ff;
  5921. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5922. }
  5923. // float16 to float32
  5924. function fromHalfFloat( val ) {
  5925. const m = val >> 10;
  5926. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5927. return _tables.floatView[ 0 ];
  5928. }
  5929. const DataUtils = {
  5930. toHalfFloat: toHalfFloat,
  5931. fromHalfFloat: fromHalfFloat,
  5932. };
  5933. const _vector$9 = /*@__PURE__*/ new Vector3();
  5934. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5935. class BufferAttribute {
  5936. constructor( array, itemSize, normalized = false ) {
  5937. if ( Array.isArray( array ) ) {
  5938. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5939. }
  5940. this.isBufferAttribute = true;
  5941. this.name = '';
  5942. this.array = array;
  5943. this.itemSize = itemSize;
  5944. this.count = array !== undefined ? array.length / itemSize : 0;
  5945. this.normalized = normalized;
  5946. this.usage = StaticDrawUsage;
  5947. this._updateRange = { offset: 0, count: - 1 };
  5948. this.updateRanges = [];
  5949. this.gpuType = FloatType;
  5950. this.version = 0;
  5951. }
  5952. onUploadCallback() {}
  5953. set needsUpdate( value ) {
  5954. if ( value === true ) this.version ++;
  5955. }
  5956. get updateRange() {
  5957. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5958. return this._updateRange;
  5959. }
  5960. setUsage( value ) {
  5961. this.usage = value;
  5962. return this;
  5963. }
  5964. addUpdateRange( start, count ) {
  5965. this.updateRanges.push( { start, count } );
  5966. }
  5967. clearUpdateRanges() {
  5968. this.updateRanges.length = 0;
  5969. }
  5970. copy( source ) {
  5971. this.name = source.name;
  5972. this.array = new source.array.constructor( source.array );
  5973. this.itemSize = source.itemSize;
  5974. this.count = source.count;
  5975. this.normalized = source.normalized;
  5976. this.usage = source.usage;
  5977. this.gpuType = source.gpuType;
  5978. return this;
  5979. }
  5980. copyAt( index1, attribute, index2 ) {
  5981. index1 *= this.itemSize;
  5982. index2 *= attribute.itemSize;
  5983. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5984. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5985. }
  5986. return this;
  5987. }
  5988. copyArray( array ) {
  5989. this.array.set( array );
  5990. return this;
  5991. }
  5992. applyMatrix3( m ) {
  5993. if ( this.itemSize === 2 ) {
  5994. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5995. _vector2$1.fromBufferAttribute( this, i );
  5996. _vector2$1.applyMatrix3( m );
  5997. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5998. }
  5999. } else if ( this.itemSize === 3 ) {
  6000. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6001. _vector$9.fromBufferAttribute( this, i );
  6002. _vector$9.applyMatrix3( m );
  6003. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6004. }
  6005. }
  6006. return this;
  6007. }
  6008. applyMatrix4( m ) {
  6009. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6010. _vector$9.fromBufferAttribute( this, i );
  6011. _vector$9.applyMatrix4( m );
  6012. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6013. }
  6014. return this;
  6015. }
  6016. applyNormalMatrix( m ) {
  6017. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6018. _vector$9.fromBufferAttribute( this, i );
  6019. _vector$9.applyNormalMatrix( m );
  6020. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6021. }
  6022. return this;
  6023. }
  6024. transformDirection( m ) {
  6025. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6026. _vector$9.fromBufferAttribute( this, i );
  6027. _vector$9.transformDirection( m );
  6028. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6029. }
  6030. return this;
  6031. }
  6032. set( value, offset = 0 ) {
  6033. // Matching BufferAttribute constructor, do not normalize the array.
  6034. this.array.set( value, offset );
  6035. return this;
  6036. }
  6037. getComponent( index, component ) {
  6038. let value = this.array[ index * this.itemSize + component ];
  6039. if ( this.normalized ) value = denormalize( value, this.array );
  6040. return value;
  6041. }
  6042. setComponent( index, component, value ) {
  6043. if ( this.normalized ) value = normalize( value, this.array );
  6044. this.array[ index * this.itemSize + component ] = value;
  6045. return this;
  6046. }
  6047. getX( index ) {
  6048. let x = this.array[ index * this.itemSize ];
  6049. if ( this.normalized ) x = denormalize( x, this.array );
  6050. return x;
  6051. }
  6052. setX( index, x ) {
  6053. if ( this.normalized ) x = normalize( x, this.array );
  6054. this.array[ index * this.itemSize ] = x;
  6055. return this;
  6056. }
  6057. getY( index ) {
  6058. let y = this.array[ index * this.itemSize + 1 ];
  6059. if ( this.normalized ) y = denormalize( y, this.array );
  6060. return y;
  6061. }
  6062. setY( index, y ) {
  6063. if ( this.normalized ) y = normalize( y, this.array );
  6064. this.array[ index * this.itemSize + 1 ] = y;
  6065. return this;
  6066. }
  6067. getZ( index ) {
  6068. let z = this.array[ index * this.itemSize + 2 ];
  6069. if ( this.normalized ) z = denormalize( z, this.array );
  6070. return z;
  6071. }
  6072. setZ( index, z ) {
  6073. if ( this.normalized ) z = normalize( z, this.array );
  6074. this.array[ index * this.itemSize + 2 ] = z;
  6075. return this;
  6076. }
  6077. getW( index ) {
  6078. let w = this.array[ index * this.itemSize + 3 ];
  6079. if ( this.normalized ) w = denormalize( w, this.array );
  6080. return w;
  6081. }
  6082. setW( index, w ) {
  6083. if ( this.normalized ) w = normalize( w, this.array );
  6084. this.array[ index * this.itemSize + 3 ] = w;
  6085. return this;
  6086. }
  6087. setXY( index, x, y ) {
  6088. index *= this.itemSize;
  6089. if ( this.normalized ) {
  6090. x = normalize( x, this.array );
  6091. y = normalize( y, this.array );
  6092. }
  6093. this.array[ index + 0 ] = x;
  6094. this.array[ index + 1 ] = y;
  6095. return this;
  6096. }
  6097. setXYZ( index, x, y, z ) {
  6098. index *= this.itemSize;
  6099. if ( this.normalized ) {
  6100. x = normalize( x, this.array );
  6101. y = normalize( y, this.array );
  6102. z = normalize( z, this.array );
  6103. }
  6104. this.array[ index + 0 ] = x;
  6105. this.array[ index + 1 ] = y;
  6106. this.array[ index + 2 ] = z;
  6107. return this;
  6108. }
  6109. setXYZW( index, x, y, z, w ) {
  6110. index *= this.itemSize;
  6111. if ( this.normalized ) {
  6112. x = normalize( x, this.array );
  6113. y = normalize( y, this.array );
  6114. z = normalize( z, this.array );
  6115. w = normalize( w, this.array );
  6116. }
  6117. this.array[ index + 0 ] = x;
  6118. this.array[ index + 1 ] = y;
  6119. this.array[ index + 2 ] = z;
  6120. this.array[ index + 3 ] = w;
  6121. return this;
  6122. }
  6123. onUpload( callback ) {
  6124. this.onUploadCallback = callback;
  6125. return this;
  6126. }
  6127. clone() {
  6128. return new this.constructor( this.array, this.itemSize ).copy( this );
  6129. }
  6130. toJSON() {
  6131. const data = {
  6132. itemSize: this.itemSize,
  6133. type: this.array.constructor.name,
  6134. array: Array.from( this.array ),
  6135. normalized: this.normalized
  6136. };
  6137. if ( this.name !== '' ) data.name = this.name;
  6138. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6139. return data;
  6140. }
  6141. }
  6142. //
  6143. class Int8BufferAttribute extends BufferAttribute {
  6144. constructor( array, itemSize, normalized ) {
  6145. super( new Int8Array( array ), itemSize, normalized );
  6146. }
  6147. }
  6148. class Uint8BufferAttribute extends BufferAttribute {
  6149. constructor( array, itemSize, normalized ) {
  6150. super( new Uint8Array( array ), itemSize, normalized );
  6151. }
  6152. }
  6153. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6154. constructor( array, itemSize, normalized ) {
  6155. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6156. }
  6157. }
  6158. class Int16BufferAttribute extends BufferAttribute {
  6159. constructor( array, itemSize, normalized ) {
  6160. super( new Int16Array( array ), itemSize, normalized );
  6161. }
  6162. }
  6163. class Uint16BufferAttribute extends BufferAttribute {
  6164. constructor( array, itemSize, normalized ) {
  6165. super( new Uint16Array( array ), itemSize, normalized );
  6166. }
  6167. }
  6168. class Int32BufferAttribute extends BufferAttribute {
  6169. constructor( array, itemSize, normalized ) {
  6170. super( new Int32Array( array ), itemSize, normalized );
  6171. }
  6172. }
  6173. class Uint32BufferAttribute extends BufferAttribute {
  6174. constructor( array, itemSize, normalized ) {
  6175. super( new Uint32Array( array ), itemSize, normalized );
  6176. }
  6177. }
  6178. class Float16BufferAttribute extends BufferAttribute {
  6179. constructor( array, itemSize, normalized ) {
  6180. super( new Uint16Array( array ), itemSize, normalized );
  6181. this.isFloat16BufferAttribute = true;
  6182. }
  6183. getX( index ) {
  6184. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6185. if ( this.normalized ) x = denormalize( x, this.array );
  6186. return x;
  6187. }
  6188. setX( index, x ) {
  6189. if ( this.normalized ) x = normalize( x, this.array );
  6190. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6191. return this;
  6192. }
  6193. getY( index ) {
  6194. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6195. if ( this.normalized ) y = denormalize( y, this.array );
  6196. return y;
  6197. }
  6198. setY( index, y ) {
  6199. if ( this.normalized ) y = normalize( y, this.array );
  6200. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6201. return this;
  6202. }
  6203. getZ( index ) {
  6204. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6205. if ( this.normalized ) z = denormalize( z, this.array );
  6206. return z;
  6207. }
  6208. setZ( index, z ) {
  6209. if ( this.normalized ) z = normalize( z, this.array );
  6210. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6211. return this;
  6212. }
  6213. getW( index ) {
  6214. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6215. if ( this.normalized ) w = denormalize( w, this.array );
  6216. return w;
  6217. }
  6218. setW( index, w ) {
  6219. if ( this.normalized ) w = normalize( w, this.array );
  6220. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6221. return this;
  6222. }
  6223. setXY( index, x, y ) {
  6224. index *= this.itemSize;
  6225. if ( this.normalized ) {
  6226. x = normalize( x, this.array );
  6227. y = normalize( y, this.array );
  6228. }
  6229. this.array[ index + 0 ] = toHalfFloat( x );
  6230. this.array[ index + 1 ] = toHalfFloat( y );
  6231. return this;
  6232. }
  6233. setXYZ( index, x, y, z ) {
  6234. index *= this.itemSize;
  6235. if ( this.normalized ) {
  6236. x = normalize( x, this.array );
  6237. y = normalize( y, this.array );
  6238. z = normalize( z, this.array );
  6239. }
  6240. this.array[ index + 0 ] = toHalfFloat( x );
  6241. this.array[ index + 1 ] = toHalfFloat( y );
  6242. this.array[ index + 2 ] = toHalfFloat( z );
  6243. return this;
  6244. }
  6245. setXYZW( index, x, y, z, w ) {
  6246. index *= this.itemSize;
  6247. if ( this.normalized ) {
  6248. x = normalize( x, this.array );
  6249. y = normalize( y, this.array );
  6250. z = normalize( z, this.array );
  6251. w = normalize( w, this.array );
  6252. }
  6253. this.array[ index + 0 ] = toHalfFloat( x );
  6254. this.array[ index + 1 ] = toHalfFloat( y );
  6255. this.array[ index + 2 ] = toHalfFloat( z );
  6256. this.array[ index + 3 ] = toHalfFloat( w );
  6257. return this;
  6258. }
  6259. }
  6260. class Float32BufferAttribute extends BufferAttribute {
  6261. constructor( array, itemSize, normalized ) {
  6262. super( new Float32Array( array ), itemSize, normalized );
  6263. }
  6264. }
  6265. let _id$2 = 0;
  6266. const _m1$2 = /*@__PURE__*/ new Matrix4();
  6267. const _obj = /*@__PURE__*/ new Object3D();
  6268. const _offset = /*@__PURE__*/ new Vector3();
  6269. const _box$2 = /*@__PURE__*/ new Box3();
  6270. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6271. const _vector$8 = /*@__PURE__*/ new Vector3();
  6272. class BufferGeometry extends EventDispatcher {
  6273. constructor() {
  6274. super();
  6275. this.isBufferGeometry = true;
  6276. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6277. this.uuid = generateUUID();
  6278. this.name = '';
  6279. this.type = 'BufferGeometry';
  6280. this.index = null;
  6281. this.attributes = {};
  6282. this.morphAttributes = {};
  6283. this.morphTargetsRelative = false;
  6284. this.groups = [];
  6285. this.boundingBox = null;
  6286. this.boundingSphere = null;
  6287. this.drawRange = { start: 0, count: Infinity };
  6288. this.userData = {};
  6289. }
  6290. getIndex() {
  6291. return this.index;
  6292. }
  6293. setIndex( index ) {
  6294. if ( Array.isArray( index ) ) {
  6295. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6296. } else {
  6297. this.index = index;
  6298. }
  6299. return this;
  6300. }
  6301. getAttribute( name ) {
  6302. return this.attributes[ name ];
  6303. }
  6304. setAttribute( name, attribute ) {
  6305. this.attributes[ name ] = attribute;
  6306. return this;
  6307. }
  6308. deleteAttribute( name ) {
  6309. delete this.attributes[ name ];
  6310. return this;
  6311. }
  6312. hasAttribute( name ) {
  6313. return this.attributes[ name ] !== undefined;
  6314. }
  6315. addGroup( start, count, materialIndex = 0 ) {
  6316. this.groups.push( {
  6317. start: start,
  6318. count: count,
  6319. materialIndex: materialIndex
  6320. } );
  6321. }
  6322. clearGroups() {
  6323. this.groups = [];
  6324. }
  6325. setDrawRange( start, count ) {
  6326. this.drawRange.start = start;
  6327. this.drawRange.count = count;
  6328. }
  6329. applyMatrix4( matrix ) {
  6330. const position = this.attributes.position;
  6331. if ( position !== undefined ) {
  6332. position.applyMatrix4( matrix );
  6333. position.needsUpdate = true;
  6334. }
  6335. const normal = this.attributes.normal;
  6336. if ( normal !== undefined ) {
  6337. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6338. normal.applyNormalMatrix( normalMatrix );
  6339. normal.needsUpdate = true;
  6340. }
  6341. const tangent = this.attributes.tangent;
  6342. if ( tangent !== undefined ) {
  6343. tangent.transformDirection( matrix );
  6344. tangent.needsUpdate = true;
  6345. }
  6346. if ( this.boundingBox !== null ) {
  6347. this.computeBoundingBox();
  6348. }
  6349. if ( this.boundingSphere !== null ) {
  6350. this.computeBoundingSphere();
  6351. }
  6352. return this;
  6353. }
  6354. applyQuaternion( q ) {
  6355. _m1$2.makeRotationFromQuaternion( q );
  6356. this.applyMatrix4( _m1$2 );
  6357. return this;
  6358. }
  6359. rotateX( angle ) {
  6360. // rotate geometry around world x-axis
  6361. _m1$2.makeRotationX( angle );
  6362. this.applyMatrix4( _m1$2 );
  6363. return this;
  6364. }
  6365. rotateY( angle ) {
  6366. // rotate geometry around world y-axis
  6367. _m1$2.makeRotationY( angle );
  6368. this.applyMatrix4( _m1$2 );
  6369. return this;
  6370. }
  6371. rotateZ( angle ) {
  6372. // rotate geometry around world z-axis
  6373. _m1$2.makeRotationZ( angle );
  6374. this.applyMatrix4( _m1$2 );
  6375. return this;
  6376. }
  6377. translate( x, y, z ) {
  6378. // translate geometry
  6379. _m1$2.makeTranslation( x, y, z );
  6380. this.applyMatrix4( _m1$2 );
  6381. return this;
  6382. }
  6383. scale( x, y, z ) {
  6384. // scale geometry
  6385. _m1$2.makeScale( x, y, z );
  6386. this.applyMatrix4( _m1$2 );
  6387. return this;
  6388. }
  6389. lookAt( vector ) {
  6390. _obj.lookAt( vector );
  6391. _obj.updateMatrix();
  6392. this.applyMatrix4( _obj.matrix );
  6393. return this;
  6394. }
  6395. center() {
  6396. this.computeBoundingBox();
  6397. this.boundingBox.getCenter( _offset ).negate();
  6398. this.translate( _offset.x, _offset.y, _offset.z );
  6399. return this;
  6400. }
  6401. setFromPoints( points ) {
  6402. const position = [];
  6403. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6404. const point = points[ i ];
  6405. position.push( point.x, point.y, point.z || 0 );
  6406. }
  6407. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6408. return this;
  6409. }
  6410. computeBoundingBox() {
  6411. if ( this.boundingBox === null ) {
  6412. this.boundingBox = new Box3();
  6413. }
  6414. const position = this.attributes.position;
  6415. const morphAttributesPosition = this.morphAttributes.position;
  6416. if ( position && position.isGLBufferAttribute ) {
  6417. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6418. this.boundingBox.set(
  6419. new Vector3( - Infinity, - Infinity, - Infinity ),
  6420. new Vector3( + Infinity, + Infinity, + Infinity )
  6421. );
  6422. return;
  6423. }
  6424. if ( position !== undefined ) {
  6425. this.boundingBox.setFromBufferAttribute( position );
  6426. // process morph attributes if present
  6427. if ( morphAttributesPosition ) {
  6428. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6429. const morphAttribute = morphAttributesPosition[ i ];
  6430. _box$2.setFromBufferAttribute( morphAttribute );
  6431. if ( this.morphTargetsRelative ) {
  6432. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6433. this.boundingBox.expandByPoint( _vector$8 );
  6434. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6435. this.boundingBox.expandByPoint( _vector$8 );
  6436. } else {
  6437. this.boundingBox.expandByPoint( _box$2.min );
  6438. this.boundingBox.expandByPoint( _box$2.max );
  6439. }
  6440. }
  6441. }
  6442. } else {
  6443. this.boundingBox.makeEmpty();
  6444. }
  6445. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6446. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6447. }
  6448. }
  6449. computeBoundingSphere() {
  6450. if ( this.boundingSphere === null ) {
  6451. this.boundingSphere = new Sphere();
  6452. }
  6453. const position = this.attributes.position;
  6454. const morphAttributesPosition = this.morphAttributes.position;
  6455. if ( position && position.isGLBufferAttribute ) {
  6456. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6457. this.boundingSphere.set( new Vector3(), Infinity );
  6458. return;
  6459. }
  6460. if ( position ) {
  6461. // first, find the center of the bounding sphere
  6462. const center = this.boundingSphere.center;
  6463. _box$2.setFromBufferAttribute( position );
  6464. // process morph attributes if present
  6465. if ( morphAttributesPosition ) {
  6466. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6467. const morphAttribute = morphAttributesPosition[ i ];
  6468. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6469. if ( this.morphTargetsRelative ) {
  6470. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6471. _box$2.expandByPoint( _vector$8 );
  6472. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6473. _box$2.expandByPoint( _vector$8 );
  6474. } else {
  6475. _box$2.expandByPoint( _boxMorphTargets.min );
  6476. _box$2.expandByPoint( _boxMorphTargets.max );
  6477. }
  6478. }
  6479. }
  6480. _box$2.getCenter( center );
  6481. // second, try to find a boundingSphere with a radius smaller than the
  6482. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6483. let maxRadiusSq = 0;
  6484. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6485. _vector$8.fromBufferAttribute( position, i );
  6486. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6487. }
  6488. // process morph attributes if present
  6489. if ( morphAttributesPosition ) {
  6490. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6491. const morphAttribute = morphAttributesPosition[ i ];
  6492. const morphTargetsRelative = this.morphTargetsRelative;
  6493. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6494. _vector$8.fromBufferAttribute( morphAttribute, j );
  6495. if ( morphTargetsRelative ) {
  6496. _offset.fromBufferAttribute( position, j );
  6497. _vector$8.add( _offset );
  6498. }
  6499. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6500. }
  6501. }
  6502. }
  6503. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6504. if ( isNaN( this.boundingSphere.radius ) ) {
  6505. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6506. }
  6507. }
  6508. }
  6509. computeTangents() {
  6510. const index = this.index;
  6511. const attributes = this.attributes;
  6512. // based on http://www.terathon.com/code/tangent.html
  6513. // (per vertex tangents)
  6514. if ( index === null ||
  6515. attributes.position === undefined ||
  6516. attributes.normal === undefined ||
  6517. attributes.uv === undefined ) {
  6518. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6519. return;
  6520. }
  6521. const positionAttribute = attributes.position;
  6522. const normalAttribute = attributes.normal;
  6523. const uvAttribute = attributes.uv;
  6524. if ( this.hasAttribute( 'tangent' ) === false ) {
  6525. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6526. }
  6527. const tangentAttribute = this.getAttribute( 'tangent' );
  6528. const tan1 = [], tan2 = [];
  6529. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6530. tan1[ i ] = new Vector3();
  6531. tan2[ i ] = new Vector3();
  6532. }
  6533. const vA = new Vector3(),
  6534. vB = new Vector3(),
  6535. vC = new Vector3(),
  6536. uvA = new Vector2(),
  6537. uvB = new Vector2(),
  6538. uvC = new Vector2(),
  6539. sdir = new Vector3(),
  6540. tdir = new Vector3();
  6541. function handleTriangle( a, b, c ) {
  6542. vA.fromBufferAttribute( positionAttribute, a );
  6543. vB.fromBufferAttribute( positionAttribute, b );
  6544. vC.fromBufferAttribute( positionAttribute, c );
  6545. uvA.fromBufferAttribute( uvAttribute, a );
  6546. uvB.fromBufferAttribute( uvAttribute, b );
  6547. uvC.fromBufferAttribute( uvAttribute, c );
  6548. vB.sub( vA );
  6549. vC.sub( vA );
  6550. uvB.sub( uvA );
  6551. uvC.sub( uvA );
  6552. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6553. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6554. if ( ! isFinite( r ) ) return;
  6555. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6556. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6557. tan1[ a ].add( sdir );
  6558. tan1[ b ].add( sdir );
  6559. tan1[ c ].add( sdir );
  6560. tan2[ a ].add( tdir );
  6561. tan2[ b ].add( tdir );
  6562. tan2[ c ].add( tdir );
  6563. }
  6564. let groups = this.groups;
  6565. if ( groups.length === 0 ) {
  6566. groups = [ {
  6567. start: 0,
  6568. count: index.count
  6569. } ];
  6570. }
  6571. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6572. const group = groups[ i ];
  6573. const start = group.start;
  6574. const count = group.count;
  6575. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6576. handleTriangle(
  6577. index.getX( j + 0 ),
  6578. index.getX( j + 1 ),
  6579. index.getX( j + 2 )
  6580. );
  6581. }
  6582. }
  6583. const tmp = new Vector3(), tmp2 = new Vector3();
  6584. const n = new Vector3(), n2 = new Vector3();
  6585. function handleVertex( v ) {
  6586. n.fromBufferAttribute( normalAttribute, v );
  6587. n2.copy( n );
  6588. const t = tan1[ v ];
  6589. // Gram-Schmidt orthogonalize
  6590. tmp.copy( t );
  6591. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6592. // Calculate handedness
  6593. tmp2.crossVectors( n2, t );
  6594. const test = tmp2.dot( tan2[ v ] );
  6595. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6596. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6597. }
  6598. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6599. const group = groups[ i ];
  6600. const start = group.start;
  6601. const count = group.count;
  6602. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6603. handleVertex( index.getX( j + 0 ) );
  6604. handleVertex( index.getX( j + 1 ) );
  6605. handleVertex( index.getX( j + 2 ) );
  6606. }
  6607. }
  6608. }
  6609. computeVertexNormals() {
  6610. const index = this.index;
  6611. const positionAttribute = this.getAttribute( 'position' );
  6612. if ( positionAttribute !== undefined ) {
  6613. let normalAttribute = this.getAttribute( 'normal' );
  6614. if ( normalAttribute === undefined ) {
  6615. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6616. this.setAttribute( 'normal', normalAttribute );
  6617. } else {
  6618. // reset existing normals to zero
  6619. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6620. normalAttribute.setXYZ( i, 0, 0, 0 );
  6621. }
  6622. }
  6623. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6624. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6625. const cb = new Vector3(), ab = new Vector3();
  6626. // indexed elements
  6627. if ( index ) {
  6628. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6629. const vA = index.getX( i + 0 );
  6630. const vB = index.getX( i + 1 );
  6631. const vC = index.getX( i + 2 );
  6632. pA.fromBufferAttribute( positionAttribute, vA );
  6633. pB.fromBufferAttribute( positionAttribute, vB );
  6634. pC.fromBufferAttribute( positionAttribute, vC );
  6635. cb.subVectors( pC, pB );
  6636. ab.subVectors( pA, pB );
  6637. cb.cross( ab );
  6638. nA.fromBufferAttribute( normalAttribute, vA );
  6639. nB.fromBufferAttribute( normalAttribute, vB );
  6640. nC.fromBufferAttribute( normalAttribute, vC );
  6641. nA.add( cb );
  6642. nB.add( cb );
  6643. nC.add( cb );
  6644. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6645. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6646. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6647. }
  6648. } else {
  6649. // non-indexed elements (unconnected triangle soup)
  6650. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6651. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6652. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6653. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6654. cb.subVectors( pC, pB );
  6655. ab.subVectors( pA, pB );
  6656. cb.cross( ab );
  6657. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6658. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6659. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6660. }
  6661. }
  6662. this.normalizeNormals();
  6663. normalAttribute.needsUpdate = true;
  6664. }
  6665. }
  6666. normalizeNormals() {
  6667. const normals = this.attributes.normal;
  6668. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6669. _vector$8.fromBufferAttribute( normals, i );
  6670. _vector$8.normalize();
  6671. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6672. }
  6673. }
  6674. toNonIndexed() {
  6675. function convertBufferAttribute( attribute, indices ) {
  6676. const array = attribute.array;
  6677. const itemSize = attribute.itemSize;
  6678. const normalized = attribute.normalized;
  6679. const array2 = new array.constructor( indices.length * itemSize );
  6680. let index = 0, index2 = 0;
  6681. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6682. if ( attribute.isInterleavedBufferAttribute ) {
  6683. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6684. } else {
  6685. index = indices[ i ] * itemSize;
  6686. }
  6687. for ( let j = 0; j < itemSize; j ++ ) {
  6688. array2[ index2 ++ ] = array[ index ++ ];
  6689. }
  6690. }
  6691. return new BufferAttribute( array2, itemSize, normalized );
  6692. }
  6693. //
  6694. if ( this.index === null ) {
  6695. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6696. return this;
  6697. }
  6698. const geometry2 = new BufferGeometry();
  6699. const indices = this.index.array;
  6700. const attributes = this.attributes;
  6701. // attributes
  6702. for ( const name in attributes ) {
  6703. const attribute = attributes[ name ];
  6704. const newAttribute = convertBufferAttribute( attribute, indices );
  6705. geometry2.setAttribute( name, newAttribute );
  6706. }
  6707. // morph attributes
  6708. const morphAttributes = this.morphAttributes;
  6709. for ( const name in morphAttributes ) {
  6710. const morphArray = [];
  6711. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6712. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6713. const attribute = morphAttribute[ i ];
  6714. const newAttribute = convertBufferAttribute( attribute, indices );
  6715. morphArray.push( newAttribute );
  6716. }
  6717. geometry2.morphAttributes[ name ] = morphArray;
  6718. }
  6719. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6720. // groups
  6721. const groups = this.groups;
  6722. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6723. const group = groups[ i ];
  6724. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6725. }
  6726. return geometry2;
  6727. }
  6728. toJSON() {
  6729. const data = {
  6730. metadata: {
  6731. version: 4.6,
  6732. type: 'BufferGeometry',
  6733. generator: 'BufferGeometry.toJSON'
  6734. }
  6735. };
  6736. // standard BufferGeometry serialization
  6737. data.uuid = this.uuid;
  6738. data.type = this.type;
  6739. if ( this.name !== '' ) data.name = this.name;
  6740. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6741. if ( this.parameters !== undefined ) {
  6742. const parameters = this.parameters;
  6743. for ( const key in parameters ) {
  6744. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6745. }
  6746. return data;
  6747. }
  6748. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6749. data.data = { attributes: {} };
  6750. const index = this.index;
  6751. if ( index !== null ) {
  6752. data.data.index = {
  6753. type: index.array.constructor.name,
  6754. array: Array.prototype.slice.call( index.array )
  6755. };
  6756. }
  6757. const attributes = this.attributes;
  6758. for ( const key in attributes ) {
  6759. const attribute = attributes[ key ];
  6760. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6761. }
  6762. const morphAttributes = {};
  6763. let hasMorphAttributes = false;
  6764. for ( const key in this.morphAttributes ) {
  6765. const attributeArray = this.morphAttributes[ key ];
  6766. const array = [];
  6767. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6768. const attribute = attributeArray[ i ];
  6769. array.push( attribute.toJSON( data.data ) );
  6770. }
  6771. if ( array.length > 0 ) {
  6772. morphAttributes[ key ] = array;
  6773. hasMorphAttributes = true;
  6774. }
  6775. }
  6776. if ( hasMorphAttributes ) {
  6777. data.data.morphAttributes = morphAttributes;
  6778. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6779. }
  6780. const groups = this.groups;
  6781. if ( groups.length > 0 ) {
  6782. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6783. }
  6784. const boundingSphere = this.boundingSphere;
  6785. if ( boundingSphere !== null ) {
  6786. data.data.boundingSphere = {
  6787. center: boundingSphere.center.toArray(),
  6788. radius: boundingSphere.radius
  6789. };
  6790. }
  6791. return data;
  6792. }
  6793. clone() {
  6794. return new this.constructor().copy( this );
  6795. }
  6796. copy( source ) {
  6797. // reset
  6798. this.index = null;
  6799. this.attributes = {};
  6800. this.morphAttributes = {};
  6801. this.groups = [];
  6802. this.boundingBox = null;
  6803. this.boundingSphere = null;
  6804. // used for storing cloned, shared data
  6805. const data = {};
  6806. // name
  6807. this.name = source.name;
  6808. // index
  6809. const index = source.index;
  6810. if ( index !== null ) {
  6811. this.setIndex( index.clone( data ) );
  6812. }
  6813. // attributes
  6814. const attributes = source.attributes;
  6815. for ( const name in attributes ) {
  6816. const attribute = attributes[ name ];
  6817. this.setAttribute( name, attribute.clone( data ) );
  6818. }
  6819. // morph attributes
  6820. const morphAttributes = source.morphAttributes;
  6821. for ( const name in morphAttributes ) {
  6822. const array = [];
  6823. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6824. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6825. array.push( morphAttribute[ i ].clone( data ) );
  6826. }
  6827. this.morphAttributes[ name ] = array;
  6828. }
  6829. this.morphTargetsRelative = source.morphTargetsRelative;
  6830. // groups
  6831. const groups = source.groups;
  6832. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6833. const group = groups[ i ];
  6834. this.addGroup( group.start, group.count, group.materialIndex );
  6835. }
  6836. // bounding box
  6837. const boundingBox = source.boundingBox;
  6838. if ( boundingBox !== null ) {
  6839. this.boundingBox = boundingBox.clone();
  6840. }
  6841. // bounding sphere
  6842. const boundingSphere = source.boundingSphere;
  6843. if ( boundingSphere !== null ) {
  6844. this.boundingSphere = boundingSphere.clone();
  6845. }
  6846. // draw range
  6847. this.drawRange.start = source.drawRange.start;
  6848. this.drawRange.count = source.drawRange.count;
  6849. // user data
  6850. this.userData = source.userData;
  6851. return this;
  6852. }
  6853. dispose() {
  6854. this.dispatchEvent( { type: 'dispose' } );
  6855. }
  6856. }
  6857. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6858. const _ray$3 = /*@__PURE__*/ new Ray();
  6859. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6860. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6861. const _vA$1 = /*@__PURE__*/ new Vector3();
  6862. const _vB$1 = /*@__PURE__*/ new Vector3();
  6863. const _vC$1 = /*@__PURE__*/ new Vector3();
  6864. const _tempA = /*@__PURE__*/ new Vector3();
  6865. const _morphA = /*@__PURE__*/ new Vector3();
  6866. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6867. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6868. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6869. const _normalA = /*@__PURE__*/ new Vector3();
  6870. const _normalB = /*@__PURE__*/ new Vector3();
  6871. const _normalC = /*@__PURE__*/ new Vector3();
  6872. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6873. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6874. class Mesh extends Object3D {
  6875. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6876. super();
  6877. this.isMesh = true;
  6878. this.type = 'Mesh';
  6879. this.geometry = geometry;
  6880. this.material = material;
  6881. this.updateMorphTargets();
  6882. }
  6883. copy( source, recursive ) {
  6884. super.copy( source, recursive );
  6885. if ( source.morphTargetInfluences !== undefined ) {
  6886. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6887. }
  6888. if ( source.morphTargetDictionary !== undefined ) {
  6889. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6890. }
  6891. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6892. this.geometry = source.geometry;
  6893. return this;
  6894. }
  6895. updateMorphTargets() {
  6896. const geometry = this.geometry;
  6897. const morphAttributes = geometry.morphAttributes;
  6898. const keys = Object.keys( morphAttributes );
  6899. if ( keys.length > 0 ) {
  6900. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6901. if ( morphAttribute !== undefined ) {
  6902. this.morphTargetInfluences = [];
  6903. this.morphTargetDictionary = {};
  6904. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6905. const name = morphAttribute[ m ].name || String( m );
  6906. this.morphTargetInfluences.push( 0 );
  6907. this.morphTargetDictionary[ name ] = m;
  6908. }
  6909. }
  6910. }
  6911. }
  6912. getVertexPosition( index, target ) {
  6913. const geometry = this.geometry;
  6914. const position = geometry.attributes.position;
  6915. const morphPosition = geometry.morphAttributes.position;
  6916. const morphTargetsRelative = geometry.morphTargetsRelative;
  6917. target.fromBufferAttribute( position, index );
  6918. const morphInfluences = this.morphTargetInfluences;
  6919. if ( morphPosition && morphInfluences ) {
  6920. _morphA.set( 0, 0, 0 );
  6921. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6922. const influence = morphInfluences[ i ];
  6923. const morphAttribute = morphPosition[ i ];
  6924. if ( influence === 0 ) continue;
  6925. _tempA.fromBufferAttribute( morphAttribute, index );
  6926. if ( morphTargetsRelative ) {
  6927. _morphA.addScaledVector( _tempA, influence );
  6928. } else {
  6929. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6930. }
  6931. }
  6932. target.add( _morphA );
  6933. }
  6934. return target;
  6935. }
  6936. raycast( raycaster, intersects ) {
  6937. const geometry = this.geometry;
  6938. const material = this.material;
  6939. const matrixWorld = this.matrixWorld;
  6940. if ( material === undefined ) return;
  6941. // test with bounding sphere in world space
  6942. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6943. _sphere$6.copy( geometry.boundingSphere );
  6944. _sphere$6.applyMatrix4( matrixWorld );
  6945. // check distance from ray origin to bounding sphere
  6946. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6947. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6948. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6949. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6950. }
  6951. // convert ray to local space of mesh
  6952. _inverseMatrix$3.copy( matrixWorld ).invert();
  6953. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6954. // test with bounding box in local space
  6955. if ( geometry.boundingBox !== null ) {
  6956. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6957. }
  6958. // test for intersections with geometry
  6959. this._computeIntersections( raycaster, intersects, _ray$3 );
  6960. }
  6961. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6962. let intersection;
  6963. const geometry = this.geometry;
  6964. const material = this.material;
  6965. const index = geometry.index;
  6966. const position = geometry.attributes.position;
  6967. const uv = geometry.attributes.uv;
  6968. const uv1 = geometry.attributes.uv1;
  6969. const normal = geometry.attributes.normal;
  6970. const groups = geometry.groups;
  6971. const drawRange = geometry.drawRange;
  6972. if ( index !== null ) {
  6973. // indexed buffer geometry
  6974. if ( Array.isArray( material ) ) {
  6975. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6976. const group = groups[ i ];
  6977. const groupMaterial = material[ group.materialIndex ];
  6978. const start = Math.max( group.start, drawRange.start );
  6979. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6980. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6981. const a = index.getX( j );
  6982. const b = index.getX( j + 1 );
  6983. const c = index.getX( j + 2 );
  6984. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6985. if ( intersection ) {
  6986. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6987. intersection.face.materialIndex = group.materialIndex;
  6988. intersects.push( intersection );
  6989. }
  6990. }
  6991. }
  6992. } else {
  6993. const start = Math.max( 0, drawRange.start );
  6994. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6995. for ( let i = start, il = end; i < il; i += 3 ) {
  6996. const a = index.getX( i );
  6997. const b = index.getX( i + 1 );
  6998. const c = index.getX( i + 2 );
  6999. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7000. if ( intersection ) {
  7001. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7002. intersects.push( intersection );
  7003. }
  7004. }
  7005. }
  7006. } else if ( position !== undefined ) {
  7007. // non-indexed buffer geometry
  7008. if ( Array.isArray( material ) ) {
  7009. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7010. const group = groups[ i ];
  7011. const groupMaterial = material[ group.materialIndex ];
  7012. const start = Math.max( group.start, drawRange.start );
  7013. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7014. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7015. const a = j;
  7016. const b = j + 1;
  7017. const c = j + 2;
  7018. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7019. if ( intersection ) {
  7020. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7021. intersection.face.materialIndex = group.materialIndex;
  7022. intersects.push( intersection );
  7023. }
  7024. }
  7025. }
  7026. } else {
  7027. const start = Math.max( 0, drawRange.start );
  7028. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7029. for ( let i = start, il = end; i < il; i += 3 ) {
  7030. const a = i;
  7031. const b = i + 1;
  7032. const c = i + 2;
  7033. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7034. if ( intersection ) {
  7035. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7036. intersects.push( intersection );
  7037. }
  7038. }
  7039. }
  7040. }
  7041. }
  7042. }
  7043. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7044. let intersect;
  7045. if ( material.side === BackSide ) {
  7046. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7047. } else {
  7048. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7049. }
  7050. if ( intersect === null ) return null;
  7051. _intersectionPointWorld.copy( point );
  7052. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7053. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7054. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7055. return {
  7056. distance: distance,
  7057. point: _intersectionPointWorld.clone(),
  7058. object: object
  7059. };
  7060. }
  7061. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7062. object.getVertexPosition( a, _vA$1 );
  7063. object.getVertexPosition( b, _vB$1 );
  7064. object.getVertexPosition( c, _vC$1 );
  7065. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7066. if ( intersection ) {
  7067. if ( uv ) {
  7068. _uvA$1.fromBufferAttribute( uv, a );
  7069. _uvB$1.fromBufferAttribute( uv, b );
  7070. _uvC$1.fromBufferAttribute( uv, c );
  7071. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7072. }
  7073. if ( uv1 ) {
  7074. _uvA$1.fromBufferAttribute( uv1, a );
  7075. _uvB$1.fromBufferAttribute( uv1, b );
  7076. _uvC$1.fromBufferAttribute( uv1, c );
  7077. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7078. }
  7079. if ( normal ) {
  7080. _normalA.fromBufferAttribute( normal, a );
  7081. _normalB.fromBufferAttribute( normal, b );
  7082. _normalC.fromBufferAttribute( normal, c );
  7083. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7084. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7085. intersection.normal.multiplyScalar( - 1 );
  7086. }
  7087. }
  7088. const face = {
  7089. a: a,
  7090. b: b,
  7091. c: c,
  7092. normal: new Vector3(),
  7093. materialIndex: 0
  7094. };
  7095. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7096. intersection.face = face;
  7097. }
  7098. return intersection;
  7099. }
  7100. class BoxGeometry extends BufferGeometry {
  7101. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7102. super();
  7103. this.type = 'BoxGeometry';
  7104. this.parameters = {
  7105. width: width,
  7106. height: height,
  7107. depth: depth,
  7108. widthSegments: widthSegments,
  7109. heightSegments: heightSegments,
  7110. depthSegments: depthSegments
  7111. };
  7112. const scope = this;
  7113. // segments
  7114. widthSegments = Math.floor( widthSegments );
  7115. heightSegments = Math.floor( heightSegments );
  7116. depthSegments = Math.floor( depthSegments );
  7117. // buffers
  7118. const indices = [];
  7119. const vertices = [];
  7120. const normals = [];
  7121. const uvs = [];
  7122. // helper variables
  7123. let numberOfVertices = 0;
  7124. let groupStart = 0;
  7125. // build each side of the box geometry
  7126. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7127. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7128. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7129. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7130. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7131. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7132. // build geometry
  7133. this.setIndex( indices );
  7134. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7135. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7136. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7137. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7138. const segmentWidth = width / gridX;
  7139. const segmentHeight = height / gridY;
  7140. const widthHalf = width / 2;
  7141. const heightHalf = height / 2;
  7142. const depthHalf = depth / 2;
  7143. const gridX1 = gridX + 1;
  7144. const gridY1 = gridY + 1;
  7145. let vertexCounter = 0;
  7146. let groupCount = 0;
  7147. const vector = new Vector3();
  7148. // generate vertices, normals and uvs
  7149. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7150. const y = iy * segmentHeight - heightHalf;
  7151. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7152. const x = ix * segmentWidth - widthHalf;
  7153. // set values to correct vector component
  7154. vector[ u ] = x * udir;
  7155. vector[ v ] = y * vdir;
  7156. vector[ w ] = depthHalf;
  7157. // now apply vector to vertex buffer
  7158. vertices.push( vector.x, vector.y, vector.z );
  7159. // set values to correct vector component
  7160. vector[ u ] = 0;
  7161. vector[ v ] = 0;
  7162. vector[ w ] = depth > 0 ? 1 : - 1;
  7163. // now apply vector to normal buffer
  7164. normals.push( vector.x, vector.y, vector.z );
  7165. // uvs
  7166. uvs.push( ix / gridX );
  7167. uvs.push( 1 - ( iy / gridY ) );
  7168. // counters
  7169. vertexCounter += 1;
  7170. }
  7171. }
  7172. // indices
  7173. // 1. you need three indices to draw a single face
  7174. // 2. a single segment consists of two faces
  7175. // 3. so we need to generate six (2*3) indices per segment
  7176. for ( let iy = 0; iy < gridY; iy ++ ) {
  7177. for ( let ix = 0; ix < gridX; ix ++ ) {
  7178. const a = numberOfVertices + ix + gridX1 * iy;
  7179. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7180. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7181. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7182. // faces
  7183. indices.push( a, b, d );
  7184. indices.push( b, c, d );
  7185. // increase counter
  7186. groupCount += 6;
  7187. }
  7188. }
  7189. // add a group to the geometry. this will ensure multi material support
  7190. scope.addGroup( groupStart, groupCount, materialIndex );
  7191. // calculate new start value for groups
  7192. groupStart += groupCount;
  7193. // update total number of vertices
  7194. numberOfVertices += vertexCounter;
  7195. }
  7196. }
  7197. copy( source ) {
  7198. super.copy( source );
  7199. this.parameters = Object.assign( {}, source.parameters );
  7200. return this;
  7201. }
  7202. static fromJSON( data ) {
  7203. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7204. }
  7205. }
  7206. /**
  7207. * Uniform Utilities
  7208. */
  7209. function cloneUniforms( src ) {
  7210. const dst = {};
  7211. for ( const u in src ) {
  7212. dst[ u ] = {};
  7213. for ( const p in src[ u ] ) {
  7214. const property = src[ u ][ p ];
  7215. if ( property && ( property.isColor ||
  7216. property.isMatrix3 || property.isMatrix4 ||
  7217. property.isVector2 || property.isVector3 || property.isVector4 ||
  7218. property.isTexture || property.isQuaternion ) ) {
  7219. if ( property.isRenderTargetTexture ) {
  7220. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7221. dst[ u ][ p ] = null;
  7222. } else {
  7223. dst[ u ][ p ] = property.clone();
  7224. }
  7225. } else if ( Array.isArray( property ) ) {
  7226. dst[ u ][ p ] = property.slice();
  7227. } else {
  7228. dst[ u ][ p ] = property;
  7229. }
  7230. }
  7231. }
  7232. return dst;
  7233. }
  7234. function mergeUniforms( uniforms ) {
  7235. const merged = {};
  7236. for ( let u = 0; u < uniforms.length; u ++ ) {
  7237. const tmp = cloneUniforms( uniforms[ u ] );
  7238. for ( const p in tmp ) {
  7239. merged[ p ] = tmp[ p ];
  7240. }
  7241. }
  7242. return merged;
  7243. }
  7244. function cloneUniformsGroups( src ) {
  7245. const dst = [];
  7246. for ( let u = 0; u < src.length; u ++ ) {
  7247. dst.push( src[ u ].clone() );
  7248. }
  7249. return dst;
  7250. }
  7251. function getUnlitUniformColorSpace( renderer ) {
  7252. const currentRenderTarget = renderer.getRenderTarget();
  7253. if ( currentRenderTarget === null ) {
  7254. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7255. return renderer.outputColorSpace;
  7256. }
  7257. // https://github.com/mrdoob/three.js/issues/27868
  7258. if ( currentRenderTarget.isXRRenderTarget === true ) {
  7259. return currentRenderTarget.texture.colorSpace;
  7260. }
  7261. return ColorManagement.workingColorSpace;
  7262. }
  7263. // Legacy
  7264. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7265. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7266. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7267. class ShaderMaterial extends Material {
  7268. constructor( parameters ) {
  7269. super();
  7270. this.isShaderMaterial = true;
  7271. this.type = 'ShaderMaterial';
  7272. this.defines = {};
  7273. this.uniforms = {};
  7274. this.uniformsGroups = [];
  7275. this.vertexShader = default_vertex;
  7276. this.fragmentShader = default_fragment;
  7277. this.linewidth = 1;
  7278. this.wireframe = false;
  7279. this.wireframeLinewidth = 1;
  7280. this.fog = false; // set to use scene fog
  7281. this.lights = false; // set to use scene lights
  7282. this.clipping = false; // set to use user-defined clipping planes
  7283. this.forceSinglePass = true;
  7284. this.extensions = {
  7285. clipCullDistance: false, // set to use vertex shader clipping
  7286. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7287. };
  7288. // When rendered geometry doesn't include these attributes but the material does,
  7289. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7290. this.defaultAttributeValues = {
  7291. 'color': [ 1, 1, 1 ],
  7292. 'uv': [ 0, 0 ],
  7293. 'uv1': [ 0, 0 ]
  7294. };
  7295. this.index0AttributeName = undefined;
  7296. this.uniformsNeedUpdate = false;
  7297. this.glslVersion = null;
  7298. if ( parameters !== undefined ) {
  7299. this.setValues( parameters );
  7300. }
  7301. }
  7302. copy( source ) {
  7303. super.copy( source );
  7304. this.fragmentShader = source.fragmentShader;
  7305. this.vertexShader = source.vertexShader;
  7306. this.uniforms = cloneUniforms( source.uniforms );
  7307. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7308. this.defines = Object.assign( {}, source.defines );
  7309. this.wireframe = source.wireframe;
  7310. this.wireframeLinewidth = source.wireframeLinewidth;
  7311. this.fog = source.fog;
  7312. this.lights = source.lights;
  7313. this.clipping = source.clipping;
  7314. this.extensions = Object.assign( {}, source.extensions );
  7315. this.glslVersion = source.glslVersion;
  7316. return this;
  7317. }
  7318. toJSON( meta ) {
  7319. const data = super.toJSON( meta );
  7320. data.glslVersion = this.glslVersion;
  7321. data.uniforms = {};
  7322. for ( const name in this.uniforms ) {
  7323. const uniform = this.uniforms[ name ];
  7324. const value = uniform.value;
  7325. if ( value && value.isTexture ) {
  7326. data.uniforms[ name ] = {
  7327. type: 't',
  7328. value: value.toJSON( meta ).uuid
  7329. };
  7330. } else if ( value && value.isColor ) {
  7331. data.uniforms[ name ] = {
  7332. type: 'c',
  7333. value: value.getHex()
  7334. };
  7335. } else if ( value && value.isVector2 ) {
  7336. data.uniforms[ name ] = {
  7337. type: 'v2',
  7338. value: value.toArray()
  7339. };
  7340. } else if ( value && value.isVector3 ) {
  7341. data.uniforms[ name ] = {
  7342. type: 'v3',
  7343. value: value.toArray()
  7344. };
  7345. } else if ( value && value.isVector4 ) {
  7346. data.uniforms[ name ] = {
  7347. type: 'v4',
  7348. value: value.toArray()
  7349. };
  7350. } else if ( value && value.isMatrix3 ) {
  7351. data.uniforms[ name ] = {
  7352. type: 'm3',
  7353. value: value.toArray()
  7354. };
  7355. } else if ( value && value.isMatrix4 ) {
  7356. data.uniforms[ name ] = {
  7357. type: 'm4',
  7358. value: value.toArray()
  7359. };
  7360. } else {
  7361. data.uniforms[ name ] = {
  7362. value: value
  7363. };
  7364. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7365. }
  7366. }
  7367. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7368. data.vertexShader = this.vertexShader;
  7369. data.fragmentShader = this.fragmentShader;
  7370. data.lights = this.lights;
  7371. data.clipping = this.clipping;
  7372. const extensions = {};
  7373. for ( const key in this.extensions ) {
  7374. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7375. }
  7376. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7377. return data;
  7378. }
  7379. }
  7380. class Camera extends Object3D {
  7381. constructor() {
  7382. super();
  7383. this.isCamera = true;
  7384. this.type = 'Camera';
  7385. this.matrixWorldInverse = new Matrix4();
  7386. this.projectionMatrix = new Matrix4();
  7387. this.projectionMatrixInverse = new Matrix4();
  7388. this.coordinateSystem = WebGLCoordinateSystem;
  7389. }
  7390. copy( source, recursive ) {
  7391. super.copy( source, recursive );
  7392. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7393. this.projectionMatrix.copy( source.projectionMatrix );
  7394. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7395. this.coordinateSystem = source.coordinateSystem;
  7396. return this;
  7397. }
  7398. getWorldDirection( target ) {
  7399. return super.getWorldDirection( target ).negate();
  7400. }
  7401. updateMatrixWorld( force ) {
  7402. super.updateMatrixWorld( force );
  7403. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7404. }
  7405. updateWorldMatrix( updateParents, updateChildren ) {
  7406. super.updateWorldMatrix( updateParents, updateChildren );
  7407. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7408. }
  7409. clone() {
  7410. return new this.constructor().copy( this );
  7411. }
  7412. }
  7413. const _v3$1 = /*@__PURE__*/ new Vector3();
  7414. const _minTarget = /*@__PURE__*/ new Vector2();
  7415. const _maxTarget = /*@__PURE__*/ new Vector2();
  7416. class PerspectiveCamera extends Camera {
  7417. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7418. super();
  7419. this.isPerspectiveCamera = true;
  7420. this.type = 'PerspectiveCamera';
  7421. this.fov = fov;
  7422. this.zoom = 1;
  7423. this.near = near;
  7424. this.far = far;
  7425. this.focus = 10;
  7426. this.aspect = aspect;
  7427. this.view = null;
  7428. this.filmGauge = 35; // width of the film (default in millimeters)
  7429. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7430. this.updateProjectionMatrix();
  7431. }
  7432. copy( source, recursive ) {
  7433. super.copy( source, recursive );
  7434. this.fov = source.fov;
  7435. this.zoom = source.zoom;
  7436. this.near = source.near;
  7437. this.far = source.far;
  7438. this.focus = source.focus;
  7439. this.aspect = source.aspect;
  7440. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7441. this.filmGauge = source.filmGauge;
  7442. this.filmOffset = source.filmOffset;
  7443. return this;
  7444. }
  7445. /**
  7446. * Sets the FOV by focal length in respect to the current .filmGauge.
  7447. *
  7448. * The default film gauge is 35, so that the focal length can be specified for
  7449. * a 35mm (full frame) camera.
  7450. *
  7451. * Values for focal length and film gauge must have the same unit.
  7452. */
  7453. setFocalLength( focalLength ) {
  7454. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7455. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7456. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7457. this.updateProjectionMatrix();
  7458. }
  7459. /**
  7460. * Calculates the focal length from the current .fov and .filmGauge.
  7461. */
  7462. getFocalLength() {
  7463. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7464. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7465. }
  7466. getEffectiveFOV() {
  7467. return RAD2DEG * 2 * Math.atan(
  7468. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7469. }
  7470. getFilmWidth() {
  7471. // film not completely covered in portrait format (aspect < 1)
  7472. return this.filmGauge * Math.min( this.aspect, 1 );
  7473. }
  7474. getFilmHeight() {
  7475. // film not completely covered in landscape format (aspect > 1)
  7476. return this.filmGauge / Math.max( this.aspect, 1 );
  7477. }
  7478. /**
  7479. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7480. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7481. */
  7482. getViewBounds( distance, minTarget, maxTarget ) {
  7483. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7484. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7485. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7486. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7487. }
  7488. /**
  7489. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7490. * Copies the result into the target Vector2, where x is width and y is height.
  7491. */
  7492. getViewSize( distance, target ) {
  7493. this.getViewBounds( distance, _minTarget, _maxTarget );
  7494. return target.subVectors( _maxTarget, _minTarget );
  7495. }
  7496. /**
  7497. * Sets an offset in a larger frustum. This is useful for multi-window or
  7498. * multi-monitor/multi-machine setups.
  7499. *
  7500. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7501. * the monitors are in grid like this
  7502. *
  7503. * +---+---+---+
  7504. * | A | B | C |
  7505. * +---+---+---+
  7506. * | D | E | F |
  7507. * +---+---+---+
  7508. *
  7509. * then for each monitor you would call it like this
  7510. *
  7511. * const w = 1920;
  7512. * const h = 1080;
  7513. * const fullWidth = w * 3;
  7514. * const fullHeight = h * 2;
  7515. *
  7516. * --A--
  7517. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7518. * --B--
  7519. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7520. * --C--
  7521. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7522. * --D--
  7523. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7524. * --E--
  7525. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7526. * --F--
  7527. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7528. *
  7529. * Note there is no reason monitors have to be the same size or in a grid.
  7530. */
  7531. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7532. this.aspect = fullWidth / fullHeight;
  7533. if ( this.view === null ) {
  7534. this.view = {
  7535. enabled: true,
  7536. fullWidth: 1,
  7537. fullHeight: 1,
  7538. offsetX: 0,
  7539. offsetY: 0,
  7540. width: 1,
  7541. height: 1
  7542. };
  7543. }
  7544. this.view.enabled = true;
  7545. this.view.fullWidth = fullWidth;
  7546. this.view.fullHeight = fullHeight;
  7547. this.view.offsetX = x;
  7548. this.view.offsetY = y;
  7549. this.view.width = width;
  7550. this.view.height = height;
  7551. this.updateProjectionMatrix();
  7552. }
  7553. clearViewOffset() {
  7554. if ( this.view !== null ) {
  7555. this.view.enabled = false;
  7556. }
  7557. this.updateProjectionMatrix();
  7558. }
  7559. updateProjectionMatrix() {
  7560. const near = this.near;
  7561. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7562. let height = 2 * top;
  7563. let width = this.aspect * height;
  7564. let left = - 0.5 * width;
  7565. const view = this.view;
  7566. if ( this.view !== null && this.view.enabled ) {
  7567. const fullWidth = view.fullWidth,
  7568. fullHeight = view.fullHeight;
  7569. left += view.offsetX * width / fullWidth;
  7570. top -= view.offsetY * height / fullHeight;
  7571. width *= view.width / fullWidth;
  7572. height *= view.height / fullHeight;
  7573. }
  7574. const skew = this.filmOffset;
  7575. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7576. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7577. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7578. }
  7579. toJSON( meta ) {
  7580. const data = super.toJSON( meta );
  7581. data.object.fov = this.fov;
  7582. data.object.zoom = this.zoom;
  7583. data.object.near = this.near;
  7584. data.object.far = this.far;
  7585. data.object.focus = this.focus;
  7586. data.object.aspect = this.aspect;
  7587. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7588. data.object.filmGauge = this.filmGauge;
  7589. data.object.filmOffset = this.filmOffset;
  7590. return data;
  7591. }
  7592. }
  7593. const fov = - 90; // negative fov is not an error
  7594. const aspect = 1;
  7595. class CubeCamera extends Object3D {
  7596. constructor( near, far, renderTarget ) {
  7597. super();
  7598. this.type = 'CubeCamera';
  7599. this.renderTarget = renderTarget;
  7600. this.coordinateSystem = null;
  7601. this.activeMipmapLevel = 0;
  7602. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7603. cameraPX.layers = this.layers;
  7604. this.add( cameraPX );
  7605. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7606. cameraNX.layers = this.layers;
  7607. this.add( cameraNX );
  7608. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7609. cameraPY.layers = this.layers;
  7610. this.add( cameraPY );
  7611. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7612. cameraNY.layers = this.layers;
  7613. this.add( cameraNY );
  7614. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7615. cameraPZ.layers = this.layers;
  7616. this.add( cameraPZ );
  7617. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7618. cameraNZ.layers = this.layers;
  7619. this.add( cameraNZ );
  7620. }
  7621. updateCoordinateSystem() {
  7622. const coordinateSystem = this.coordinateSystem;
  7623. const cameras = this.children.concat();
  7624. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7625. for ( const camera of cameras ) this.remove( camera );
  7626. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7627. cameraPX.up.set( 0, 1, 0 );
  7628. cameraPX.lookAt( 1, 0, 0 );
  7629. cameraNX.up.set( 0, 1, 0 );
  7630. cameraNX.lookAt( - 1, 0, 0 );
  7631. cameraPY.up.set( 0, 0, - 1 );
  7632. cameraPY.lookAt( 0, 1, 0 );
  7633. cameraNY.up.set( 0, 0, 1 );
  7634. cameraNY.lookAt( 0, - 1, 0 );
  7635. cameraPZ.up.set( 0, 1, 0 );
  7636. cameraPZ.lookAt( 0, 0, 1 );
  7637. cameraNZ.up.set( 0, 1, 0 );
  7638. cameraNZ.lookAt( 0, 0, - 1 );
  7639. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7640. cameraPX.up.set( 0, - 1, 0 );
  7641. cameraPX.lookAt( - 1, 0, 0 );
  7642. cameraNX.up.set( 0, - 1, 0 );
  7643. cameraNX.lookAt( 1, 0, 0 );
  7644. cameraPY.up.set( 0, 0, 1 );
  7645. cameraPY.lookAt( 0, 1, 0 );
  7646. cameraNY.up.set( 0, 0, - 1 );
  7647. cameraNY.lookAt( 0, - 1, 0 );
  7648. cameraPZ.up.set( 0, - 1, 0 );
  7649. cameraPZ.lookAt( 0, 0, 1 );
  7650. cameraNZ.up.set( 0, - 1, 0 );
  7651. cameraNZ.lookAt( 0, 0, - 1 );
  7652. } else {
  7653. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7654. }
  7655. for ( const camera of cameras ) {
  7656. this.add( camera );
  7657. camera.updateMatrixWorld();
  7658. }
  7659. }
  7660. update( renderer, scene ) {
  7661. if ( this.parent === null ) this.updateMatrixWorld();
  7662. const { renderTarget, activeMipmapLevel } = this;
  7663. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7664. this.coordinateSystem = renderer.coordinateSystem;
  7665. this.updateCoordinateSystem();
  7666. }
  7667. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7668. const currentRenderTarget = renderer.getRenderTarget();
  7669. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7670. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7671. const currentXrEnabled = renderer.xr.enabled;
  7672. renderer.xr.enabled = false;
  7673. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7674. renderTarget.texture.generateMipmaps = false;
  7675. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7676. renderer.render( scene, cameraPX );
  7677. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7678. renderer.render( scene, cameraNX );
  7679. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7680. renderer.render( scene, cameraPY );
  7681. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7682. renderer.render( scene, cameraNY );
  7683. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7684. renderer.render( scene, cameraPZ );
  7685. // mipmaps are generated during the last call of render()
  7686. // at this point, all sides of the cube render target are defined
  7687. renderTarget.texture.generateMipmaps = generateMipmaps;
  7688. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7689. renderer.render( scene, cameraNZ );
  7690. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7691. renderer.xr.enabled = currentXrEnabled;
  7692. renderTarget.texture.needsPMREMUpdate = true;
  7693. }
  7694. }
  7695. class CubeTexture extends Texture {
  7696. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7697. images = images !== undefined ? images : [];
  7698. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7699. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7700. this.isCubeTexture = true;
  7701. this.flipY = false;
  7702. }
  7703. get images() {
  7704. return this.image;
  7705. }
  7706. set images( value ) {
  7707. this.image = value;
  7708. }
  7709. }
  7710. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7711. constructor( size = 1, options = {} ) {
  7712. super( size, size, options );
  7713. this.isWebGLCubeRenderTarget = true;
  7714. const image = { width: size, height: size, depth: 1 };
  7715. const images = [ image, image, image, image, image, image ];
  7716. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7717. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7718. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7719. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7720. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7721. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7722. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7723. this.texture.isRenderTargetTexture = true;
  7724. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7725. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7726. }
  7727. fromEquirectangularTexture( renderer, texture ) {
  7728. this.texture.type = texture.type;
  7729. this.texture.colorSpace = texture.colorSpace;
  7730. this.texture.generateMipmaps = texture.generateMipmaps;
  7731. this.texture.minFilter = texture.minFilter;
  7732. this.texture.magFilter = texture.magFilter;
  7733. const shader = {
  7734. uniforms: {
  7735. tEquirect: { value: null },
  7736. },
  7737. vertexShader: /* glsl */`
  7738. varying vec3 vWorldDirection;
  7739. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7740. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7741. }
  7742. void main() {
  7743. vWorldDirection = transformDirection( position, modelMatrix );
  7744. #include <begin_vertex>
  7745. #include <project_vertex>
  7746. }
  7747. `,
  7748. fragmentShader: /* glsl */`
  7749. uniform sampler2D tEquirect;
  7750. varying vec3 vWorldDirection;
  7751. #include <common>
  7752. void main() {
  7753. vec3 direction = normalize( vWorldDirection );
  7754. vec2 sampleUV = equirectUv( direction );
  7755. gl_FragColor = texture2D( tEquirect, sampleUV );
  7756. }
  7757. `
  7758. };
  7759. const geometry = new BoxGeometry( 5, 5, 5 );
  7760. const material = new ShaderMaterial( {
  7761. name: 'CubemapFromEquirect',
  7762. uniforms: cloneUniforms( shader.uniforms ),
  7763. vertexShader: shader.vertexShader,
  7764. fragmentShader: shader.fragmentShader,
  7765. side: BackSide,
  7766. blending: NoBlending
  7767. } );
  7768. material.uniforms.tEquirect.value = texture;
  7769. const mesh = new Mesh( geometry, material );
  7770. const currentMinFilter = texture.minFilter;
  7771. // Avoid blurred poles
  7772. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7773. const camera = new CubeCamera( 1, 10, this );
  7774. camera.update( renderer, mesh );
  7775. texture.minFilter = currentMinFilter;
  7776. mesh.geometry.dispose();
  7777. mesh.material.dispose();
  7778. return this;
  7779. }
  7780. clear( renderer, color, depth, stencil ) {
  7781. const currentRenderTarget = renderer.getRenderTarget();
  7782. for ( let i = 0; i < 6; i ++ ) {
  7783. renderer.setRenderTarget( this, i );
  7784. renderer.clear( color, depth, stencil );
  7785. }
  7786. renderer.setRenderTarget( currentRenderTarget );
  7787. }
  7788. }
  7789. const _vector1 = /*@__PURE__*/ new Vector3();
  7790. const _vector2 = /*@__PURE__*/ new Vector3();
  7791. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7792. class Plane {
  7793. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7794. this.isPlane = true;
  7795. // normal is assumed to be normalized
  7796. this.normal = normal;
  7797. this.constant = constant;
  7798. }
  7799. set( normal, constant ) {
  7800. this.normal.copy( normal );
  7801. this.constant = constant;
  7802. return this;
  7803. }
  7804. setComponents( x, y, z, w ) {
  7805. this.normal.set( x, y, z );
  7806. this.constant = w;
  7807. return this;
  7808. }
  7809. setFromNormalAndCoplanarPoint( normal, point ) {
  7810. this.normal.copy( normal );
  7811. this.constant = - point.dot( this.normal );
  7812. return this;
  7813. }
  7814. setFromCoplanarPoints( a, b, c ) {
  7815. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7816. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7817. this.setFromNormalAndCoplanarPoint( normal, a );
  7818. return this;
  7819. }
  7820. copy( plane ) {
  7821. this.normal.copy( plane.normal );
  7822. this.constant = plane.constant;
  7823. return this;
  7824. }
  7825. normalize() {
  7826. // Note: will lead to a divide by zero if the plane is invalid.
  7827. const inverseNormalLength = 1.0 / this.normal.length();
  7828. this.normal.multiplyScalar( inverseNormalLength );
  7829. this.constant *= inverseNormalLength;
  7830. return this;
  7831. }
  7832. negate() {
  7833. this.constant *= - 1;
  7834. this.normal.negate();
  7835. return this;
  7836. }
  7837. distanceToPoint( point ) {
  7838. return this.normal.dot( point ) + this.constant;
  7839. }
  7840. distanceToSphere( sphere ) {
  7841. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7842. }
  7843. projectPoint( point, target ) {
  7844. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7845. }
  7846. intersectLine( line, target ) {
  7847. const direction = line.delta( _vector1 );
  7848. const denominator = this.normal.dot( direction );
  7849. if ( denominator === 0 ) {
  7850. // line is coplanar, return origin
  7851. if ( this.distanceToPoint( line.start ) === 0 ) {
  7852. return target.copy( line.start );
  7853. }
  7854. // Unsure if this is the correct method to handle this case.
  7855. return null;
  7856. }
  7857. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7858. if ( t < 0 || t > 1 ) {
  7859. return null;
  7860. }
  7861. return target.copy( line.start ).addScaledVector( direction, t );
  7862. }
  7863. intersectsLine( line ) {
  7864. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7865. const startSign = this.distanceToPoint( line.start );
  7866. const endSign = this.distanceToPoint( line.end );
  7867. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7868. }
  7869. intersectsBox( box ) {
  7870. return box.intersectsPlane( this );
  7871. }
  7872. intersectsSphere( sphere ) {
  7873. return sphere.intersectsPlane( this );
  7874. }
  7875. coplanarPoint( target ) {
  7876. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7877. }
  7878. applyMatrix4( matrix, optionalNormalMatrix ) {
  7879. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7880. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7881. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7882. this.constant = - referencePoint.dot( normal );
  7883. return this;
  7884. }
  7885. translate( offset ) {
  7886. this.constant -= offset.dot( this.normal );
  7887. return this;
  7888. }
  7889. equals( plane ) {
  7890. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7891. }
  7892. clone() {
  7893. return new this.constructor().copy( this );
  7894. }
  7895. }
  7896. const _sphere$5 = /*@__PURE__*/ new Sphere();
  7897. const _vector$7 = /*@__PURE__*/ new Vector3();
  7898. class Frustum {
  7899. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7900. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7901. }
  7902. set( p0, p1, p2, p3, p4, p5 ) {
  7903. const planes = this.planes;
  7904. planes[ 0 ].copy( p0 );
  7905. planes[ 1 ].copy( p1 );
  7906. planes[ 2 ].copy( p2 );
  7907. planes[ 3 ].copy( p3 );
  7908. planes[ 4 ].copy( p4 );
  7909. planes[ 5 ].copy( p5 );
  7910. return this;
  7911. }
  7912. copy( frustum ) {
  7913. const planes = this.planes;
  7914. for ( let i = 0; i < 6; i ++ ) {
  7915. planes[ i ].copy( frustum.planes[ i ] );
  7916. }
  7917. return this;
  7918. }
  7919. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7920. const planes = this.planes;
  7921. const me = m.elements;
  7922. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7923. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7924. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7925. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7926. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7927. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7928. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7929. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7930. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7931. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7932. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7933. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7934. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7935. } else {
  7936. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7937. }
  7938. return this;
  7939. }
  7940. intersectsObject( object ) {
  7941. if ( object.boundingSphere !== undefined ) {
  7942. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7943. _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7944. } else {
  7945. const geometry = object.geometry;
  7946. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7947. _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7948. }
  7949. return this.intersectsSphere( _sphere$5 );
  7950. }
  7951. intersectsSprite( sprite ) {
  7952. _sphere$5.center.set( 0, 0, 0 );
  7953. _sphere$5.radius = 0.7071067811865476;
  7954. _sphere$5.applyMatrix4( sprite.matrixWorld );
  7955. return this.intersectsSphere( _sphere$5 );
  7956. }
  7957. intersectsSphere( sphere ) {
  7958. const planes = this.planes;
  7959. const center = sphere.center;
  7960. const negRadius = - sphere.radius;
  7961. for ( let i = 0; i < 6; i ++ ) {
  7962. const distance = planes[ i ].distanceToPoint( center );
  7963. if ( distance < negRadius ) {
  7964. return false;
  7965. }
  7966. }
  7967. return true;
  7968. }
  7969. intersectsBox( box ) {
  7970. const planes = this.planes;
  7971. for ( let i = 0; i < 6; i ++ ) {
  7972. const plane = planes[ i ];
  7973. // corner at max distance
  7974. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7975. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7976. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7977. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7978. return false;
  7979. }
  7980. }
  7981. return true;
  7982. }
  7983. containsPoint( point ) {
  7984. const planes = this.planes;
  7985. for ( let i = 0; i < 6; i ++ ) {
  7986. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7987. return false;
  7988. }
  7989. }
  7990. return true;
  7991. }
  7992. clone() {
  7993. return new this.constructor().copy( this );
  7994. }
  7995. }
  7996. function WebGLAnimation() {
  7997. let context = null;
  7998. let isAnimating = false;
  7999. let animationLoop = null;
  8000. let requestId = null;
  8001. function onAnimationFrame( time, frame ) {
  8002. animationLoop( time, frame );
  8003. requestId = context.requestAnimationFrame( onAnimationFrame );
  8004. }
  8005. return {
  8006. start: function () {
  8007. if ( isAnimating === true ) return;
  8008. if ( animationLoop === null ) return;
  8009. requestId = context.requestAnimationFrame( onAnimationFrame );
  8010. isAnimating = true;
  8011. },
  8012. stop: function () {
  8013. context.cancelAnimationFrame( requestId );
  8014. isAnimating = false;
  8015. },
  8016. setAnimationLoop: function ( callback ) {
  8017. animationLoop = callback;
  8018. },
  8019. setContext: function ( value ) {
  8020. context = value;
  8021. }
  8022. };
  8023. }
  8024. function WebGLAttributes( gl ) {
  8025. const buffers = new WeakMap();
  8026. function createBuffer( attribute, bufferType ) {
  8027. const array = attribute.array;
  8028. const usage = attribute.usage;
  8029. const size = array.byteLength;
  8030. const buffer = gl.createBuffer();
  8031. gl.bindBuffer( bufferType, buffer );
  8032. gl.bufferData( bufferType, array, usage );
  8033. attribute.onUploadCallback();
  8034. let type;
  8035. if ( array instanceof Float32Array ) {
  8036. type = gl.FLOAT;
  8037. } else if ( array instanceof Uint16Array ) {
  8038. if ( attribute.isFloat16BufferAttribute ) {
  8039. type = gl.HALF_FLOAT;
  8040. } else {
  8041. type = gl.UNSIGNED_SHORT;
  8042. }
  8043. } else if ( array instanceof Int16Array ) {
  8044. type = gl.SHORT;
  8045. } else if ( array instanceof Uint32Array ) {
  8046. type = gl.UNSIGNED_INT;
  8047. } else if ( array instanceof Int32Array ) {
  8048. type = gl.INT;
  8049. } else if ( array instanceof Int8Array ) {
  8050. type = gl.BYTE;
  8051. } else if ( array instanceof Uint8Array ) {
  8052. type = gl.UNSIGNED_BYTE;
  8053. } else if ( array instanceof Uint8ClampedArray ) {
  8054. type = gl.UNSIGNED_BYTE;
  8055. } else {
  8056. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  8057. }
  8058. return {
  8059. buffer: buffer,
  8060. type: type,
  8061. bytesPerElement: array.BYTES_PER_ELEMENT,
  8062. version: attribute.version,
  8063. size: size
  8064. };
  8065. }
  8066. function updateBuffer( buffer, attribute, bufferType ) {
  8067. const array = attribute.array;
  8068. const updateRange = attribute._updateRange; // @deprecated, r159
  8069. const updateRanges = attribute.updateRanges;
  8070. gl.bindBuffer( bufferType, buffer );
  8071. if ( updateRange.count === - 1 && updateRanges.length === 0 ) {
  8072. // Not using update ranges
  8073. gl.bufferSubData( bufferType, 0, array );
  8074. }
  8075. if ( updateRanges.length !== 0 ) {
  8076. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  8077. const range = updateRanges[ i ];
  8078. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8079. array, range.start, range.count );
  8080. }
  8081. attribute.clearUpdateRanges();
  8082. }
  8083. // @deprecated, r159
  8084. if ( updateRange.count !== - 1 ) {
  8085. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8086. array, updateRange.offset, updateRange.count );
  8087. updateRange.count = - 1; // reset range
  8088. }
  8089. attribute.onUploadCallback();
  8090. }
  8091. //
  8092. function get( attribute ) {
  8093. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8094. return buffers.get( attribute );
  8095. }
  8096. function remove( attribute ) {
  8097. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8098. const data = buffers.get( attribute );
  8099. if ( data ) {
  8100. gl.deleteBuffer( data.buffer );
  8101. buffers.delete( attribute );
  8102. }
  8103. }
  8104. function update( attribute, bufferType ) {
  8105. if ( attribute.isGLBufferAttribute ) {
  8106. const cached = buffers.get( attribute );
  8107. if ( ! cached || cached.version < attribute.version ) {
  8108. buffers.set( attribute, {
  8109. buffer: attribute.buffer,
  8110. type: attribute.type,
  8111. bytesPerElement: attribute.elementSize,
  8112. version: attribute.version
  8113. } );
  8114. }
  8115. return;
  8116. }
  8117. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8118. const data = buffers.get( attribute );
  8119. if ( data === undefined ) {
  8120. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8121. } else if ( data.version < attribute.version ) {
  8122. if ( data.size !== attribute.array.byteLength ) {
  8123. 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.' );
  8124. }
  8125. updateBuffer( data.buffer, attribute, bufferType );
  8126. data.version = attribute.version;
  8127. }
  8128. }
  8129. return {
  8130. get: get,
  8131. remove: remove,
  8132. update: update
  8133. };
  8134. }
  8135. class PlaneGeometry extends BufferGeometry {
  8136. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8137. super();
  8138. this.type = 'PlaneGeometry';
  8139. this.parameters = {
  8140. width: width,
  8141. height: height,
  8142. widthSegments: widthSegments,
  8143. heightSegments: heightSegments
  8144. };
  8145. const width_half = width / 2;
  8146. const height_half = height / 2;
  8147. const gridX = Math.floor( widthSegments );
  8148. const gridY = Math.floor( heightSegments );
  8149. const gridX1 = gridX + 1;
  8150. const gridY1 = gridY + 1;
  8151. const segment_width = width / gridX;
  8152. const segment_height = height / gridY;
  8153. //
  8154. const indices = [];
  8155. const vertices = [];
  8156. const normals = [];
  8157. const uvs = [];
  8158. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8159. const y = iy * segment_height - height_half;
  8160. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8161. const x = ix * segment_width - width_half;
  8162. vertices.push( x, - y, 0 );
  8163. normals.push( 0, 0, 1 );
  8164. uvs.push( ix / gridX );
  8165. uvs.push( 1 - ( iy / gridY ) );
  8166. }
  8167. }
  8168. for ( let iy = 0; iy < gridY; iy ++ ) {
  8169. for ( let ix = 0; ix < gridX; ix ++ ) {
  8170. const a = ix + gridX1 * iy;
  8171. const b = ix + gridX1 * ( iy + 1 );
  8172. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8173. const d = ( ix + 1 ) + gridX1 * iy;
  8174. indices.push( a, b, d );
  8175. indices.push( b, c, d );
  8176. }
  8177. }
  8178. this.setIndex( indices );
  8179. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8180. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8181. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8182. }
  8183. copy( source ) {
  8184. super.copy( source );
  8185. this.parameters = Object.assign( {}, source.parameters );
  8186. return this;
  8187. }
  8188. static fromJSON( data ) {
  8189. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8190. }
  8191. }
  8192. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8193. 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";
  8194. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8195. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8196. 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";
  8197. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8198. 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";
  8199. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8200. var batching_pars_vertex = "#ifdef USE_BATCHING\n\tattribute float batchId;\n\tuniform highp sampler2D batchingTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif\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";
  8201. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( batchId );\n#endif";
  8202. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8203. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8204. 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";
  8205. 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";
  8206. 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";
  8207. 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";
  8208. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8209. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8210. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8211. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8212. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8213. 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";
  8214. 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( batchId );\n\tvColor.xyz *= batchingColor.xyz;\n#endif";
  8215. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
  8216. 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";
  8217. 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";
  8218. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8219. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8220. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8221. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8222. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8223. var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}";
  8224. 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";
  8225. 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";
  8226. 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";
  8227. 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";
  8228. 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";
  8229. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8230. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8231. 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";
  8232. 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";
  8233. 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}";
  8234. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8235. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8236. 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";
  8237. 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";
  8238. 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";
  8239. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8240. 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";
  8241. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8242. 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";
  8243. 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";
  8244. 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}";
  8245. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8246. 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";
  8247. 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";
  8248. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8249. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8250. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8251. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  8252. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  8253. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8254. 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";
  8255. 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";
  8256. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8257. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8258. 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";
  8259. 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";
  8260. 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";
  8261. 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";
  8262. 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";
  8263. 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;";
  8264. 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";
  8265. 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";
  8266. 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";
  8267. 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";
  8268. 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";
  8269. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8270. 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";
  8271. 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";
  8272. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8273. 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 );";
  8274. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  8275. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8276. 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;";
  8277. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8278. 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";
  8279. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8280. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8281. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n#endif";
  8282. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8283. 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";
  8284. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8285. 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";
  8286. 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";
  8287. 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";
  8288. 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";
  8289. 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";
  8290. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8291. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8292. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\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; }";
  8293. 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";
  8294. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  8295. 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";
  8296. 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";
  8297. 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";
  8298. 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";
  8299. 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}";
  8300. 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}";
  8301. 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}";
  8302. 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}";
  8303. 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}";
  8304. 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}";
  8305. 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}";
  8306. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8307. 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}";
  8308. 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}";
  8309. 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}";
  8310. 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}";
  8311. 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}";
  8312. 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}";
  8313. 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}";
  8314. 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}";
  8315. 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}";
  8316. 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}";
  8317. 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}";
  8318. 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}";
  8319. 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}";
  8320. 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}";
  8321. 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}";
  8322. 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}";
  8323. 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}";
  8324. 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}";
  8325. 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}";
  8326. 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}";
  8327. 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}";
  8328. 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}";
  8329. 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}";
  8330. 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}";
  8331. const vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8332. 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}";
  8333. const ShaderChunk = {
  8334. alphahash_fragment: alphahash_fragment,
  8335. alphahash_pars_fragment: alphahash_pars_fragment,
  8336. alphamap_fragment: alphamap_fragment,
  8337. alphamap_pars_fragment: alphamap_pars_fragment,
  8338. alphatest_fragment: alphatest_fragment,
  8339. alphatest_pars_fragment: alphatest_pars_fragment,
  8340. aomap_fragment: aomap_fragment,
  8341. aomap_pars_fragment: aomap_pars_fragment,
  8342. batching_pars_vertex: batching_pars_vertex,
  8343. batching_vertex: batching_vertex,
  8344. begin_vertex: begin_vertex,
  8345. beginnormal_vertex: beginnormal_vertex,
  8346. bsdfs: bsdfs,
  8347. iridescence_fragment: iridescence_fragment,
  8348. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8349. clipping_planes_fragment: clipping_planes_fragment,
  8350. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8351. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8352. clipping_planes_vertex: clipping_planes_vertex,
  8353. color_fragment: color_fragment,
  8354. color_pars_fragment: color_pars_fragment,
  8355. color_pars_vertex: color_pars_vertex,
  8356. color_vertex: color_vertex,
  8357. common: common,
  8358. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8359. defaultnormal_vertex: defaultnormal_vertex,
  8360. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8361. displacementmap_vertex: displacementmap_vertex,
  8362. emissivemap_fragment: emissivemap_fragment,
  8363. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8364. colorspace_fragment: colorspace_fragment,
  8365. colorspace_pars_fragment: colorspace_pars_fragment,
  8366. envmap_fragment: envmap_fragment,
  8367. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8368. envmap_pars_fragment: envmap_pars_fragment,
  8369. envmap_pars_vertex: envmap_pars_vertex,
  8370. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8371. envmap_vertex: envmap_vertex,
  8372. fog_vertex: fog_vertex,
  8373. fog_pars_vertex: fog_pars_vertex,
  8374. fog_fragment: fog_fragment,
  8375. fog_pars_fragment: fog_pars_fragment,
  8376. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8377. lightmap_pars_fragment: lightmap_pars_fragment,
  8378. lights_lambert_fragment: lights_lambert_fragment,
  8379. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8380. lights_pars_begin: lights_pars_begin,
  8381. lights_toon_fragment: lights_toon_fragment,
  8382. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8383. lights_phong_fragment: lights_phong_fragment,
  8384. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8385. lights_physical_fragment: lights_physical_fragment,
  8386. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8387. lights_fragment_begin: lights_fragment_begin,
  8388. lights_fragment_maps: lights_fragment_maps,
  8389. lights_fragment_end: lights_fragment_end,
  8390. logdepthbuf_fragment: logdepthbuf_fragment,
  8391. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8392. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8393. logdepthbuf_vertex: logdepthbuf_vertex,
  8394. map_fragment: map_fragment,
  8395. map_pars_fragment: map_pars_fragment,
  8396. map_particle_fragment: map_particle_fragment,
  8397. map_particle_pars_fragment: map_particle_pars_fragment,
  8398. metalnessmap_fragment: metalnessmap_fragment,
  8399. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8400. morphinstance_vertex: morphinstance_vertex,
  8401. morphcolor_vertex: morphcolor_vertex,
  8402. morphnormal_vertex: morphnormal_vertex,
  8403. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8404. morphtarget_vertex: morphtarget_vertex,
  8405. normal_fragment_begin: normal_fragment_begin,
  8406. normal_fragment_maps: normal_fragment_maps,
  8407. normal_pars_fragment: normal_pars_fragment,
  8408. normal_pars_vertex: normal_pars_vertex,
  8409. normal_vertex: normal_vertex,
  8410. normalmap_pars_fragment: normalmap_pars_fragment,
  8411. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8412. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8413. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8414. iridescence_pars_fragment: iridescence_pars_fragment,
  8415. opaque_fragment: opaque_fragment,
  8416. packing: packing,
  8417. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8418. project_vertex: project_vertex,
  8419. dithering_fragment: dithering_fragment,
  8420. dithering_pars_fragment: dithering_pars_fragment,
  8421. roughnessmap_fragment: roughnessmap_fragment,
  8422. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8423. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8424. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8425. shadowmap_vertex: shadowmap_vertex,
  8426. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8427. skinbase_vertex: skinbase_vertex,
  8428. skinning_pars_vertex: skinning_pars_vertex,
  8429. skinning_vertex: skinning_vertex,
  8430. skinnormal_vertex: skinnormal_vertex,
  8431. specularmap_fragment: specularmap_fragment,
  8432. specularmap_pars_fragment: specularmap_pars_fragment,
  8433. tonemapping_fragment: tonemapping_fragment,
  8434. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8435. transmission_fragment: transmission_fragment,
  8436. transmission_pars_fragment: transmission_pars_fragment,
  8437. uv_pars_fragment: uv_pars_fragment,
  8438. uv_pars_vertex: uv_pars_vertex,
  8439. uv_vertex: uv_vertex,
  8440. worldpos_vertex: worldpos_vertex,
  8441. background_vert: vertex$h,
  8442. background_frag: fragment$h,
  8443. backgroundCube_vert: vertex$g,
  8444. backgroundCube_frag: fragment$g,
  8445. cube_vert: vertex$f,
  8446. cube_frag: fragment$f,
  8447. depth_vert: vertex$e,
  8448. depth_frag: fragment$e,
  8449. distanceRGBA_vert: vertex$d,
  8450. distanceRGBA_frag: fragment$d,
  8451. equirect_vert: vertex$c,
  8452. equirect_frag: fragment$c,
  8453. linedashed_vert: vertex$b,
  8454. linedashed_frag: fragment$b,
  8455. meshbasic_vert: vertex$a,
  8456. meshbasic_frag: fragment$a,
  8457. meshlambert_vert: vertex$9,
  8458. meshlambert_frag: fragment$9,
  8459. meshmatcap_vert: vertex$8,
  8460. meshmatcap_frag: fragment$8,
  8461. meshnormal_vert: vertex$7,
  8462. meshnormal_frag: fragment$7,
  8463. meshphong_vert: vertex$6,
  8464. meshphong_frag: fragment$6,
  8465. meshphysical_vert: vertex$5,
  8466. meshphysical_frag: fragment$5,
  8467. meshtoon_vert: vertex$4,
  8468. meshtoon_frag: fragment$4,
  8469. points_vert: vertex$3,
  8470. points_frag: fragment$3,
  8471. shadow_vert: vertex$2,
  8472. shadow_frag: fragment$2,
  8473. sprite_vert: vertex$1,
  8474. sprite_frag: fragment$1
  8475. };
  8476. /**
  8477. * Uniforms library for shared webgl shaders
  8478. */
  8479. const UniformsLib = {
  8480. common: {
  8481. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8482. opacity: { value: 1.0 },
  8483. map: { value: null },
  8484. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8485. alphaMap: { value: null },
  8486. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8487. alphaTest: { value: 0 }
  8488. },
  8489. specularmap: {
  8490. specularMap: { value: null },
  8491. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8492. },
  8493. envmap: {
  8494. envMap: { value: null },
  8495. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  8496. flipEnvMap: { value: - 1 },
  8497. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8498. ior: { value: 1.5 }, // physical
  8499. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8500. },
  8501. aomap: {
  8502. aoMap: { value: null },
  8503. aoMapIntensity: { value: 1 },
  8504. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8505. },
  8506. lightmap: {
  8507. lightMap: { value: null },
  8508. lightMapIntensity: { value: 1 },
  8509. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8510. },
  8511. bumpmap: {
  8512. bumpMap: { value: null },
  8513. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8514. bumpScale: { value: 1 }
  8515. },
  8516. normalmap: {
  8517. normalMap: { value: null },
  8518. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8519. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8520. },
  8521. displacementmap: {
  8522. displacementMap: { value: null },
  8523. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8524. displacementScale: { value: 1 },
  8525. displacementBias: { value: 0 }
  8526. },
  8527. emissivemap: {
  8528. emissiveMap: { value: null },
  8529. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8530. },
  8531. metalnessmap: {
  8532. metalnessMap: { value: null },
  8533. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8534. },
  8535. roughnessmap: {
  8536. roughnessMap: { value: null },
  8537. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8538. },
  8539. gradientmap: {
  8540. gradientMap: { value: null }
  8541. },
  8542. fog: {
  8543. fogDensity: { value: 0.00025 },
  8544. fogNear: { value: 1 },
  8545. fogFar: { value: 2000 },
  8546. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8547. },
  8548. lights: {
  8549. ambientLightColor: { value: [] },
  8550. lightProbe: { value: [] },
  8551. directionalLights: { value: [], properties: {
  8552. direction: {},
  8553. color: {}
  8554. } },
  8555. directionalLightShadows: { value: [], properties: {
  8556. shadowBias: {},
  8557. shadowNormalBias: {},
  8558. shadowRadius: {},
  8559. shadowMapSize: {}
  8560. } },
  8561. directionalShadowMap: { value: [] },
  8562. directionalShadowMatrix: { value: [] },
  8563. spotLights: { value: [], properties: {
  8564. color: {},
  8565. position: {},
  8566. direction: {},
  8567. distance: {},
  8568. coneCos: {},
  8569. penumbraCos: {},
  8570. decay: {}
  8571. } },
  8572. spotLightShadows: { value: [], properties: {
  8573. shadowBias: {},
  8574. shadowNormalBias: {},
  8575. shadowRadius: {},
  8576. shadowMapSize: {}
  8577. } },
  8578. spotLightMap: { value: [] },
  8579. spotShadowMap: { value: [] },
  8580. spotLightMatrix: { value: [] },
  8581. pointLights: { value: [], properties: {
  8582. color: {},
  8583. position: {},
  8584. decay: {},
  8585. distance: {}
  8586. } },
  8587. pointLightShadows: { value: [], properties: {
  8588. shadowBias: {},
  8589. shadowNormalBias: {},
  8590. shadowRadius: {},
  8591. shadowMapSize: {},
  8592. shadowCameraNear: {},
  8593. shadowCameraFar: {}
  8594. } },
  8595. pointShadowMap: { value: [] },
  8596. pointShadowMatrix: { value: [] },
  8597. hemisphereLights: { value: [], properties: {
  8598. direction: {},
  8599. skyColor: {},
  8600. groundColor: {}
  8601. } },
  8602. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8603. rectAreaLights: { value: [], properties: {
  8604. color: {},
  8605. position: {},
  8606. width: {},
  8607. height: {}
  8608. } },
  8609. ltc_1: { value: null },
  8610. ltc_2: { value: null }
  8611. },
  8612. points: {
  8613. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8614. opacity: { value: 1.0 },
  8615. size: { value: 1.0 },
  8616. scale: { value: 1.0 },
  8617. map: { value: null },
  8618. alphaMap: { value: null },
  8619. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8620. alphaTest: { value: 0 },
  8621. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8622. },
  8623. sprite: {
  8624. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8625. opacity: { value: 1.0 },
  8626. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8627. rotation: { value: 0.0 },
  8628. map: { value: null },
  8629. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8630. alphaMap: { value: null },
  8631. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8632. alphaTest: { value: 0 }
  8633. }
  8634. };
  8635. const ShaderLib = {
  8636. basic: {
  8637. uniforms: /*@__PURE__*/ mergeUniforms( [
  8638. UniformsLib.common,
  8639. UniformsLib.specularmap,
  8640. UniformsLib.envmap,
  8641. UniformsLib.aomap,
  8642. UniformsLib.lightmap,
  8643. UniformsLib.fog
  8644. ] ),
  8645. vertexShader: ShaderChunk.meshbasic_vert,
  8646. fragmentShader: ShaderChunk.meshbasic_frag
  8647. },
  8648. lambert: {
  8649. uniforms: /*@__PURE__*/ mergeUniforms( [
  8650. UniformsLib.common,
  8651. UniformsLib.specularmap,
  8652. UniformsLib.envmap,
  8653. UniformsLib.aomap,
  8654. UniformsLib.lightmap,
  8655. UniformsLib.emissivemap,
  8656. UniformsLib.bumpmap,
  8657. UniformsLib.normalmap,
  8658. UniformsLib.displacementmap,
  8659. UniformsLib.fog,
  8660. UniformsLib.lights,
  8661. {
  8662. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8663. }
  8664. ] ),
  8665. vertexShader: ShaderChunk.meshlambert_vert,
  8666. fragmentShader: ShaderChunk.meshlambert_frag
  8667. },
  8668. phong: {
  8669. uniforms: /*@__PURE__*/ mergeUniforms( [
  8670. UniformsLib.common,
  8671. UniformsLib.specularmap,
  8672. UniformsLib.envmap,
  8673. UniformsLib.aomap,
  8674. UniformsLib.lightmap,
  8675. UniformsLib.emissivemap,
  8676. UniformsLib.bumpmap,
  8677. UniformsLib.normalmap,
  8678. UniformsLib.displacementmap,
  8679. UniformsLib.fog,
  8680. UniformsLib.lights,
  8681. {
  8682. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8683. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8684. shininess: { value: 30 }
  8685. }
  8686. ] ),
  8687. vertexShader: ShaderChunk.meshphong_vert,
  8688. fragmentShader: ShaderChunk.meshphong_frag
  8689. },
  8690. standard: {
  8691. uniforms: /*@__PURE__*/ mergeUniforms( [
  8692. UniformsLib.common,
  8693. UniformsLib.envmap,
  8694. UniformsLib.aomap,
  8695. UniformsLib.lightmap,
  8696. UniformsLib.emissivemap,
  8697. UniformsLib.bumpmap,
  8698. UniformsLib.normalmap,
  8699. UniformsLib.displacementmap,
  8700. UniformsLib.roughnessmap,
  8701. UniformsLib.metalnessmap,
  8702. UniformsLib.fog,
  8703. UniformsLib.lights,
  8704. {
  8705. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8706. roughness: { value: 1.0 },
  8707. metalness: { value: 0.0 },
  8708. envMapIntensity: { value: 1 }
  8709. }
  8710. ] ),
  8711. vertexShader: ShaderChunk.meshphysical_vert,
  8712. fragmentShader: ShaderChunk.meshphysical_frag
  8713. },
  8714. toon: {
  8715. uniforms: /*@__PURE__*/ mergeUniforms( [
  8716. UniformsLib.common,
  8717. UniformsLib.aomap,
  8718. UniformsLib.lightmap,
  8719. UniformsLib.emissivemap,
  8720. UniformsLib.bumpmap,
  8721. UniformsLib.normalmap,
  8722. UniformsLib.displacementmap,
  8723. UniformsLib.gradientmap,
  8724. UniformsLib.fog,
  8725. UniformsLib.lights,
  8726. {
  8727. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8728. }
  8729. ] ),
  8730. vertexShader: ShaderChunk.meshtoon_vert,
  8731. fragmentShader: ShaderChunk.meshtoon_frag
  8732. },
  8733. matcap: {
  8734. uniforms: /*@__PURE__*/ mergeUniforms( [
  8735. UniformsLib.common,
  8736. UniformsLib.bumpmap,
  8737. UniformsLib.normalmap,
  8738. UniformsLib.displacementmap,
  8739. UniformsLib.fog,
  8740. {
  8741. matcap: { value: null }
  8742. }
  8743. ] ),
  8744. vertexShader: ShaderChunk.meshmatcap_vert,
  8745. fragmentShader: ShaderChunk.meshmatcap_frag
  8746. },
  8747. points: {
  8748. uniforms: /*@__PURE__*/ mergeUniforms( [
  8749. UniformsLib.points,
  8750. UniformsLib.fog
  8751. ] ),
  8752. vertexShader: ShaderChunk.points_vert,
  8753. fragmentShader: ShaderChunk.points_frag
  8754. },
  8755. dashed: {
  8756. uniforms: /*@__PURE__*/ mergeUniforms( [
  8757. UniformsLib.common,
  8758. UniformsLib.fog,
  8759. {
  8760. scale: { value: 1 },
  8761. dashSize: { value: 1 },
  8762. totalSize: { value: 2 }
  8763. }
  8764. ] ),
  8765. vertexShader: ShaderChunk.linedashed_vert,
  8766. fragmentShader: ShaderChunk.linedashed_frag
  8767. },
  8768. depth: {
  8769. uniforms: /*@__PURE__*/ mergeUniforms( [
  8770. UniformsLib.common,
  8771. UniformsLib.displacementmap
  8772. ] ),
  8773. vertexShader: ShaderChunk.depth_vert,
  8774. fragmentShader: ShaderChunk.depth_frag
  8775. },
  8776. normal: {
  8777. uniforms: /*@__PURE__*/ mergeUniforms( [
  8778. UniformsLib.common,
  8779. UniformsLib.bumpmap,
  8780. UniformsLib.normalmap,
  8781. UniformsLib.displacementmap,
  8782. {
  8783. opacity: { value: 1.0 }
  8784. }
  8785. ] ),
  8786. vertexShader: ShaderChunk.meshnormal_vert,
  8787. fragmentShader: ShaderChunk.meshnormal_frag
  8788. },
  8789. sprite: {
  8790. uniforms: /*@__PURE__*/ mergeUniforms( [
  8791. UniformsLib.sprite,
  8792. UniformsLib.fog
  8793. ] ),
  8794. vertexShader: ShaderChunk.sprite_vert,
  8795. fragmentShader: ShaderChunk.sprite_frag
  8796. },
  8797. background: {
  8798. uniforms: {
  8799. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8800. t2D: { value: null },
  8801. backgroundIntensity: { value: 1 }
  8802. },
  8803. vertexShader: ShaderChunk.background_vert,
  8804. fragmentShader: ShaderChunk.background_frag
  8805. },
  8806. backgroundCube: {
  8807. uniforms: {
  8808. envMap: { value: null },
  8809. flipEnvMap: { value: - 1 },
  8810. backgroundBlurriness: { value: 0 },
  8811. backgroundIntensity: { value: 1 },
  8812. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  8813. },
  8814. vertexShader: ShaderChunk.backgroundCube_vert,
  8815. fragmentShader: ShaderChunk.backgroundCube_frag
  8816. },
  8817. cube: {
  8818. uniforms: {
  8819. tCube: { value: null },
  8820. tFlip: { value: - 1 },
  8821. opacity: { value: 1.0 }
  8822. },
  8823. vertexShader: ShaderChunk.cube_vert,
  8824. fragmentShader: ShaderChunk.cube_frag
  8825. },
  8826. equirect: {
  8827. uniforms: {
  8828. tEquirect: { value: null },
  8829. },
  8830. vertexShader: ShaderChunk.equirect_vert,
  8831. fragmentShader: ShaderChunk.equirect_frag
  8832. },
  8833. distanceRGBA: {
  8834. uniforms: /*@__PURE__*/ mergeUniforms( [
  8835. UniformsLib.common,
  8836. UniformsLib.displacementmap,
  8837. {
  8838. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8839. nearDistance: { value: 1 },
  8840. farDistance: { value: 1000 }
  8841. }
  8842. ] ),
  8843. vertexShader: ShaderChunk.distanceRGBA_vert,
  8844. fragmentShader: ShaderChunk.distanceRGBA_frag
  8845. },
  8846. shadow: {
  8847. uniforms: /*@__PURE__*/ mergeUniforms( [
  8848. UniformsLib.lights,
  8849. UniformsLib.fog,
  8850. {
  8851. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8852. opacity: { value: 1.0 }
  8853. },
  8854. ] ),
  8855. vertexShader: ShaderChunk.shadow_vert,
  8856. fragmentShader: ShaderChunk.shadow_frag
  8857. }
  8858. };
  8859. ShaderLib.physical = {
  8860. uniforms: /*@__PURE__*/ mergeUniforms( [
  8861. ShaderLib.standard.uniforms,
  8862. {
  8863. clearcoat: { value: 0 },
  8864. clearcoatMap: { value: null },
  8865. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8866. clearcoatNormalMap: { value: null },
  8867. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8868. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8869. clearcoatRoughness: { value: 0 },
  8870. clearcoatRoughnessMap: { value: null },
  8871. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8872. dispersion: { value: 0 },
  8873. iridescence: { value: 0 },
  8874. iridescenceMap: { value: null },
  8875. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8876. iridescenceIOR: { value: 1.3 },
  8877. iridescenceThicknessMinimum: { value: 100 },
  8878. iridescenceThicknessMaximum: { value: 400 },
  8879. iridescenceThicknessMap: { value: null },
  8880. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8881. sheen: { value: 0 },
  8882. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8883. sheenColorMap: { value: null },
  8884. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8885. sheenRoughness: { value: 1 },
  8886. sheenRoughnessMap: { value: null },
  8887. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8888. transmission: { value: 0 },
  8889. transmissionMap: { value: null },
  8890. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8891. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8892. transmissionSamplerMap: { value: null },
  8893. thickness: { value: 0 },
  8894. thicknessMap: { value: null },
  8895. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8896. attenuationDistance: { value: 0 },
  8897. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8898. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8899. specularColorMap: { value: null },
  8900. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8901. specularIntensity: { value: 1 },
  8902. specularIntensityMap: { value: null },
  8903. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8904. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8905. anisotropyMap: { value: null },
  8906. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8907. }
  8908. ] ),
  8909. vertexShader: ShaderChunk.meshphysical_vert,
  8910. fragmentShader: ShaderChunk.meshphysical_frag
  8911. };
  8912. const _rgb = { r: 0, b: 0, g: 0 };
  8913. const _e1$1 = /*@__PURE__*/ new Euler();
  8914. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8915. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8916. const clearColor = new Color( 0x000000 );
  8917. let clearAlpha = alpha === true ? 0 : 1;
  8918. let planeMesh;
  8919. let boxMesh;
  8920. let currentBackground = null;
  8921. let currentBackgroundVersion = 0;
  8922. let currentTonemapping = null;
  8923. function getBackground( scene ) {
  8924. let background = scene.isScene === true ? scene.background : null;
  8925. if ( background && background.isTexture ) {
  8926. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8927. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8928. }
  8929. return background;
  8930. }
  8931. function render( scene ) {
  8932. let forceClear = false;
  8933. const background = getBackground( scene );
  8934. if ( background === null ) {
  8935. setClear( clearColor, clearAlpha );
  8936. } else if ( background && background.isColor ) {
  8937. setClear( background, 1 );
  8938. forceClear = true;
  8939. }
  8940. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8941. if ( environmentBlendMode === 'additive' ) {
  8942. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8943. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8944. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8945. }
  8946. if ( renderer.autoClear || forceClear ) {
  8947. // buffers might not be writable which is required to ensure a correct clear
  8948. state.buffers.depth.setTest( true );
  8949. state.buffers.depth.setMask( true );
  8950. state.buffers.color.setMask( true );
  8951. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8952. }
  8953. }
  8954. function addToRenderList( renderList, scene ) {
  8955. const background = getBackground( scene );
  8956. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8957. if ( boxMesh === undefined ) {
  8958. boxMesh = new Mesh(
  8959. new BoxGeometry( 1, 1, 1 ),
  8960. new ShaderMaterial( {
  8961. name: 'BackgroundCubeMaterial',
  8962. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8963. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8964. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8965. side: BackSide,
  8966. depthTest: false,
  8967. depthWrite: false,
  8968. fog: false
  8969. } )
  8970. );
  8971. boxMesh.geometry.deleteAttribute( 'normal' );
  8972. boxMesh.geometry.deleteAttribute( 'uv' );
  8973. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8974. this.matrixWorld.copyPosition( camera.matrixWorld );
  8975. };
  8976. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8977. Object.defineProperty( boxMesh.material, 'envMap', {
  8978. get: function () {
  8979. return this.uniforms.envMap.value;
  8980. }
  8981. } );
  8982. objects.update( boxMesh );
  8983. }
  8984. _e1$1.copy( scene.backgroundRotation );
  8985. // accommodate left-handed frame
  8986. _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1;
  8987. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  8988. // environment maps which are not cube render targets or PMREMs follow a different convention
  8989. _e1$1.y *= - 1;
  8990. _e1$1.z *= - 1;
  8991. }
  8992. boxMesh.material.uniforms.envMap.value = background;
  8993. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8994. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8995. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8996. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  8997. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8998. if ( currentBackground !== background ||
  8999. currentBackgroundVersion !== background.version ||
  9000. currentTonemapping !== renderer.toneMapping ) {
  9001. boxMesh.material.needsUpdate = true;
  9002. currentBackground = background;
  9003. currentBackgroundVersion = background.version;
  9004. currentTonemapping = renderer.toneMapping;
  9005. }
  9006. boxMesh.layers.enableAll();
  9007. // push to the pre-sorted opaque render list
  9008. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9009. } else if ( background && background.isTexture ) {
  9010. if ( planeMesh === undefined ) {
  9011. planeMesh = new Mesh(
  9012. new PlaneGeometry( 2, 2 ),
  9013. new ShaderMaterial( {
  9014. name: 'BackgroundMaterial',
  9015. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9016. vertexShader: ShaderLib.background.vertexShader,
  9017. fragmentShader: ShaderLib.background.fragmentShader,
  9018. side: FrontSide,
  9019. depthTest: false,
  9020. depthWrite: false,
  9021. fog: false
  9022. } )
  9023. );
  9024. planeMesh.geometry.deleteAttribute( 'normal' );
  9025. // add "map" material property so the renderer can evaluate it like for built-in materials
  9026. Object.defineProperty( planeMesh.material, 'map', {
  9027. get: function () {
  9028. return this.uniforms.t2D.value;
  9029. }
  9030. } );
  9031. objects.update( planeMesh );
  9032. }
  9033. planeMesh.material.uniforms.t2D.value = background;
  9034. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  9035. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  9036. if ( background.matrixAutoUpdate === true ) {
  9037. background.updateMatrix();
  9038. }
  9039. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9040. if ( currentBackground !== background ||
  9041. currentBackgroundVersion !== background.version ||
  9042. currentTonemapping !== renderer.toneMapping ) {
  9043. planeMesh.material.needsUpdate = true;
  9044. currentBackground = background;
  9045. currentBackgroundVersion = background.version;
  9046. currentTonemapping = renderer.toneMapping;
  9047. }
  9048. planeMesh.layers.enableAll();
  9049. // push to the pre-sorted opaque render list
  9050. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9051. }
  9052. }
  9053. function setClear( color, alpha ) {
  9054. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  9055. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  9056. }
  9057. return {
  9058. getClearColor: function () {
  9059. return clearColor;
  9060. },
  9061. setClearColor: function ( color, alpha = 1 ) {
  9062. clearColor.set( color );
  9063. clearAlpha = alpha;
  9064. setClear( clearColor, clearAlpha );
  9065. },
  9066. getClearAlpha: function () {
  9067. return clearAlpha;
  9068. },
  9069. setClearAlpha: function ( alpha ) {
  9070. clearAlpha = alpha;
  9071. setClear( clearColor, clearAlpha );
  9072. },
  9073. render: render,
  9074. addToRenderList: addToRenderList
  9075. };
  9076. }
  9077. function WebGLBindingStates( gl, attributes ) {
  9078. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9079. const bindingStates = {};
  9080. const defaultState = createBindingState( null );
  9081. let currentState = defaultState;
  9082. let forceUpdate = false;
  9083. function setup( object, material, program, geometry, index ) {
  9084. let updateBuffers = false;
  9085. const state = getBindingState( geometry, program, material );
  9086. if ( currentState !== state ) {
  9087. currentState = state;
  9088. bindVertexArrayObject( currentState.object );
  9089. }
  9090. updateBuffers = needsUpdate( object, geometry, program, index );
  9091. if ( updateBuffers ) saveCache( object, geometry, program, index );
  9092. if ( index !== null ) {
  9093. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9094. }
  9095. if ( updateBuffers || forceUpdate ) {
  9096. forceUpdate = false;
  9097. setupVertexAttributes( object, material, program, geometry );
  9098. if ( index !== null ) {
  9099. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9100. }
  9101. }
  9102. }
  9103. function createVertexArrayObject() {
  9104. return gl.createVertexArray();
  9105. }
  9106. function bindVertexArrayObject( vao ) {
  9107. return gl.bindVertexArray( vao );
  9108. }
  9109. function deleteVertexArrayObject( vao ) {
  9110. return gl.deleteVertexArray( vao );
  9111. }
  9112. function getBindingState( geometry, program, material ) {
  9113. const wireframe = ( material.wireframe === true );
  9114. let programMap = bindingStates[ geometry.id ];
  9115. if ( programMap === undefined ) {
  9116. programMap = {};
  9117. bindingStates[ geometry.id ] = programMap;
  9118. }
  9119. let stateMap = programMap[ program.id ];
  9120. if ( stateMap === undefined ) {
  9121. stateMap = {};
  9122. programMap[ program.id ] = stateMap;
  9123. }
  9124. let state = stateMap[ wireframe ];
  9125. if ( state === undefined ) {
  9126. state = createBindingState( createVertexArrayObject() );
  9127. stateMap[ wireframe ] = state;
  9128. }
  9129. return state;
  9130. }
  9131. function createBindingState( vao ) {
  9132. const newAttributes = [];
  9133. const enabledAttributes = [];
  9134. const attributeDivisors = [];
  9135. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9136. newAttributes[ i ] = 0;
  9137. enabledAttributes[ i ] = 0;
  9138. attributeDivisors[ i ] = 0;
  9139. }
  9140. return {
  9141. // for backward compatibility on non-VAO support browser
  9142. geometry: null,
  9143. program: null,
  9144. wireframe: false,
  9145. newAttributes: newAttributes,
  9146. enabledAttributes: enabledAttributes,
  9147. attributeDivisors: attributeDivisors,
  9148. object: vao,
  9149. attributes: {},
  9150. index: null
  9151. };
  9152. }
  9153. function needsUpdate( object, geometry, program, index ) {
  9154. const cachedAttributes = currentState.attributes;
  9155. const geometryAttributes = geometry.attributes;
  9156. let attributesNum = 0;
  9157. const programAttributes = program.getAttributes();
  9158. for ( const name in programAttributes ) {
  9159. const programAttribute = programAttributes[ name ];
  9160. if ( programAttribute.location >= 0 ) {
  9161. const cachedAttribute = cachedAttributes[ name ];
  9162. let geometryAttribute = geometryAttributes[ name ];
  9163. if ( geometryAttribute === undefined ) {
  9164. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9165. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9166. }
  9167. if ( cachedAttribute === undefined ) return true;
  9168. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9169. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9170. attributesNum ++;
  9171. }
  9172. }
  9173. if ( currentState.attributesNum !== attributesNum ) return true;
  9174. if ( currentState.index !== index ) return true;
  9175. return false;
  9176. }
  9177. function saveCache( object, geometry, program, index ) {
  9178. const cache = {};
  9179. const attributes = geometry.attributes;
  9180. let attributesNum = 0;
  9181. const programAttributes = program.getAttributes();
  9182. for ( const name in programAttributes ) {
  9183. const programAttribute = programAttributes[ name ];
  9184. if ( programAttribute.location >= 0 ) {
  9185. let attribute = attributes[ name ];
  9186. if ( attribute === undefined ) {
  9187. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9188. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9189. }
  9190. const data = {};
  9191. data.attribute = attribute;
  9192. if ( attribute && attribute.data ) {
  9193. data.data = attribute.data;
  9194. }
  9195. cache[ name ] = data;
  9196. attributesNum ++;
  9197. }
  9198. }
  9199. currentState.attributes = cache;
  9200. currentState.attributesNum = attributesNum;
  9201. currentState.index = index;
  9202. }
  9203. function initAttributes() {
  9204. const newAttributes = currentState.newAttributes;
  9205. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9206. newAttributes[ i ] = 0;
  9207. }
  9208. }
  9209. function enableAttribute( attribute ) {
  9210. enableAttributeAndDivisor( attribute, 0 );
  9211. }
  9212. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9213. const newAttributes = currentState.newAttributes;
  9214. const enabledAttributes = currentState.enabledAttributes;
  9215. const attributeDivisors = currentState.attributeDivisors;
  9216. newAttributes[ attribute ] = 1;
  9217. if ( enabledAttributes[ attribute ] === 0 ) {
  9218. gl.enableVertexAttribArray( attribute );
  9219. enabledAttributes[ attribute ] = 1;
  9220. }
  9221. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9222. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  9223. attributeDivisors[ attribute ] = meshPerAttribute;
  9224. }
  9225. }
  9226. function disableUnusedAttributes() {
  9227. const newAttributes = currentState.newAttributes;
  9228. const enabledAttributes = currentState.enabledAttributes;
  9229. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9230. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9231. gl.disableVertexAttribArray( i );
  9232. enabledAttributes[ i ] = 0;
  9233. }
  9234. }
  9235. }
  9236. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9237. if ( integer === true ) {
  9238. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9239. } else {
  9240. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9241. }
  9242. }
  9243. function setupVertexAttributes( object, material, program, geometry ) {
  9244. initAttributes();
  9245. const geometryAttributes = geometry.attributes;
  9246. const programAttributes = program.getAttributes();
  9247. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9248. for ( const name in programAttributes ) {
  9249. const programAttribute = programAttributes[ name ];
  9250. if ( programAttribute.location >= 0 ) {
  9251. let geometryAttribute = geometryAttributes[ name ];
  9252. if ( geometryAttribute === undefined ) {
  9253. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9254. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9255. }
  9256. if ( geometryAttribute !== undefined ) {
  9257. const normalized = geometryAttribute.normalized;
  9258. const size = geometryAttribute.itemSize;
  9259. const attribute = attributes.get( geometryAttribute );
  9260. // TODO Attribute may not be available on context restore
  9261. if ( attribute === undefined ) continue;
  9262. const buffer = attribute.buffer;
  9263. const type = attribute.type;
  9264. const bytesPerElement = attribute.bytesPerElement;
  9265. // check for integer attributes
  9266. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  9267. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9268. const data = geometryAttribute.data;
  9269. const stride = data.stride;
  9270. const offset = geometryAttribute.offset;
  9271. if ( data.isInstancedInterleavedBuffer ) {
  9272. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9273. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9274. }
  9275. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9276. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9277. }
  9278. } else {
  9279. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9280. enableAttribute( programAttribute.location + i );
  9281. }
  9282. }
  9283. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9284. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9285. vertexAttribPointer(
  9286. programAttribute.location + i,
  9287. size / programAttribute.locationSize,
  9288. type,
  9289. normalized,
  9290. stride * bytesPerElement,
  9291. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9292. integer
  9293. );
  9294. }
  9295. } else {
  9296. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9297. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9298. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9299. }
  9300. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9301. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9302. }
  9303. } else {
  9304. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9305. enableAttribute( programAttribute.location + i );
  9306. }
  9307. }
  9308. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9309. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9310. vertexAttribPointer(
  9311. programAttribute.location + i,
  9312. size / programAttribute.locationSize,
  9313. type,
  9314. normalized,
  9315. size * bytesPerElement,
  9316. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9317. integer
  9318. );
  9319. }
  9320. }
  9321. } else if ( materialDefaultAttributeValues !== undefined ) {
  9322. const value = materialDefaultAttributeValues[ name ];
  9323. if ( value !== undefined ) {
  9324. switch ( value.length ) {
  9325. case 2:
  9326. gl.vertexAttrib2fv( programAttribute.location, value );
  9327. break;
  9328. case 3:
  9329. gl.vertexAttrib3fv( programAttribute.location, value );
  9330. break;
  9331. case 4:
  9332. gl.vertexAttrib4fv( programAttribute.location, value );
  9333. break;
  9334. default:
  9335. gl.vertexAttrib1fv( programAttribute.location, value );
  9336. }
  9337. }
  9338. }
  9339. }
  9340. }
  9341. disableUnusedAttributes();
  9342. }
  9343. function dispose() {
  9344. reset();
  9345. for ( const geometryId in bindingStates ) {
  9346. const programMap = bindingStates[ geometryId ];
  9347. for ( const programId in programMap ) {
  9348. const stateMap = programMap[ programId ];
  9349. for ( const wireframe in stateMap ) {
  9350. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9351. delete stateMap[ wireframe ];
  9352. }
  9353. delete programMap[ programId ];
  9354. }
  9355. delete bindingStates[ geometryId ];
  9356. }
  9357. }
  9358. function releaseStatesOfGeometry( geometry ) {
  9359. if ( bindingStates[ geometry.id ] === undefined ) return;
  9360. const programMap = bindingStates[ geometry.id ];
  9361. for ( const programId in programMap ) {
  9362. const stateMap = programMap[ programId ];
  9363. for ( const wireframe in stateMap ) {
  9364. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9365. delete stateMap[ wireframe ];
  9366. }
  9367. delete programMap[ programId ];
  9368. }
  9369. delete bindingStates[ geometry.id ];
  9370. }
  9371. function releaseStatesOfProgram( program ) {
  9372. for ( const geometryId in bindingStates ) {
  9373. const programMap = bindingStates[ geometryId ];
  9374. if ( programMap[ program.id ] === undefined ) continue;
  9375. const stateMap = programMap[ program.id ];
  9376. for ( const wireframe in stateMap ) {
  9377. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9378. delete stateMap[ wireframe ];
  9379. }
  9380. delete programMap[ program.id ];
  9381. }
  9382. }
  9383. function reset() {
  9384. resetDefaultState();
  9385. forceUpdate = true;
  9386. if ( currentState === defaultState ) return;
  9387. currentState = defaultState;
  9388. bindVertexArrayObject( currentState.object );
  9389. }
  9390. // for backward-compatibility
  9391. function resetDefaultState() {
  9392. defaultState.geometry = null;
  9393. defaultState.program = null;
  9394. defaultState.wireframe = false;
  9395. }
  9396. return {
  9397. setup: setup,
  9398. reset: reset,
  9399. resetDefaultState: resetDefaultState,
  9400. dispose: dispose,
  9401. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9402. releaseStatesOfProgram: releaseStatesOfProgram,
  9403. initAttributes: initAttributes,
  9404. enableAttribute: enableAttribute,
  9405. disableUnusedAttributes: disableUnusedAttributes
  9406. };
  9407. }
  9408. function WebGLBufferRenderer( gl, extensions, info ) {
  9409. let mode;
  9410. function setMode( value ) {
  9411. mode = value;
  9412. }
  9413. function render( start, count ) {
  9414. gl.drawArrays( mode, start, count );
  9415. info.update( count, mode, 1 );
  9416. }
  9417. function renderInstances( start, count, primcount ) {
  9418. if ( primcount === 0 ) return;
  9419. gl.drawArraysInstanced( mode, start, count, primcount );
  9420. info.update( count, mode, primcount );
  9421. }
  9422. function renderMultiDraw( starts, counts, drawCount ) {
  9423. if ( drawCount === 0 ) return;
  9424. const extension = extensions.get( 'WEBGL_multi_draw' );
  9425. if ( extension === null ) {
  9426. for ( let i = 0; i < drawCount; i ++ ) {
  9427. this.render( starts[ i ], counts[ i ] );
  9428. }
  9429. } else {
  9430. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  9431. let elementCount = 0;
  9432. for ( let i = 0; i < drawCount; i ++ ) {
  9433. elementCount += counts[ i ];
  9434. }
  9435. info.update( elementCount, mode, 1 );
  9436. }
  9437. }
  9438. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  9439. if ( drawCount === 0 ) return;
  9440. const extension = extensions.get( 'WEBGL_multi_draw' );
  9441. if ( extension === null ) {
  9442. for ( let i = 0; i < starts.length; i ++ ) {
  9443. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  9444. }
  9445. } else {
  9446. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  9447. let elementCount = 0;
  9448. for ( let i = 0; i < drawCount; i ++ ) {
  9449. elementCount += counts[ i ];
  9450. }
  9451. for ( let i = 0; i < primcount.length; i ++ ) {
  9452. info.update( elementCount, mode, primcount[ i ] );
  9453. }
  9454. }
  9455. }
  9456. //
  9457. this.setMode = setMode;
  9458. this.render = render;
  9459. this.renderInstances = renderInstances;
  9460. this.renderMultiDraw = renderMultiDraw;
  9461. this.renderMultiDrawInstances = renderMultiDrawInstances;
  9462. }
  9463. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  9464. let maxAnisotropy;
  9465. function getMaxAnisotropy() {
  9466. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9467. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9468. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9469. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9470. } else {
  9471. maxAnisotropy = 0;
  9472. }
  9473. return maxAnisotropy;
  9474. }
  9475. function textureFormatReadable( textureFormat ) {
  9476. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  9477. return false;
  9478. }
  9479. return true;
  9480. }
  9481. function textureTypeReadable( textureType ) {
  9482. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  9483. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  9484. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  9485. return false;
  9486. }
  9487. return true;
  9488. }
  9489. function getMaxPrecision( precision ) {
  9490. if ( precision === 'highp' ) {
  9491. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9492. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9493. return 'highp';
  9494. }
  9495. precision = 'mediump';
  9496. }
  9497. if ( precision === 'mediump' ) {
  9498. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9499. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9500. return 'mediump';
  9501. }
  9502. }
  9503. return 'lowp';
  9504. }
  9505. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9506. const maxPrecision = getMaxPrecision( precision );
  9507. if ( maxPrecision !== precision ) {
  9508. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9509. precision = maxPrecision;
  9510. }
  9511. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9512. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9513. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9514. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9515. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9516. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9517. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9518. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9519. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9520. const vertexTextures = maxVertexTextures > 0;
  9521. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  9522. return {
  9523. isWebGL2: true, // keeping this for backwards compatibility
  9524. getMaxAnisotropy: getMaxAnisotropy,
  9525. getMaxPrecision: getMaxPrecision,
  9526. textureFormatReadable: textureFormatReadable,
  9527. textureTypeReadable: textureTypeReadable,
  9528. precision: precision,
  9529. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9530. maxTextures: maxTextures,
  9531. maxVertexTextures: maxVertexTextures,
  9532. maxTextureSize: maxTextureSize,
  9533. maxCubemapSize: maxCubemapSize,
  9534. maxAttributes: maxAttributes,
  9535. maxVertexUniforms: maxVertexUniforms,
  9536. maxVaryings: maxVaryings,
  9537. maxFragmentUniforms: maxFragmentUniforms,
  9538. vertexTextures: vertexTextures,
  9539. maxSamples: maxSamples
  9540. };
  9541. }
  9542. function WebGLClipping( properties ) {
  9543. const scope = this;
  9544. let globalState = null,
  9545. numGlobalPlanes = 0,
  9546. localClippingEnabled = false,
  9547. renderingShadows = false;
  9548. const plane = new Plane(),
  9549. viewNormalMatrix = new Matrix3(),
  9550. uniform = { value: null, needsUpdate: false };
  9551. this.uniform = uniform;
  9552. this.numPlanes = 0;
  9553. this.numIntersection = 0;
  9554. this.init = function ( planes, enableLocalClipping ) {
  9555. const enabled =
  9556. planes.length !== 0 ||
  9557. enableLocalClipping ||
  9558. // enable state of previous frame - the clipping code has to
  9559. // run another frame in order to reset the state:
  9560. numGlobalPlanes !== 0 ||
  9561. localClippingEnabled;
  9562. localClippingEnabled = enableLocalClipping;
  9563. numGlobalPlanes = planes.length;
  9564. return enabled;
  9565. };
  9566. this.beginShadows = function () {
  9567. renderingShadows = true;
  9568. projectPlanes( null );
  9569. };
  9570. this.endShadows = function () {
  9571. renderingShadows = false;
  9572. };
  9573. this.setGlobalState = function ( planes, camera ) {
  9574. globalState = projectPlanes( planes, camera, 0 );
  9575. };
  9576. this.setState = function ( material, camera, useCache ) {
  9577. const planes = material.clippingPlanes,
  9578. clipIntersection = material.clipIntersection,
  9579. clipShadows = material.clipShadows;
  9580. const materialProperties = properties.get( material );
  9581. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9582. // there's no local clipping
  9583. if ( renderingShadows ) {
  9584. // there's no global clipping
  9585. projectPlanes( null );
  9586. } else {
  9587. resetGlobalState();
  9588. }
  9589. } else {
  9590. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9591. lGlobal = nGlobal * 4;
  9592. let dstArray = materialProperties.clippingState || null;
  9593. uniform.value = dstArray; // ensure unique state
  9594. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9595. for ( let i = 0; i !== lGlobal; ++ i ) {
  9596. dstArray[ i ] = globalState[ i ];
  9597. }
  9598. materialProperties.clippingState = dstArray;
  9599. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9600. this.numPlanes += nGlobal;
  9601. }
  9602. };
  9603. function resetGlobalState() {
  9604. if ( uniform.value !== globalState ) {
  9605. uniform.value = globalState;
  9606. uniform.needsUpdate = numGlobalPlanes > 0;
  9607. }
  9608. scope.numPlanes = numGlobalPlanes;
  9609. scope.numIntersection = 0;
  9610. }
  9611. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9612. const nPlanes = planes !== null ? planes.length : 0;
  9613. let dstArray = null;
  9614. if ( nPlanes !== 0 ) {
  9615. dstArray = uniform.value;
  9616. if ( skipTransform !== true || dstArray === null ) {
  9617. const flatSize = dstOffset + nPlanes * 4,
  9618. viewMatrix = camera.matrixWorldInverse;
  9619. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9620. if ( dstArray === null || dstArray.length < flatSize ) {
  9621. dstArray = new Float32Array( flatSize );
  9622. }
  9623. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9624. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9625. plane.normal.toArray( dstArray, i4 );
  9626. dstArray[ i4 + 3 ] = plane.constant;
  9627. }
  9628. }
  9629. uniform.value = dstArray;
  9630. uniform.needsUpdate = true;
  9631. }
  9632. scope.numPlanes = nPlanes;
  9633. scope.numIntersection = 0;
  9634. return dstArray;
  9635. }
  9636. }
  9637. function WebGLCubeMaps( renderer ) {
  9638. let cubemaps = new WeakMap();
  9639. function mapTextureMapping( texture, mapping ) {
  9640. if ( mapping === EquirectangularReflectionMapping ) {
  9641. texture.mapping = CubeReflectionMapping;
  9642. } else if ( mapping === EquirectangularRefractionMapping ) {
  9643. texture.mapping = CubeRefractionMapping;
  9644. }
  9645. return texture;
  9646. }
  9647. function get( texture ) {
  9648. if ( texture && texture.isTexture ) {
  9649. const mapping = texture.mapping;
  9650. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9651. if ( cubemaps.has( texture ) ) {
  9652. const cubemap = cubemaps.get( texture ).texture;
  9653. return mapTextureMapping( cubemap, texture.mapping );
  9654. } else {
  9655. const image = texture.image;
  9656. if ( image && image.height > 0 ) {
  9657. const renderTarget = new WebGLCubeRenderTarget( image.height );
  9658. renderTarget.fromEquirectangularTexture( renderer, texture );
  9659. cubemaps.set( texture, renderTarget );
  9660. texture.addEventListener( 'dispose', onTextureDispose );
  9661. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9662. } else {
  9663. // image not yet ready. try the conversion next frame
  9664. return null;
  9665. }
  9666. }
  9667. }
  9668. }
  9669. return texture;
  9670. }
  9671. function onTextureDispose( event ) {
  9672. const texture = event.target;
  9673. texture.removeEventListener( 'dispose', onTextureDispose );
  9674. const cubemap = cubemaps.get( texture );
  9675. if ( cubemap !== undefined ) {
  9676. cubemaps.delete( texture );
  9677. cubemap.dispose();
  9678. }
  9679. }
  9680. function dispose() {
  9681. cubemaps = new WeakMap();
  9682. }
  9683. return {
  9684. get: get,
  9685. dispose: dispose
  9686. };
  9687. }
  9688. class OrthographicCamera extends Camera {
  9689. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9690. super();
  9691. this.isOrthographicCamera = true;
  9692. this.type = 'OrthographicCamera';
  9693. this.zoom = 1;
  9694. this.view = null;
  9695. this.left = left;
  9696. this.right = right;
  9697. this.top = top;
  9698. this.bottom = bottom;
  9699. this.near = near;
  9700. this.far = far;
  9701. this.updateProjectionMatrix();
  9702. }
  9703. copy( source, recursive ) {
  9704. super.copy( source, recursive );
  9705. this.left = source.left;
  9706. this.right = source.right;
  9707. this.top = source.top;
  9708. this.bottom = source.bottom;
  9709. this.near = source.near;
  9710. this.far = source.far;
  9711. this.zoom = source.zoom;
  9712. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9713. return this;
  9714. }
  9715. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9716. if ( this.view === null ) {
  9717. this.view = {
  9718. enabled: true,
  9719. fullWidth: 1,
  9720. fullHeight: 1,
  9721. offsetX: 0,
  9722. offsetY: 0,
  9723. width: 1,
  9724. height: 1
  9725. };
  9726. }
  9727. this.view.enabled = true;
  9728. this.view.fullWidth = fullWidth;
  9729. this.view.fullHeight = fullHeight;
  9730. this.view.offsetX = x;
  9731. this.view.offsetY = y;
  9732. this.view.width = width;
  9733. this.view.height = height;
  9734. this.updateProjectionMatrix();
  9735. }
  9736. clearViewOffset() {
  9737. if ( this.view !== null ) {
  9738. this.view.enabled = false;
  9739. }
  9740. this.updateProjectionMatrix();
  9741. }
  9742. updateProjectionMatrix() {
  9743. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9744. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9745. const cx = ( this.right + this.left ) / 2;
  9746. const cy = ( this.top + this.bottom ) / 2;
  9747. let left = cx - dx;
  9748. let right = cx + dx;
  9749. let top = cy + dy;
  9750. let bottom = cy - dy;
  9751. if ( this.view !== null && this.view.enabled ) {
  9752. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9753. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9754. left += scaleW * this.view.offsetX;
  9755. right = left + scaleW * this.view.width;
  9756. top -= scaleH * this.view.offsetY;
  9757. bottom = top - scaleH * this.view.height;
  9758. }
  9759. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9760. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9761. }
  9762. toJSON( meta ) {
  9763. const data = super.toJSON( meta );
  9764. data.object.zoom = this.zoom;
  9765. data.object.left = this.left;
  9766. data.object.right = this.right;
  9767. data.object.top = this.top;
  9768. data.object.bottom = this.bottom;
  9769. data.object.near = this.near;
  9770. data.object.far = this.far;
  9771. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9772. return data;
  9773. }
  9774. }
  9775. const LOD_MIN = 4;
  9776. // The standard deviations (radians) associated with the extra mips. These are
  9777. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9778. // geometric shadowing function. These sigma values squared must match the
  9779. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9780. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9781. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9782. // samples and exit early, but not recompile the shader.
  9783. const MAX_SAMPLES = 20;
  9784. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9785. const _clearColor = /*@__PURE__*/ new Color();
  9786. let _oldTarget = null;
  9787. let _oldActiveCubeFace = 0;
  9788. let _oldActiveMipmapLevel = 0;
  9789. let _oldXrEnabled = false;
  9790. // Golden Ratio
  9791. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9792. const INV_PHI = 1 / PHI;
  9793. // Vertices of a dodecahedron (except the opposites, which represent the
  9794. // same axis), used as axis directions evenly spread on a sphere.
  9795. const _axisDirections = [
  9796. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  9797. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9798. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9799. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9800. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9801. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9802. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9803. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9804. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9805. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  9806. /**
  9807. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9808. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9809. * blur to be quickly accessed based on material roughness. It is packed into a
  9810. * special CubeUV format that allows us to perform custom interpolation so that
  9811. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9812. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9813. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9814. * higher roughness levels. In this way we maintain resolution to smoothly
  9815. * interpolate diffuse lighting while limiting sampling computation.
  9816. *
  9817. * Paper: Fast, Accurate Image-Based Lighting
  9818. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9819. */
  9820. class PMREMGenerator {
  9821. constructor( renderer ) {
  9822. this._renderer = renderer;
  9823. this._pingPongRenderTarget = null;
  9824. this._lodMax = 0;
  9825. this._cubeSize = 0;
  9826. this._lodPlanes = [];
  9827. this._sizeLods = [];
  9828. this._sigmas = [];
  9829. this._blurMaterial = null;
  9830. this._cubemapMaterial = null;
  9831. this._equirectMaterial = null;
  9832. this._compileMaterial( this._blurMaterial );
  9833. }
  9834. /**
  9835. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9836. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9837. * in radians to be applied to the scene before PMREM generation. Optional near
  9838. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9839. * is placed at the origin).
  9840. */
  9841. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9842. _oldTarget = this._renderer.getRenderTarget();
  9843. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9844. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9845. _oldXrEnabled = this._renderer.xr.enabled;
  9846. this._renderer.xr.enabled = false;
  9847. this._setSize( 256 );
  9848. const cubeUVRenderTarget = this._allocateTargets();
  9849. cubeUVRenderTarget.depthBuffer = true;
  9850. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9851. if ( sigma > 0 ) {
  9852. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9853. }
  9854. this._applyPMREM( cubeUVRenderTarget );
  9855. this._cleanup( cubeUVRenderTarget );
  9856. return cubeUVRenderTarget;
  9857. }
  9858. /**
  9859. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9860. * or HDR. The ideal input image size is 1k (1024 x 512),
  9861. * as this matches best with the 256 x 256 cubemap output.
  9862. * The smallest supported equirectangular image size is 64 x 32.
  9863. */
  9864. fromEquirectangular( equirectangular, renderTarget = null ) {
  9865. return this._fromTexture( equirectangular, renderTarget );
  9866. }
  9867. /**
  9868. * Generates a PMREM from an cubemap texture, which can be either LDR
  9869. * or HDR. The ideal input cube size is 256 x 256,
  9870. * as this matches best with the 256 x 256 cubemap output.
  9871. * The smallest supported cube size is 16 x 16.
  9872. */
  9873. fromCubemap( cubemap, renderTarget = null ) {
  9874. return this._fromTexture( cubemap, renderTarget );
  9875. }
  9876. /**
  9877. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9878. * your texture's network fetch for increased concurrency.
  9879. */
  9880. compileCubemapShader() {
  9881. if ( this._cubemapMaterial === null ) {
  9882. this._cubemapMaterial = _getCubemapMaterial();
  9883. this._compileMaterial( this._cubemapMaterial );
  9884. }
  9885. }
  9886. /**
  9887. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9888. * your texture's network fetch for increased concurrency.
  9889. */
  9890. compileEquirectangularShader() {
  9891. if ( this._equirectMaterial === null ) {
  9892. this._equirectMaterial = _getEquirectMaterial();
  9893. this._compileMaterial( this._equirectMaterial );
  9894. }
  9895. }
  9896. /**
  9897. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9898. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9899. * one of them will cause any others to also become unusable.
  9900. */
  9901. dispose() {
  9902. this._dispose();
  9903. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9904. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9905. }
  9906. // private interface
  9907. _setSize( cubeSize ) {
  9908. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9909. this._cubeSize = Math.pow( 2, this._lodMax );
  9910. }
  9911. _dispose() {
  9912. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9913. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9914. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9915. this._lodPlanes[ i ].dispose();
  9916. }
  9917. }
  9918. _cleanup( outputTarget ) {
  9919. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  9920. this._renderer.xr.enabled = _oldXrEnabled;
  9921. outputTarget.scissorTest = false;
  9922. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9923. }
  9924. _fromTexture( texture, renderTarget ) {
  9925. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9926. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9927. } else { // Equirectangular
  9928. this._setSize( texture.image.width / 4 );
  9929. }
  9930. _oldTarget = this._renderer.getRenderTarget();
  9931. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9932. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9933. _oldXrEnabled = this._renderer.xr.enabled;
  9934. this._renderer.xr.enabled = false;
  9935. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9936. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9937. this._applyPMREM( cubeUVRenderTarget );
  9938. this._cleanup( cubeUVRenderTarget );
  9939. return cubeUVRenderTarget;
  9940. }
  9941. _allocateTargets() {
  9942. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9943. const height = 4 * this._cubeSize;
  9944. const params = {
  9945. magFilter: LinearFilter,
  9946. minFilter: LinearFilter,
  9947. generateMipmaps: false,
  9948. type: HalfFloatType,
  9949. format: RGBAFormat,
  9950. colorSpace: LinearSRGBColorSpace,
  9951. depthBuffer: false
  9952. };
  9953. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9954. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9955. if ( this._pingPongRenderTarget !== null ) {
  9956. this._dispose();
  9957. }
  9958. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9959. const { _lodMax } = this;
  9960. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9961. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9962. }
  9963. return cubeUVRenderTarget;
  9964. }
  9965. _compileMaterial( material ) {
  9966. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9967. this._renderer.compile( tmpMesh, _flatCamera );
  9968. }
  9969. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9970. const fov = 90;
  9971. const aspect = 1;
  9972. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9973. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9974. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9975. const renderer = this._renderer;
  9976. const originalAutoClear = renderer.autoClear;
  9977. const toneMapping = renderer.toneMapping;
  9978. renderer.getClearColor( _clearColor );
  9979. renderer.toneMapping = NoToneMapping;
  9980. renderer.autoClear = false;
  9981. const backgroundMaterial = new MeshBasicMaterial( {
  9982. name: 'PMREM.Background',
  9983. side: BackSide,
  9984. depthWrite: false,
  9985. depthTest: false,
  9986. } );
  9987. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9988. let useSolidColor = false;
  9989. const background = scene.background;
  9990. if ( background ) {
  9991. if ( background.isColor ) {
  9992. backgroundMaterial.color.copy( background );
  9993. scene.background = null;
  9994. useSolidColor = true;
  9995. }
  9996. } else {
  9997. backgroundMaterial.color.copy( _clearColor );
  9998. useSolidColor = true;
  9999. }
  10000. for ( let i = 0; i < 6; i ++ ) {
  10001. const col = i % 3;
  10002. if ( col === 0 ) {
  10003. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10004. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  10005. } else if ( col === 1 ) {
  10006. cubeCamera.up.set( 0, 0, upSign[ i ] );
  10007. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  10008. } else {
  10009. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10010. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  10011. }
  10012. const size = this._cubeSize;
  10013. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  10014. renderer.setRenderTarget( cubeUVRenderTarget );
  10015. if ( useSolidColor ) {
  10016. renderer.render( backgroundBox, cubeCamera );
  10017. }
  10018. renderer.render( scene, cubeCamera );
  10019. }
  10020. backgroundBox.geometry.dispose();
  10021. backgroundBox.material.dispose();
  10022. renderer.toneMapping = toneMapping;
  10023. renderer.autoClear = originalAutoClear;
  10024. scene.background = background;
  10025. }
  10026. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  10027. const renderer = this._renderer;
  10028. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  10029. if ( isCubeTexture ) {
  10030. if ( this._cubemapMaterial === null ) {
  10031. this._cubemapMaterial = _getCubemapMaterial();
  10032. }
  10033. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  10034. } else {
  10035. if ( this._equirectMaterial === null ) {
  10036. this._equirectMaterial = _getEquirectMaterial();
  10037. }
  10038. }
  10039. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  10040. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  10041. const uniforms = material.uniforms;
  10042. uniforms[ 'envMap' ].value = texture;
  10043. const size = this._cubeSize;
  10044. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  10045. renderer.setRenderTarget( cubeUVRenderTarget );
  10046. renderer.render( mesh, _flatCamera );
  10047. }
  10048. _applyPMREM( cubeUVRenderTarget ) {
  10049. const renderer = this._renderer;
  10050. const autoClear = renderer.autoClear;
  10051. renderer.autoClear = false;
  10052. const n = this._lodPlanes.length;
  10053. for ( let i = 1; i < n; i ++ ) {
  10054. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  10055. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  10056. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  10057. }
  10058. renderer.autoClear = autoClear;
  10059. }
  10060. /**
  10061. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  10062. * vertically and horizontally, but this breaks down on a cube. Here we apply
  10063. * the blur latitudinally (around the poles), and then longitudinally (towards
  10064. * the poles) to approximate the orthogonally-separable blur. It is least
  10065. * accurate at the poles, but still does a decent job.
  10066. */
  10067. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  10068. const pingPongRenderTarget = this._pingPongRenderTarget;
  10069. this._halfBlur(
  10070. cubeUVRenderTarget,
  10071. pingPongRenderTarget,
  10072. lodIn,
  10073. lodOut,
  10074. sigma,
  10075. 'latitudinal',
  10076. poleAxis );
  10077. this._halfBlur(
  10078. pingPongRenderTarget,
  10079. cubeUVRenderTarget,
  10080. lodOut,
  10081. lodOut,
  10082. sigma,
  10083. 'longitudinal',
  10084. poleAxis );
  10085. }
  10086. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10087. const renderer = this._renderer;
  10088. const blurMaterial = this._blurMaterial;
  10089. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10090. console.error(
  10091. 'blur direction must be either latitudinal or longitudinal!' );
  10092. }
  10093. // Number of standard deviations at which to cut off the discrete approximation.
  10094. const STANDARD_DEVIATIONS = 3;
  10095. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  10096. const blurUniforms = blurMaterial.uniforms;
  10097. const pixels = this._sizeLods[ lodIn ] - 1;
  10098. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10099. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10100. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10101. if ( samples > MAX_SAMPLES ) {
  10102. console.warn( `sigmaRadians, ${
  10103. sigmaRadians}, is too large and will clip, as it requested ${
  10104. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10105. }
  10106. const weights = [];
  10107. let sum = 0;
  10108. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10109. const x = i / sigmaPixels;
  10110. const weight = Math.exp( - x * x / 2 );
  10111. weights.push( weight );
  10112. if ( i === 0 ) {
  10113. sum += weight;
  10114. } else if ( i < samples ) {
  10115. sum += 2 * weight;
  10116. }
  10117. }
  10118. for ( let i = 0; i < weights.length; i ++ ) {
  10119. weights[ i ] = weights[ i ] / sum;
  10120. }
  10121. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10122. blurUniforms[ 'samples' ].value = samples;
  10123. blurUniforms[ 'weights' ].value = weights;
  10124. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10125. if ( poleAxis ) {
  10126. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10127. }
  10128. const { _lodMax } = this;
  10129. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10130. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10131. const outputSize = this._sizeLods[ lodOut ];
  10132. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10133. const y = 4 * ( this._cubeSize - outputSize );
  10134. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10135. renderer.setRenderTarget( targetOut );
  10136. renderer.render( blurMesh, _flatCamera );
  10137. }
  10138. }
  10139. function _createPlanes( lodMax ) {
  10140. const lodPlanes = [];
  10141. const sizeLods = [];
  10142. const sigmas = [];
  10143. let lod = lodMax;
  10144. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10145. for ( let i = 0; i < totalLods; i ++ ) {
  10146. const sizeLod = Math.pow( 2, lod );
  10147. sizeLods.push( sizeLod );
  10148. let sigma = 1.0 / sizeLod;
  10149. if ( i > lodMax - LOD_MIN ) {
  10150. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10151. } else if ( i === 0 ) {
  10152. sigma = 0;
  10153. }
  10154. sigmas.push( sigma );
  10155. const texelSize = 1.0 / ( sizeLod - 2 );
  10156. const min = - texelSize;
  10157. const max = 1 + texelSize;
  10158. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10159. const cubeFaces = 6;
  10160. const vertices = 6;
  10161. const positionSize = 3;
  10162. const uvSize = 2;
  10163. const faceIndexSize = 1;
  10164. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10165. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10166. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10167. for ( let face = 0; face < cubeFaces; face ++ ) {
  10168. const x = ( face % 3 ) * 2 / 3 - 1;
  10169. const y = face > 2 ? 0 : - 1;
  10170. const coordinates = [
  10171. x, y, 0,
  10172. x + 2 / 3, y, 0,
  10173. x + 2 / 3, y + 1, 0,
  10174. x, y, 0,
  10175. x + 2 / 3, y + 1, 0,
  10176. x, y + 1, 0
  10177. ];
  10178. position.set( coordinates, positionSize * vertices * face );
  10179. uv.set( uv1, uvSize * vertices * face );
  10180. const fill = [ face, face, face, face, face, face ];
  10181. faceIndex.set( fill, faceIndexSize * vertices * face );
  10182. }
  10183. const planes = new BufferGeometry();
  10184. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10185. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10186. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10187. lodPlanes.push( planes );
  10188. if ( lod > LOD_MIN ) {
  10189. lod --;
  10190. }
  10191. }
  10192. return { lodPlanes, sizeLods, sigmas };
  10193. }
  10194. function _createRenderTarget( width, height, params ) {
  10195. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10196. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10197. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10198. cubeUVRenderTarget.scissorTest = true;
  10199. return cubeUVRenderTarget;
  10200. }
  10201. function _setViewport( target, x, y, width, height ) {
  10202. target.viewport.set( x, y, width, height );
  10203. target.scissor.set( x, y, width, height );
  10204. }
  10205. function _getBlurShader( lodMax, width, height ) {
  10206. const weights = new Float32Array( MAX_SAMPLES );
  10207. const poleAxis = new Vector3( 0, 1, 0 );
  10208. const shaderMaterial = new ShaderMaterial( {
  10209. name: 'SphericalGaussianBlur',
  10210. defines: {
  10211. 'n': MAX_SAMPLES,
  10212. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10213. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10214. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10215. },
  10216. uniforms: {
  10217. 'envMap': { value: null },
  10218. 'samples': { value: 1 },
  10219. 'weights': { value: weights },
  10220. 'latitudinal': { value: false },
  10221. 'dTheta': { value: 0 },
  10222. 'mipInt': { value: 0 },
  10223. 'poleAxis': { value: poleAxis }
  10224. },
  10225. vertexShader: _getCommonVertexShader(),
  10226. fragmentShader: /* glsl */`
  10227. precision mediump float;
  10228. precision mediump int;
  10229. varying vec3 vOutputDirection;
  10230. uniform sampler2D envMap;
  10231. uniform int samples;
  10232. uniform float weights[ n ];
  10233. uniform bool latitudinal;
  10234. uniform float dTheta;
  10235. uniform float mipInt;
  10236. uniform vec3 poleAxis;
  10237. #define ENVMAP_TYPE_CUBE_UV
  10238. #include <cube_uv_reflection_fragment>
  10239. vec3 getSample( float theta, vec3 axis ) {
  10240. float cosTheta = cos( theta );
  10241. // Rodrigues' axis-angle rotation
  10242. vec3 sampleDirection = vOutputDirection * cosTheta
  10243. + cross( axis, vOutputDirection ) * sin( theta )
  10244. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10245. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10246. }
  10247. void main() {
  10248. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10249. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10250. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10251. }
  10252. axis = normalize( axis );
  10253. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10254. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10255. for ( int i = 1; i < n; i++ ) {
  10256. if ( i >= samples ) {
  10257. break;
  10258. }
  10259. float theta = dTheta * float( i );
  10260. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10261. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10262. }
  10263. }
  10264. `,
  10265. blending: NoBlending,
  10266. depthTest: false,
  10267. depthWrite: false
  10268. } );
  10269. return shaderMaterial;
  10270. }
  10271. function _getEquirectMaterial() {
  10272. return new ShaderMaterial( {
  10273. name: 'EquirectangularToCubeUV',
  10274. uniforms: {
  10275. 'envMap': { value: null }
  10276. },
  10277. vertexShader: _getCommonVertexShader(),
  10278. fragmentShader: /* glsl */`
  10279. precision mediump float;
  10280. precision mediump int;
  10281. varying vec3 vOutputDirection;
  10282. uniform sampler2D envMap;
  10283. #include <common>
  10284. void main() {
  10285. vec3 outputDirection = normalize( vOutputDirection );
  10286. vec2 uv = equirectUv( outputDirection );
  10287. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10288. }
  10289. `,
  10290. blending: NoBlending,
  10291. depthTest: false,
  10292. depthWrite: false
  10293. } );
  10294. }
  10295. function _getCubemapMaterial() {
  10296. return new ShaderMaterial( {
  10297. name: 'CubemapToCubeUV',
  10298. uniforms: {
  10299. 'envMap': { value: null },
  10300. 'flipEnvMap': { value: - 1 }
  10301. },
  10302. vertexShader: _getCommonVertexShader(),
  10303. fragmentShader: /* glsl */`
  10304. precision mediump float;
  10305. precision mediump int;
  10306. uniform float flipEnvMap;
  10307. varying vec3 vOutputDirection;
  10308. uniform samplerCube envMap;
  10309. void main() {
  10310. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10311. }
  10312. `,
  10313. blending: NoBlending,
  10314. depthTest: false,
  10315. depthWrite: false
  10316. } );
  10317. }
  10318. function _getCommonVertexShader() {
  10319. return /* glsl */`
  10320. precision mediump float;
  10321. precision mediump int;
  10322. attribute float faceIndex;
  10323. varying vec3 vOutputDirection;
  10324. // RH coordinate system; PMREM face-indexing convention
  10325. vec3 getDirection( vec2 uv, float face ) {
  10326. uv = 2.0 * uv - 1.0;
  10327. vec3 direction = vec3( uv, 1.0 );
  10328. if ( face == 0.0 ) {
  10329. direction = direction.zyx; // ( 1, v, u ) pos x
  10330. } else if ( face == 1.0 ) {
  10331. direction = direction.xzy;
  10332. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10333. } else if ( face == 2.0 ) {
  10334. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10335. } else if ( face == 3.0 ) {
  10336. direction = direction.zyx;
  10337. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10338. } else if ( face == 4.0 ) {
  10339. direction = direction.xzy;
  10340. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10341. } else if ( face == 5.0 ) {
  10342. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10343. }
  10344. return direction;
  10345. }
  10346. void main() {
  10347. vOutputDirection = getDirection( uv, faceIndex );
  10348. gl_Position = vec4( position, 1.0 );
  10349. }
  10350. `;
  10351. }
  10352. function WebGLCubeUVMaps( renderer ) {
  10353. let cubeUVmaps = new WeakMap();
  10354. let pmremGenerator = null;
  10355. function get( texture ) {
  10356. if ( texture && texture.isTexture ) {
  10357. const mapping = texture.mapping;
  10358. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10359. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10360. // equirect/cube map to cubeUV conversion
  10361. if ( isEquirectMap || isCubeMap ) {
  10362. let renderTarget = cubeUVmaps.get( texture );
  10363. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  10364. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  10365. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10366. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10367. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10368. cubeUVmaps.set( texture, renderTarget );
  10369. return renderTarget.texture;
  10370. } else {
  10371. if ( renderTarget !== undefined ) {
  10372. return renderTarget.texture;
  10373. } else {
  10374. const image = texture.image;
  10375. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10376. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10377. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10378. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10379. cubeUVmaps.set( texture, renderTarget );
  10380. texture.addEventListener( 'dispose', onTextureDispose );
  10381. return renderTarget.texture;
  10382. } else {
  10383. // image not yet ready. try the conversion next frame
  10384. return null;
  10385. }
  10386. }
  10387. }
  10388. }
  10389. }
  10390. return texture;
  10391. }
  10392. function isCubeTextureComplete( image ) {
  10393. let count = 0;
  10394. const length = 6;
  10395. for ( let i = 0; i < length; i ++ ) {
  10396. if ( image[ i ] !== undefined ) count ++;
  10397. }
  10398. return count === length;
  10399. }
  10400. function onTextureDispose( event ) {
  10401. const texture = event.target;
  10402. texture.removeEventListener( 'dispose', onTextureDispose );
  10403. const cubemapUV = cubeUVmaps.get( texture );
  10404. if ( cubemapUV !== undefined ) {
  10405. cubeUVmaps.delete( texture );
  10406. cubemapUV.dispose();
  10407. }
  10408. }
  10409. function dispose() {
  10410. cubeUVmaps = new WeakMap();
  10411. if ( pmremGenerator !== null ) {
  10412. pmremGenerator.dispose();
  10413. pmremGenerator = null;
  10414. }
  10415. }
  10416. return {
  10417. get: get,
  10418. dispose: dispose
  10419. };
  10420. }
  10421. function WebGLExtensions( gl ) {
  10422. const extensions = {};
  10423. function getExtension( name ) {
  10424. if ( extensions[ name ] !== undefined ) {
  10425. return extensions[ name ];
  10426. }
  10427. let extension;
  10428. switch ( name ) {
  10429. case 'WEBGL_depth_texture':
  10430. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10431. break;
  10432. case 'EXT_texture_filter_anisotropic':
  10433. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10434. break;
  10435. case 'WEBGL_compressed_texture_s3tc':
  10436. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10437. break;
  10438. case 'WEBGL_compressed_texture_pvrtc':
  10439. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10440. break;
  10441. default:
  10442. extension = gl.getExtension( name );
  10443. }
  10444. extensions[ name ] = extension;
  10445. return extension;
  10446. }
  10447. return {
  10448. has: function ( name ) {
  10449. return getExtension( name ) !== null;
  10450. },
  10451. init: function () {
  10452. getExtension( 'EXT_color_buffer_float' );
  10453. getExtension( 'WEBGL_clip_cull_distance' );
  10454. getExtension( 'OES_texture_float_linear' );
  10455. getExtension( 'EXT_color_buffer_half_float' );
  10456. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10457. getExtension( 'WEBGL_render_shared_exponent' );
  10458. },
  10459. get: function ( name ) {
  10460. const extension = getExtension( name );
  10461. if ( extension === null ) {
  10462. warnOnce( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10463. }
  10464. return extension;
  10465. }
  10466. };
  10467. }
  10468. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10469. const geometries = {};
  10470. const wireframeAttributes = new WeakMap();
  10471. function onGeometryDispose( event ) {
  10472. const geometry = event.target;
  10473. if ( geometry.index !== null ) {
  10474. attributes.remove( geometry.index );
  10475. }
  10476. for ( const name in geometry.attributes ) {
  10477. attributes.remove( geometry.attributes[ name ] );
  10478. }
  10479. for ( const name in geometry.morphAttributes ) {
  10480. const array = geometry.morphAttributes[ name ];
  10481. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10482. attributes.remove( array[ i ] );
  10483. }
  10484. }
  10485. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10486. delete geometries[ geometry.id ];
  10487. const attribute = wireframeAttributes.get( geometry );
  10488. if ( attribute ) {
  10489. attributes.remove( attribute );
  10490. wireframeAttributes.delete( geometry );
  10491. }
  10492. bindingStates.releaseStatesOfGeometry( geometry );
  10493. if ( geometry.isInstancedBufferGeometry === true ) {
  10494. delete geometry._maxInstanceCount;
  10495. }
  10496. //
  10497. info.memory.geometries --;
  10498. }
  10499. function get( object, geometry ) {
  10500. if ( geometries[ geometry.id ] === true ) return geometry;
  10501. geometry.addEventListener( 'dispose', onGeometryDispose );
  10502. geometries[ geometry.id ] = true;
  10503. info.memory.geometries ++;
  10504. return geometry;
  10505. }
  10506. function update( geometry ) {
  10507. const geometryAttributes = geometry.attributes;
  10508. // Updating index buffer in VAO now. See WebGLBindingStates.
  10509. for ( const name in geometryAttributes ) {
  10510. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10511. }
  10512. // morph targets
  10513. const morphAttributes = geometry.morphAttributes;
  10514. for ( const name in morphAttributes ) {
  10515. const array = morphAttributes[ name ];
  10516. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10517. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10518. }
  10519. }
  10520. }
  10521. function updateWireframeAttribute( geometry ) {
  10522. const indices = [];
  10523. const geometryIndex = geometry.index;
  10524. const geometryPosition = geometry.attributes.position;
  10525. let version = 0;
  10526. if ( geometryIndex !== null ) {
  10527. const array = geometryIndex.array;
  10528. version = geometryIndex.version;
  10529. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10530. const a = array[ i + 0 ];
  10531. const b = array[ i + 1 ];
  10532. const c = array[ i + 2 ];
  10533. indices.push( a, b, b, c, c, a );
  10534. }
  10535. } else if ( geometryPosition !== undefined ) {
  10536. const array = geometryPosition.array;
  10537. version = geometryPosition.version;
  10538. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10539. const a = i + 0;
  10540. const b = i + 1;
  10541. const c = i + 2;
  10542. indices.push( a, b, b, c, c, a );
  10543. }
  10544. } else {
  10545. return;
  10546. }
  10547. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10548. attribute.version = version;
  10549. // Updating index buffer in VAO now. See WebGLBindingStates
  10550. //
  10551. const previousAttribute = wireframeAttributes.get( geometry );
  10552. if ( previousAttribute ) attributes.remove( previousAttribute );
  10553. //
  10554. wireframeAttributes.set( geometry, attribute );
  10555. }
  10556. function getWireframeAttribute( geometry ) {
  10557. const currentAttribute = wireframeAttributes.get( geometry );
  10558. if ( currentAttribute ) {
  10559. const geometryIndex = geometry.index;
  10560. if ( geometryIndex !== null ) {
  10561. // if the attribute is obsolete, create a new one
  10562. if ( currentAttribute.version < geometryIndex.version ) {
  10563. updateWireframeAttribute( geometry );
  10564. }
  10565. }
  10566. } else {
  10567. updateWireframeAttribute( geometry );
  10568. }
  10569. return wireframeAttributes.get( geometry );
  10570. }
  10571. return {
  10572. get: get,
  10573. update: update,
  10574. getWireframeAttribute: getWireframeAttribute
  10575. };
  10576. }
  10577. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  10578. let mode;
  10579. function setMode( value ) {
  10580. mode = value;
  10581. }
  10582. let type, bytesPerElement;
  10583. function setIndex( value ) {
  10584. type = value.type;
  10585. bytesPerElement = value.bytesPerElement;
  10586. }
  10587. function render( start, count ) {
  10588. gl.drawElements( mode, count, type, start * bytesPerElement );
  10589. info.update( count, mode, 1 );
  10590. }
  10591. function renderInstances( start, count, primcount ) {
  10592. if ( primcount === 0 ) return;
  10593. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  10594. info.update( count, mode, primcount );
  10595. }
  10596. function renderMultiDraw( starts, counts, drawCount ) {
  10597. if ( drawCount === 0 ) return;
  10598. const extension = extensions.get( 'WEBGL_multi_draw' );
  10599. if ( extension === null ) {
  10600. for ( let i = 0; i < drawCount; i ++ ) {
  10601. this.render( starts[ i ] / bytesPerElement, counts[ i ] );
  10602. }
  10603. } else {
  10604. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  10605. let elementCount = 0;
  10606. for ( let i = 0; i < drawCount; i ++ ) {
  10607. elementCount += counts[ i ];
  10608. }
  10609. info.update( elementCount, mode, 1 );
  10610. }
  10611. }
  10612. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  10613. if ( drawCount === 0 ) return;
  10614. const extension = extensions.get( 'WEBGL_multi_draw' );
  10615. if ( extension === null ) {
  10616. for ( let i = 0; i < starts.length; i ++ ) {
  10617. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  10618. }
  10619. } else {
  10620. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  10621. let elementCount = 0;
  10622. for ( let i = 0; i < drawCount; i ++ ) {
  10623. elementCount += counts[ i ];
  10624. }
  10625. for ( let i = 0; i < primcount.length; i ++ ) {
  10626. info.update( elementCount, mode, primcount[ i ] );
  10627. }
  10628. }
  10629. }
  10630. //
  10631. this.setMode = setMode;
  10632. this.setIndex = setIndex;
  10633. this.render = render;
  10634. this.renderInstances = renderInstances;
  10635. this.renderMultiDraw = renderMultiDraw;
  10636. this.renderMultiDrawInstances = renderMultiDrawInstances;
  10637. }
  10638. function WebGLInfo( gl ) {
  10639. const memory = {
  10640. geometries: 0,
  10641. textures: 0
  10642. };
  10643. const render = {
  10644. frame: 0,
  10645. calls: 0,
  10646. triangles: 0,
  10647. points: 0,
  10648. lines: 0
  10649. };
  10650. function update( count, mode, instanceCount ) {
  10651. render.calls ++;
  10652. switch ( mode ) {
  10653. case gl.TRIANGLES:
  10654. render.triangles += instanceCount * ( count / 3 );
  10655. break;
  10656. case gl.LINES:
  10657. render.lines += instanceCount * ( count / 2 );
  10658. break;
  10659. case gl.LINE_STRIP:
  10660. render.lines += instanceCount * ( count - 1 );
  10661. break;
  10662. case gl.LINE_LOOP:
  10663. render.lines += instanceCount * count;
  10664. break;
  10665. case gl.POINTS:
  10666. render.points += instanceCount * count;
  10667. break;
  10668. default:
  10669. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10670. break;
  10671. }
  10672. }
  10673. function reset() {
  10674. render.calls = 0;
  10675. render.triangles = 0;
  10676. render.points = 0;
  10677. render.lines = 0;
  10678. }
  10679. return {
  10680. memory: memory,
  10681. render: render,
  10682. programs: null,
  10683. autoReset: true,
  10684. reset: reset,
  10685. update: update
  10686. };
  10687. }
  10688. function WebGLMorphtargets( gl, capabilities, textures ) {
  10689. const morphTextures = new WeakMap();
  10690. const morph = new Vector4();
  10691. function update( object, geometry, program ) {
  10692. const objectInfluences = object.morphTargetInfluences;
  10693. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  10694. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10695. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10696. let entry = morphTextures.get( geometry );
  10697. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10698. if ( entry !== undefined ) entry.texture.dispose();
  10699. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10700. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10701. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10702. const morphTargets = geometry.morphAttributes.position || [];
  10703. const morphNormals = geometry.morphAttributes.normal || [];
  10704. const morphColors = geometry.morphAttributes.color || [];
  10705. let vertexDataCount = 0;
  10706. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10707. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10708. if ( hasMorphColors === true ) vertexDataCount = 3;
  10709. let width = geometry.attributes.position.count * vertexDataCount;
  10710. let height = 1;
  10711. if ( width > capabilities.maxTextureSize ) {
  10712. height = Math.ceil( width / capabilities.maxTextureSize );
  10713. width = capabilities.maxTextureSize;
  10714. }
  10715. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10716. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10717. texture.type = FloatType;
  10718. texture.needsUpdate = true;
  10719. // fill buffer
  10720. const vertexDataStride = vertexDataCount * 4;
  10721. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10722. const morphTarget = morphTargets[ i ];
  10723. const morphNormal = morphNormals[ i ];
  10724. const morphColor = morphColors[ i ];
  10725. const offset = width * height * 4 * i;
  10726. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10727. const stride = j * vertexDataStride;
  10728. if ( hasMorphPosition === true ) {
  10729. morph.fromBufferAttribute( morphTarget, j );
  10730. buffer[ offset + stride + 0 ] = morph.x;
  10731. buffer[ offset + stride + 1 ] = morph.y;
  10732. buffer[ offset + stride + 2 ] = morph.z;
  10733. buffer[ offset + stride + 3 ] = 0;
  10734. }
  10735. if ( hasMorphNormals === true ) {
  10736. morph.fromBufferAttribute( morphNormal, j );
  10737. buffer[ offset + stride + 4 ] = morph.x;
  10738. buffer[ offset + stride + 5 ] = morph.y;
  10739. buffer[ offset + stride + 6 ] = morph.z;
  10740. buffer[ offset + stride + 7 ] = 0;
  10741. }
  10742. if ( hasMorphColors === true ) {
  10743. morph.fromBufferAttribute( morphColor, j );
  10744. buffer[ offset + stride + 8 ] = morph.x;
  10745. buffer[ offset + stride + 9 ] = morph.y;
  10746. buffer[ offset + stride + 10 ] = morph.z;
  10747. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10748. }
  10749. }
  10750. }
  10751. entry = {
  10752. count: morphTargetsCount,
  10753. texture: texture,
  10754. size: new Vector2( width, height )
  10755. };
  10756. morphTextures.set( geometry, entry );
  10757. function disposeTexture() {
  10758. texture.dispose();
  10759. morphTextures.delete( geometry );
  10760. geometry.removeEventListener( 'dispose', disposeTexture );
  10761. }
  10762. geometry.addEventListener( 'dispose', disposeTexture );
  10763. }
  10764. //
  10765. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  10766. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  10767. } else {
  10768. let morphInfluencesSum = 0;
  10769. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10770. morphInfluencesSum += objectInfluences[ i ];
  10771. }
  10772. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10773. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10774. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10775. }
  10776. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10777. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10778. }
  10779. return {
  10780. update: update
  10781. };
  10782. }
  10783. function WebGLObjects( gl, geometries, attributes, info ) {
  10784. let updateMap = new WeakMap();
  10785. function update( object ) {
  10786. const frame = info.render.frame;
  10787. const geometry = object.geometry;
  10788. const buffergeometry = geometries.get( object, geometry );
  10789. // Update once per frame
  10790. if ( updateMap.get( buffergeometry ) !== frame ) {
  10791. geometries.update( buffergeometry );
  10792. updateMap.set( buffergeometry, frame );
  10793. }
  10794. if ( object.isInstancedMesh ) {
  10795. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10796. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10797. }
  10798. if ( updateMap.get( object ) !== frame ) {
  10799. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10800. if ( object.instanceColor !== null ) {
  10801. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10802. }
  10803. updateMap.set( object, frame );
  10804. }
  10805. }
  10806. if ( object.isSkinnedMesh ) {
  10807. const skeleton = object.skeleton;
  10808. if ( updateMap.get( skeleton ) !== frame ) {
  10809. skeleton.update();
  10810. updateMap.set( skeleton, frame );
  10811. }
  10812. }
  10813. return buffergeometry;
  10814. }
  10815. function dispose() {
  10816. updateMap = new WeakMap();
  10817. }
  10818. function onInstancedMeshDispose( event ) {
  10819. const instancedMesh = event.target;
  10820. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10821. attributes.remove( instancedMesh.instanceMatrix );
  10822. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10823. }
  10824. return {
  10825. update: update,
  10826. dispose: dispose
  10827. };
  10828. }
  10829. class DepthTexture extends Texture {
  10830. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10831. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10832. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10833. }
  10834. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10835. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10836. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10837. this.isDepthTexture = true;
  10838. this.image = { width: width, height: height };
  10839. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10840. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10841. this.flipY = false;
  10842. this.generateMipmaps = false;
  10843. this.compareFunction = null;
  10844. }
  10845. copy( source ) {
  10846. super.copy( source );
  10847. this.compareFunction = source.compareFunction;
  10848. return this;
  10849. }
  10850. toJSON( meta ) {
  10851. const data = super.toJSON( meta );
  10852. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10853. return data;
  10854. }
  10855. }
  10856. /**
  10857. * Uniforms of a program.
  10858. * Those form a tree structure with a special top-level container for the root,
  10859. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10860. *
  10861. *
  10862. * Properties of inner nodes including the top-level container:
  10863. *
  10864. * .seq - array of nested uniforms
  10865. * .map - nested uniforms by name
  10866. *
  10867. *
  10868. * Methods of all nodes except the top-level container:
  10869. *
  10870. * .setValue( gl, value, [textures] )
  10871. *
  10872. * uploads a uniform value(s)
  10873. * the 'textures' parameter is needed for sampler uniforms
  10874. *
  10875. *
  10876. * Static methods of the top-level container (textures factorizations):
  10877. *
  10878. * .upload( gl, seq, values, textures )
  10879. *
  10880. * sets uniforms in 'seq' to 'values[id].value'
  10881. *
  10882. * .seqWithValue( seq, values ) : filteredSeq
  10883. *
  10884. * filters 'seq' entries with corresponding entry in values
  10885. *
  10886. *
  10887. * Methods of the top-level container (textures factorizations):
  10888. *
  10889. * .setValue( gl, name, value, textures )
  10890. *
  10891. * sets uniform with name 'name' to 'value'
  10892. *
  10893. * .setOptional( gl, obj, prop )
  10894. *
  10895. * like .set for an optional property of the object
  10896. *
  10897. */
  10898. const emptyTexture = /*@__PURE__*/ new Texture();
  10899. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  10900. emptyShadowTexture.compareFunction = LessEqualCompare;
  10901. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10902. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10903. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10904. // --- Utilities ---
  10905. // Array Caches (provide typed arrays for temporary by size)
  10906. const arrayCacheF32 = [];
  10907. const arrayCacheI32 = [];
  10908. // Float32Array caches used for uploading Matrix uniforms
  10909. const mat4array = new Float32Array( 16 );
  10910. const mat3array = new Float32Array( 9 );
  10911. const mat2array = new Float32Array( 4 );
  10912. // Flattening for arrays of vectors and matrices
  10913. function flatten( array, nBlocks, blockSize ) {
  10914. const firstElem = array[ 0 ];
  10915. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10916. // unoptimized: ! isNaN( firstElem )
  10917. // see http://jacksondunstan.com/articles/983
  10918. const n = nBlocks * blockSize;
  10919. let r = arrayCacheF32[ n ];
  10920. if ( r === undefined ) {
  10921. r = new Float32Array( n );
  10922. arrayCacheF32[ n ] = r;
  10923. }
  10924. if ( nBlocks !== 0 ) {
  10925. firstElem.toArray( r, 0 );
  10926. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10927. offset += blockSize;
  10928. array[ i ].toArray( r, offset );
  10929. }
  10930. }
  10931. return r;
  10932. }
  10933. function arraysEqual( a, b ) {
  10934. if ( a.length !== b.length ) return false;
  10935. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10936. if ( a[ i ] !== b[ i ] ) return false;
  10937. }
  10938. return true;
  10939. }
  10940. function copyArray( a, b ) {
  10941. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10942. a[ i ] = b[ i ];
  10943. }
  10944. }
  10945. // Texture unit allocation
  10946. function allocTexUnits( textures, n ) {
  10947. let r = arrayCacheI32[ n ];
  10948. if ( r === undefined ) {
  10949. r = new Int32Array( n );
  10950. arrayCacheI32[ n ] = r;
  10951. }
  10952. for ( let i = 0; i !== n; ++ i ) {
  10953. r[ i ] = textures.allocateTextureUnit();
  10954. }
  10955. return r;
  10956. }
  10957. // --- Setters ---
  10958. // Note: Defining these methods externally, because they come in a bunch
  10959. // and this way their names minify.
  10960. // Single scalar
  10961. function setValueV1f( gl, v ) {
  10962. const cache = this.cache;
  10963. if ( cache[ 0 ] === v ) return;
  10964. gl.uniform1f( this.addr, v );
  10965. cache[ 0 ] = v;
  10966. }
  10967. // Single float vector (from flat array or THREE.VectorN)
  10968. function setValueV2f( gl, v ) {
  10969. const cache = this.cache;
  10970. if ( v.x !== undefined ) {
  10971. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10972. gl.uniform2f( this.addr, v.x, v.y );
  10973. cache[ 0 ] = v.x;
  10974. cache[ 1 ] = v.y;
  10975. }
  10976. } else {
  10977. if ( arraysEqual( cache, v ) ) return;
  10978. gl.uniform2fv( this.addr, v );
  10979. copyArray( cache, v );
  10980. }
  10981. }
  10982. function setValueV3f( gl, v ) {
  10983. const cache = this.cache;
  10984. if ( v.x !== undefined ) {
  10985. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10986. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10987. cache[ 0 ] = v.x;
  10988. cache[ 1 ] = v.y;
  10989. cache[ 2 ] = v.z;
  10990. }
  10991. } else if ( v.r !== undefined ) {
  10992. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10993. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10994. cache[ 0 ] = v.r;
  10995. cache[ 1 ] = v.g;
  10996. cache[ 2 ] = v.b;
  10997. }
  10998. } else {
  10999. if ( arraysEqual( cache, v ) ) return;
  11000. gl.uniform3fv( this.addr, v );
  11001. copyArray( cache, v );
  11002. }
  11003. }
  11004. function setValueV4f( gl, v ) {
  11005. const cache = this.cache;
  11006. if ( v.x !== undefined ) {
  11007. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11008. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  11009. cache[ 0 ] = v.x;
  11010. cache[ 1 ] = v.y;
  11011. cache[ 2 ] = v.z;
  11012. cache[ 3 ] = v.w;
  11013. }
  11014. } else {
  11015. if ( arraysEqual( cache, v ) ) return;
  11016. gl.uniform4fv( this.addr, v );
  11017. copyArray( cache, v );
  11018. }
  11019. }
  11020. // Single matrix (from flat array or THREE.MatrixN)
  11021. function setValueM2( gl, v ) {
  11022. const cache = this.cache;
  11023. const elements = v.elements;
  11024. if ( elements === undefined ) {
  11025. if ( arraysEqual( cache, v ) ) return;
  11026. gl.uniformMatrix2fv( this.addr, false, v );
  11027. copyArray( cache, v );
  11028. } else {
  11029. if ( arraysEqual( cache, elements ) ) return;
  11030. mat2array.set( elements );
  11031. gl.uniformMatrix2fv( this.addr, false, mat2array );
  11032. copyArray( cache, elements );
  11033. }
  11034. }
  11035. function setValueM3( gl, v ) {
  11036. const cache = this.cache;
  11037. const elements = v.elements;
  11038. if ( elements === undefined ) {
  11039. if ( arraysEqual( cache, v ) ) return;
  11040. gl.uniformMatrix3fv( this.addr, false, v );
  11041. copyArray( cache, v );
  11042. } else {
  11043. if ( arraysEqual( cache, elements ) ) return;
  11044. mat3array.set( elements );
  11045. gl.uniformMatrix3fv( this.addr, false, mat3array );
  11046. copyArray( cache, elements );
  11047. }
  11048. }
  11049. function setValueM4( gl, v ) {
  11050. const cache = this.cache;
  11051. const elements = v.elements;
  11052. if ( elements === undefined ) {
  11053. if ( arraysEqual( cache, v ) ) return;
  11054. gl.uniformMatrix4fv( this.addr, false, v );
  11055. copyArray( cache, v );
  11056. } else {
  11057. if ( arraysEqual( cache, elements ) ) return;
  11058. mat4array.set( elements );
  11059. gl.uniformMatrix4fv( this.addr, false, mat4array );
  11060. copyArray( cache, elements );
  11061. }
  11062. }
  11063. // Single integer / boolean
  11064. function setValueV1i( gl, v ) {
  11065. const cache = this.cache;
  11066. if ( cache[ 0 ] === v ) return;
  11067. gl.uniform1i( this.addr, v );
  11068. cache[ 0 ] = v;
  11069. }
  11070. // Single integer / boolean vector (from flat array or THREE.VectorN)
  11071. function setValueV2i( gl, v ) {
  11072. const cache = this.cache;
  11073. if ( v.x !== undefined ) {
  11074. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11075. gl.uniform2i( this.addr, v.x, v.y );
  11076. cache[ 0 ] = v.x;
  11077. cache[ 1 ] = v.y;
  11078. }
  11079. } else {
  11080. if ( arraysEqual( cache, v ) ) return;
  11081. gl.uniform2iv( this.addr, v );
  11082. copyArray( cache, v );
  11083. }
  11084. }
  11085. function setValueV3i( gl, v ) {
  11086. const cache = this.cache;
  11087. if ( v.x !== undefined ) {
  11088. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11089. gl.uniform3i( this.addr, v.x, v.y, v.z );
  11090. cache[ 0 ] = v.x;
  11091. cache[ 1 ] = v.y;
  11092. cache[ 2 ] = v.z;
  11093. }
  11094. } else {
  11095. if ( arraysEqual( cache, v ) ) return;
  11096. gl.uniform3iv( this.addr, v );
  11097. copyArray( cache, v );
  11098. }
  11099. }
  11100. function setValueV4i( gl, v ) {
  11101. const cache = this.cache;
  11102. if ( v.x !== undefined ) {
  11103. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11104. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11105. cache[ 0 ] = v.x;
  11106. cache[ 1 ] = v.y;
  11107. cache[ 2 ] = v.z;
  11108. cache[ 3 ] = v.w;
  11109. }
  11110. } else {
  11111. if ( arraysEqual( cache, v ) ) return;
  11112. gl.uniform4iv( this.addr, v );
  11113. copyArray( cache, v );
  11114. }
  11115. }
  11116. // Single unsigned integer
  11117. function setValueV1ui( gl, v ) {
  11118. const cache = this.cache;
  11119. if ( cache[ 0 ] === v ) return;
  11120. gl.uniform1ui( this.addr, v );
  11121. cache[ 0 ] = v;
  11122. }
  11123. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11124. function setValueV2ui( gl, v ) {
  11125. const cache = this.cache;
  11126. if ( v.x !== undefined ) {
  11127. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11128. gl.uniform2ui( this.addr, v.x, v.y );
  11129. cache[ 0 ] = v.x;
  11130. cache[ 1 ] = v.y;
  11131. }
  11132. } else {
  11133. if ( arraysEqual( cache, v ) ) return;
  11134. gl.uniform2uiv( this.addr, v );
  11135. copyArray( cache, v );
  11136. }
  11137. }
  11138. function setValueV3ui( gl, v ) {
  11139. const cache = this.cache;
  11140. if ( v.x !== undefined ) {
  11141. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11142. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11143. cache[ 0 ] = v.x;
  11144. cache[ 1 ] = v.y;
  11145. cache[ 2 ] = v.z;
  11146. }
  11147. } else {
  11148. if ( arraysEqual( cache, v ) ) return;
  11149. gl.uniform3uiv( this.addr, v );
  11150. copyArray( cache, v );
  11151. }
  11152. }
  11153. function setValueV4ui( gl, v ) {
  11154. const cache = this.cache;
  11155. if ( v.x !== undefined ) {
  11156. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11157. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11158. cache[ 0 ] = v.x;
  11159. cache[ 1 ] = v.y;
  11160. cache[ 2 ] = v.z;
  11161. cache[ 3 ] = v.w;
  11162. }
  11163. } else {
  11164. if ( arraysEqual( cache, v ) ) return;
  11165. gl.uniform4uiv( this.addr, v );
  11166. copyArray( cache, v );
  11167. }
  11168. }
  11169. // Single texture (2D / Cube)
  11170. function setValueT1( gl, v, textures ) {
  11171. const cache = this.cache;
  11172. const unit = textures.allocateTextureUnit();
  11173. if ( cache[ 0 ] !== unit ) {
  11174. gl.uniform1i( this.addr, unit );
  11175. cache[ 0 ] = unit;
  11176. }
  11177. const emptyTexture2D = ( this.type === gl.SAMPLER_2D_SHADOW ) ? emptyShadowTexture : emptyTexture;
  11178. textures.setTexture2D( v || emptyTexture2D, unit );
  11179. }
  11180. function setValueT3D1( gl, v, textures ) {
  11181. const cache = this.cache;
  11182. const unit = textures.allocateTextureUnit();
  11183. if ( cache[ 0 ] !== unit ) {
  11184. gl.uniform1i( this.addr, unit );
  11185. cache[ 0 ] = unit;
  11186. }
  11187. textures.setTexture3D( v || empty3dTexture, unit );
  11188. }
  11189. function setValueT6( gl, v, textures ) {
  11190. const cache = this.cache;
  11191. const unit = textures.allocateTextureUnit();
  11192. if ( cache[ 0 ] !== unit ) {
  11193. gl.uniform1i( this.addr, unit );
  11194. cache[ 0 ] = unit;
  11195. }
  11196. textures.setTextureCube( v || emptyCubeTexture, unit );
  11197. }
  11198. function setValueT2DArray1( gl, v, textures ) {
  11199. const cache = this.cache;
  11200. const unit = textures.allocateTextureUnit();
  11201. if ( cache[ 0 ] !== unit ) {
  11202. gl.uniform1i( this.addr, unit );
  11203. cache[ 0 ] = unit;
  11204. }
  11205. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11206. }
  11207. // Helper to pick the right setter for the singular case
  11208. function getSingularSetter( type ) {
  11209. switch ( type ) {
  11210. case 0x1406: return setValueV1f; // FLOAT
  11211. case 0x8b50: return setValueV2f; // _VEC2
  11212. case 0x8b51: return setValueV3f; // _VEC3
  11213. case 0x8b52: return setValueV4f; // _VEC4
  11214. case 0x8b5a: return setValueM2; // _MAT2
  11215. case 0x8b5b: return setValueM3; // _MAT3
  11216. case 0x8b5c: return setValueM4; // _MAT4
  11217. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11218. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11219. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11220. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11221. case 0x1405: return setValueV1ui; // UINT
  11222. case 0x8dc6: return setValueV2ui; // _VEC2
  11223. case 0x8dc7: return setValueV3ui; // _VEC3
  11224. case 0x8dc8: return setValueV4ui; // _VEC4
  11225. case 0x8b5e: // SAMPLER_2D
  11226. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11227. case 0x8dca: // INT_SAMPLER_2D
  11228. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11229. case 0x8b62: // SAMPLER_2D_SHADOW
  11230. return setValueT1;
  11231. case 0x8b5f: // SAMPLER_3D
  11232. case 0x8dcb: // INT_SAMPLER_3D
  11233. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11234. return setValueT3D1;
  11235. case 0x8b60: // SAMPLER_CUBE
  11236. case 0x8dcc: // INT_SAMPLER_CUBE
  11237. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11238. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11239. return setValueT6;
  11240. case 0x8dc1: // SAMPLER_2D_ARRAY
  11241. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11242. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11243. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11244. return setValueT2DArray1;
  11245. }
  11246. }
  11247. // Array of scalars
  11248. function setValueV1fArray( gl, v ) {
  11249. gl.uniform1fv( this.addr, v );
  11250. }
  11251. // Array of vectors (from flat array or array of THREE.VectorN)
  11252. function setValueV2fArray( gl, v ) {
  11253. const data = flatten( v, this.size, 2 );
  11254. gl.uniform2fv( this.addr, data );
  11255. }
  11256. function setValueV3fArray( gl, v ) {
  11257. const data = flatten( v, this.size, 3 );
  11258. gl.uniform3fv( this.addr, data );
  11259. }
  11260. function setValueV4fArray( gl, v ) {
  11261. const data = flatten( v, this.size, 4 );
  11262. gl.uniform4fv( this.addr, data );
  11263. }
  11264. // Array of matrices (from flat array or array of THREE.MatrixN)
  11265. function setValueM2Array( gl, v ) {
  11266. const data = flatten( v, this.size, 4 );
  11267. gl.uniformMatrix2fv( this.addr, false, data );
  11268. }
  11269. function setValueM3Array( gl, v ) {
  11270. const data = flatten( v, this.size, 9 );
  11271. gl.uniformMatrix3fv( this.addr, false, data );
  11272. }
  11273. function setValueM4Array( gl, v ) {
  11274. const data = flatten( v, this.size, 16 );
  11275. gl.uniformMatrix4fv( this.addr, false, data );
  11276. }
  11277. // Array of integer / boolean
  11278. function setValueV1iArray( gl, v ) {
  11279. gl.uniform1iv( this.addr, v );
  11280. }
  11281. // Array of integer / boolean vectors (from flat array)
  11282. function setValueV2iArray( gl, v ) {
  11283. gl.uniform2iv( this.addr, v );
  11284. }
  11285. function setValueV3iArray( gl, v ) {
  11286. gl.uniform3iv( this.addr, v );
  11287. }
  11288. function setValueV4iArray( gl, v ) {
  11289. gl.uniform4iv( this.addr, v );
  11290. }
  11291. // Array of unsigned integer
  11292. function setValueV1uiArray( gl, v ) {
  11293. gl.uniform1uiv( this.addr, v );
  11294. }
  11295. // Array of unsigned integer vectors (from flat array)
  11296. function setValueV2uiArray( gl, v ) {
  11297. gl.uniform2uiv( this.addr, v );
  11298. }
  11299. function setValueV3uiArray( gl, v ) {
  11300. gl.uniform3uiv( this.addr, v );
  11301. }
  11302. function setValueV4uiArray( gl, v ) {
  11303. gl.uniform4uiv( this.addr, v );
  11304. }
  11305. // Array of textures (2D / 3D / Cube / 2DArray)
  11306. function setValueT1Array( gl, v, textures ) {
  11307. const cache = this.cache;
  11308. const n = v.length;
  11309. const units = allocTexUnits( textures, n );
  11310. if ( ! arraysEqual( cache, units ) ) {
  11311. gl.uniform1iv( this.addr, units );
  11312. copyArray( cache, units );
  11313. }
  11314. for ( let i = 0; i !== n; ++ i ) {
  11315. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11316. }
  11317. }
  11318. function setValueT3DArray( gl, v, textures ) {
  11319. const cache = this.cache;
  11320. const n = v.length;
  11321. const units = allocTexUnits( textures, n );
  11322. if ( ! arraysEqual( cache, units ) ) {
  11323. gl.uniform1iv( this.addr, units );
  11324. copyArray( cache, units );
  11325. }
  11326. for ( let i = 0; i !== n; ++ i ) {
  11327. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11328. }
  11329. }
  11330. function setValueT6Array( gl, v, textures ) {
  11331. const cache = this.cache;
  11332. const n = v.length;
  11333. const units = allocTexUnits( textures, n );
  11334. if ( ! arraysEqual( cache, units ) ) {
  11335. gl.uniform1iv( this.addr, units );
  11336. copyArray( cache, units );
  11337. }
  11338. for ( let i = 0; i !== n; ++ i ) {
  11339. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11340. }
  11341. }
  11342. function setValueT2DArrayArray( gl, v, textures ) {
  11343. const cache = this.cache;
  11344. const n = v.length;
  11345. const units = allocTexUnits( textures, n );
  11346. if ( ! arraysEqual( cache, units ) ) {
  11347. gl.uniform1iv( this.addr, units );
  11348. copyArray( cache, units );
  11349. }
  11350. for ( let i = 0; i !== n; ++ i ) {
  11351. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11352. }
  11353. }
  11354. // Helper to pick the right setter for a pure (bottom-level) array
  11355. function getPureArraySetter( type ) {
  11356. switch ( type ) {
  11357. case 0x1406: return setValueV1fArray; // FLOAT
  11358. case 0x8b50: return setValueV2fArray; // _VEC2
  11359. case 0x8b51: return setValueV3fArray; // _VEC3
  11360. case 0x8b52: return setValueV4fArray; // _VEC4
  11361. case 0x8b5a: return setValueM2Array; // _MAT2
  11362. case 0x8b5b: return setValueM3Array; // _MAT3
  11363. case 0x8b5c: return setValueM4Array; // _MAT4
  11364. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11365. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11366. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11367. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11368. case 0x1405: return setValueV1uiArray; // UINT
  11369. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11370. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11371. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11372. case 0x8b5e: // SAMPLER_2D
  11373. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11374. case 0x8dca: // INT_SAMPLER_2D
  11375. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11376. case 0x8b62: // SAMPLER_2D_SHADOW
  11377. return setValueT1Array;
  11378. case 0x8b5f: // SAMPLER_3D
  11379. case 0x8dcb: // INT_SAMPLER_3D
  11380. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11381. return setValueT3DArray;
  11382. case 0x8b60: // SAMPLER_CUBE
  11383. case 0x8dcc: // INT_SAMPLER_CUBE
  11384. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11385. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11386. return setValueT6Array;
  11387. case 0x8dc1: // SAMPLER_2D_ARRAY
  11388. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11389. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11390. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11391. return setValueT2DArrayArray;
  11392. }
  11393. }
  11394. // --- Uniform Classes ---
  11395. class SingleUniform {
  11396. constructor( id, activeInfo, addr ) {
  11397. this.id = id;
  11398. this.addr = addr;
  11399. this.cache = [];
  11400. this.type = activeInfo.type;
  11401. this.setValue = getSingularSetter( activeInfo.type );
  11402. // this.path = activeInfo.name; // DEBUG
  11403. }
  11404. }
  11405. class PureArrayUniform {
  11406. constructor( id, activeInfo, addr ) {
  11407. this.id = id;
  11408. this.addr = addr;
  11409. this.cache = [];
  11410. this.type = activeInfo.type;
  11411. this.size = activeInfo.size;
  11412. this.setValue = getPureArraySetter( activeInfo.type );
  11413. // this.path = activeInfo.name; // DEBUG
  11414. }
  11415. }
  11416. class StructuredUniform {
  11417. constructor( id ) {
  11418. this.id = id;
  11419. this.seq = [];
  11420. this.map = {};
  11421. }
  11422. setValue( gl, value, textures ) {
  11423. const seq = this.seq;
  11424. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11425. const u = seq[ i ];
  11426. u.setValue( gl, value[ u.id ], textures );
  11427. }
  11428. }
  11429. }
  11430. // --- Top-level ---
  11431. // Parser - builds up the property tree from the path strings
  11432. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11433. // extracts
  11434. // - the identifier (member name or array index)
  11435. // - followed by an optional right bracket (found when array index)
  11436. // - followed by an optional left bracket or dot (type of subscript)
  11437. //
  11438. // Note: These portions can be read in a non-overlapping fashion and
  11439. // allow straightforward parsing of the hierarchy that WebGL encodes
  11440. // in the uniform names.
  11441. function addUniform( container, uniformObject ) {
  11442. container.seq.push( uniformObject );
  11443. container.map[ uniformObject.id ] = uniformObject;
  11444. }
  11445. function parseUniform( activeInfo, addr, container ) {
  11446. const path = activeInfo.name,
  11447. pathLength = path.length;
  11448. // reset RegExp object, because of the early exit of a previous run
  11449. RePathPart.lastIndex = 0;
  11450. while ( true ) {
  11451. const match = RePathPart.exec( path ),
  11452. matchEnd = RePathPart.lastIndex;
  11453. let id = match[ 1 ];
  11454. const idIsIndex = match[ 2 ] === ']',
  11455. subscript = match[ 3 ];
  11456. if ( idIsIndex ) id = id | 0; // convert to integer
  11457. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11458. // bare name or "pure" bottom-level array "[0]" suffix
  11459. addUniform( container, subscript === undefined ?
  11460. new SingleUniform( id, activeInfo, addr ) :
  11461. new PureArrayUniform( id, activeInfo, addr ) );
  11462. break;
  11463. } else {
  11464. // step into inner node / create it in case it doesn't exist
  11465. const map = container.map;
  11466. let next = map[ id ];
  11467. if ( next === undefined ) {
  11468. next = new StructuredUniform( id );
  11469. addUniform( container, next );
  11470. }
  11471. container = next;
  11472. }
  11473. }
  11474. }
  11475. // Root Container
  11476. class WebGLUniforms {
  11477. constructor( gl, program ) {
  11478. this.seq = [];
  11479. this.map = {};
  11480. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11481. for ( let i = 0; i < n; ++ i ) {
  11482. const info = gl.getActiveUniform( program, i ),
  11483. addr = gl.getUniformLocation( program, info.name );
  11484. parseUniform( info, addr, this );
  11485. }
  11486. }
  11487. setValue( gl, name, value, textures ) {
  11488. const u = this.map[ name ];
  11489. if ( u !== undefined ) u.setValue( gl, value, textures );
  11490. }
  11491. setOptional( gl, object, name ) {
  11492. const v = object[ name ];
  11493. if ( v !== undefined ) this.setValue( gl, name, v );
  11494. }
  11495. static upload( gl, seq, values, textures ) {
  11496. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11497. const u = seq[ i ],
  11498. v = values[ u.id ];
  11499. if ( v.needsUpdate !== false ) {
  11500. // note: always updating when .needsUpdate is undefined
  11501. u.setValue( gl, v.value, textures );
  11502. }
  11503. }
  11504. }
  11505. static seqWithValue( seq, values ) {
  11506. const r = [];
  11507. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11508. const u = seq[ i ];
  11509. if ( u.id in values ) r.push( u );
  11510. }
  11511. return r;
  11512. }
  11513. }
  11514. function WebGLShader( gl, type, string ) {
  11515. const shader = gl.createShader( type );
  11516. gl.shaderSource( shader, string );
  11517. gl.compileShader( shader );
  11518. return shader;
  11519. }
  11520. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  11521. const COMPLETION_STATUS_KHR = 0x91B1;
  11522. let programIdCount = 0;
  11523. function handleSource( string, errorLine ) {
  11524. const lines = string.split( '\n' );
  11525. const lines2 = [];
  11526. const from = Math.max( errorLine - 6, 0 );
  11527. const to = Math.min( errorLine + 6, lines.length );
  11528. for ( let i = from; i < to; i ++ ) {
  11529. const line = i + 1;
  11530. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11531. }
  11532. return lines2.join( '\n' );
  11533. }
  11534. function getEncodingComponents( colorSpace ) {
  11535. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11536. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11537. let gamutMapping;
  11538. if ( workingPrimaries === encodingPrimaries ) {
  11539. gamutMapping = '';
  11540. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11541. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11542. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11543. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11544. }
  11545. switch ( colorSpace ) {
  11546. case LinearSRGBColorSpace:
  11547. case LinearDisplayP3ColorSpace:
  11548. return [ gamutMapping, 'LinearTransferOETF' ];
  11549. case SRGBColorSpace:
  11550. case DisplayP3ColorSpace:
  11551. return [ gamutMapping, 'sRGBTransferOETF' ];
  11552. default:
  11553. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11554. return [ gamutMapping, 'LinearTransferOETF' ];
  11555. }
  11556. }
  11557. function getShaderErrors( gl, shader, type ) {
  11558. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11559. const errors = gl.getShaderInfoLog( shader ).trim();
  11560. if ( status && errors === '' ) return '';
  11561. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11562. if ( errorMatches ) {
  11563. // --enable-privileged-webgl-extension
  11564. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11565. const errorLine = parseInt( errorMatches[ 1 ] );
  11566. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11567. } else {
  11568. return errors;
  11569. }
  11570. }
  11571. function getTexelEncodingFunction( functionName, colorSpace ) {
  11572. const components = getEncodingComponents( colorSpace );
  11573. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11574. }
  11575. function getToneMappingFunction( functionName, toneMapping ) {
  11576. let toneMappingName;
  11577. switch ( toneMapping ) {
  11578. case LinearToneMapping:
  11579. toneMappingName = 'Linear';
  11580. break;
  11581. case ReinhardToneMapping:
  11582. toneMappingName = 'Reinhard';
  11583. break;
  11584. case CineonToneMapping:
  11585. toneMappingName = 'OptimizedCineon';
  11586. break;
  11587. case ACESFilmicToneMapping:
  11588. toneMappingName = 'ACESFilmic';
  11589. break;
  11590. case AgXToneMapping:
  11591. toneMappingName = 'AgX';
  11592. break;
  11593. case NeutralToneMapping:
  11594. toneMappingName = 'Neutral';
  11595. break;
  11596. case CustomToneMapping:
  11597. toneMappingName = 'Custom';
  11598. break;
  11599. default:
  11600. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11601. toneMappingName = 'Linear';
  11602. }
  11603. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11604. }
  11605. function generateVertexExtensions( parameters ) {
  11606. const chunks = [
  11607. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  11608. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  11609. ];
  11610. return chunks.filter( filterEmptyLine ).join( '\n' );
  11611. }
  11612. function generateDefines( defines ) {
  11613. const chunks = [];
  11614. for ( const name in defines ) {
  11615. const value = defines[ name ];
  11616. if ( value === false ) continue;
  11617. chunks.push( '#define ' + name + ' ' + value );
  11618. }
  11619. return chunks.join( '\n' );
  11620. }
  11621. function fetchAttributeLocations( gl, program ) {
  11622. const attributes = {};
  11623. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11624. for ( let i = 0; i < n; i ++ ) {
  11625. const info = gl.getActiveAttrib( program, i );
  11626. const name = info.name;
  11627. let locationSize = 1;
  11628. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11629. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11630. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11631. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11632. attributes[ name ] = {
  11633. type: info.type,
  11634. location: gl.getAttribLocation( program, name ),
  11635. locationSize: locationSize
  11636. };
  11637. }
  11638. return attributes;
  11639. }
  11640. function filterEmptyLine( string ) {
  11641. return string !== '';
  11642. }
  11643. function replaceLightNums( string, parameters ) {
  11644. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11645. return string
  11646. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11647. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11648. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11649. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11650. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11651. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11652. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11653. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11654. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11655. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11656. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11657. }
  11658. function replaceClippingPlaneNums( string, parameters ) {
  11659. return string
  11660. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11661. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11662. }
  11663. // Resolve Includes
  11664. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11665. function resolveIncludes( string ) {
  11666. return string.replace( includePattern, includeReplacer );
  11667. }
  11668. const shaderChunkMap = new Map();
  11669. function includeReplacer( match, include ) {
  11670. let string = ShaderChunk[ include ];
  11671. if ( string === undefined ) {
  11672. const newInclude = shaderChunkMap.get( include );
  11673. if ( newInclude !== undefined ) {
  11674. string = ShaderChunk[ newInclude ];
  11675. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11676. } else {
  11677. throw new Error( 'Can not resolve #include <' + include + '>' );
  11678. }
  11679. }
  11680. return resolveIncludes( string );
  11681. }
  11682. // Unroll Loops
  11683. 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;
  11684. function unrollLoops( string ) {
  11685. return string.replace( unrollLoopPattern, loopReplacer );
  11686. }
  11687. function loopReplacer( match, start, end, snippet ) {
  11688. let string = '';
  11689. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11690. string += snippet
  11691. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11692. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11693. }
  11694. return string;
  11695. }
  11696. //
  11697. function generatePrecision( parameters ) {
  11698. let precisionstring = `precision ${parameters.precision} float;
  11699. precision ${parameters.precision} int;
  11700. precision ${parameters.precision} sampler2D;
  11701. precision ${parameters.precision} samplerCube;
  11702. precision ${parameters.precision} sampler3D;
  11703. precision ${parameters.precision} sampler2DArray;
  11704. precision ${parameters.precision} sampler2DShadow;
  11705. precision ${parameters.precision} samplerCubeShadow;
  11706. precision ${parameters.precision} sampler2DArrayShadow;
  11707. precision ${parameters.precision} isampler2D;
  11708. precision ${parameters.precision} isampler3D;
  11709. precision ${parameters.precision} isamplerCube;
  11710. precision ${parameters.precision} isampler2DArray;
  11711. precision ${parameters.precision} usampler2D;
  11712. precision ${parameters.precision} usampler3D;
  11713. precision ${parameters.precision} usamplerCube;
  11714. precision ${parameters.precision} usampler2DArray;
  11715. `;
  11716. if ( parameters.precision === 'highp' ) {
  11717. precisionstring += '\n#define HIGH_PRECISION';
  11718. } else if ( parameters.precision === 'mediump' ) {
  11719. precisionstring += '\n#define MEDIUM_PRECISION';
  11720. } else if ( parameters.precision === 'lowp' ) {
  11721. precisionstring += '\n#define LOW_PRECISION';
  11722. }
  11723. return precisionstring;
  11724. }
  11725. function generateShadowMapTypeDefine( parameters ) {
  11726. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11727. if ( parameters.shadowMapType === PCFShadowMap ) {
  11728. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11729. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11730. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11731. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11732. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11733. }
  11734. return shadowMapTypeDefine;
  11735. }
  11736. function generateEnvMapTypeDefine( parameters ) {
  11737. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11738. if ( parameters.envMap ) {
  11739. switch ( parameters.envMapMode ) {
  11740. case CubeReflectionMapping:
  11741. case CubeRefractionMapping:
  11742. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11743. break;
  11744. case CubeUVReflectionMapping:
  11745. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11746. break;
  11747. }
  11748. }
  11749. return envMapTypeDefine;
  11750. }
  11751. function generateEnvMapModeDefine( parameters ) {
  11752. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11753. if ( parameters.envMap ) {
  11754. switch ( parameters.envMapMode ) {
  11755. case CubeRefractionMapping:
  11756. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11757. break;
  11758. }
  11759. }
  11760. return envMapModeDefine;
  11761. }
  11762. function generateEnvMapBlendingDefine( parameters ) {
  11763. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11764. if ( parameters.envMap ) {
  11765. switch ( parameters.combine ) {
  11766. case MultiplyOperation:
  11767. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11768. break;
  11769. case MixOperation:
  11770. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11771. break;
  11772. case AddOperation:
  11773. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11774. break;
  11775. }
  11776. }
  11777. return envMapBlendingDefine;
  11778. }
  11779. function generateCubeUVSize( parameters ) {
  11780. const imageHeight = parameters.envMapCubeUVHeight;
  11781. if ( imageHeight === null ) return null;
  11782. const maxMip = Math.log2( imageHeight ) - 2;
  11783. const texelHeight = 1.0 / imageHeight;
  11784. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11785. return { texelWidth, texelHeight, maxMip };
  11786. }
  11787. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11788. // TODO Send this event to Three.js DevTools
  11789. // console.log( 'WebGLProgram', cacheKey );
  11790. const gl = renderer.getContext();
  11791. const defines = parameters.defines;
  11792. let vertexShader = parameters.vertexShader;
  11793. let fragmentShader = parameters.fragmentShader;
  11794. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11795. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11796. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11797. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11798. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11799. const customVertexExtensions = generateVertexExtensions( parameters );
  11800. const customDefines = generateDefines( defines );
  11801. const program = gl.createProgram();
  11802. let prefixVertex, prefixFragment;
  11803. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11804. if ( parameters.isRawShaderMaterial ) {
  11805. prefixVertex = [
  11806. '#define SHADER_TYPE ' + parameters.shaderType,
  11807. '#define SHADER_NAME ' + parameters.shaderName,
  11808. customDefines
  11809. ].filter( filterEmptyLine ).join( '\n' );
  11810. if ( prefixVertex.length > 0 ) {
  11811. prefixVertex += '\n';
  11812. }
  11813. prefixFragment = [
  11814. '#define SHADER_TYPE ' + parameters.shaderType,
  11815. '#define SHADER_NAME ' + parameters.shaderName,
  11816. customDefines
  11817. ].filter( filterEmptyLine ).join( '\n' );
  11818. if ( prefixFragment.length > 0 ) {
  11819. prefixFragment += '\n';
  11820. }
  11821. } else {
  11822. prefixVertex = [
  11823. generatePrecision( parameters ),
  11824. '#define SHADER_TYPE ' + parameters.shaderType,
  11825. '#define SHADER_NAME ' + parameters.shaderName,
  11826. customDefines,
  11827. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  11828. parameters.batching ? '#define USE_BATCHING' : '',
  11829. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  11830. parameters.instancing ? '#define USE_INSTANCING' : '',
  11831. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11832. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  11833. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11834. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11835. parameters.map ? '#define USE_MAP' : '',
  11836. parameters.envMap ? '#define USE_ENVMAP' : '',
  11837. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11838. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11839. parameters.aoMap ? '#define USE_AOMAP' : '',
  11840. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11841. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11842. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11843. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11844. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11845. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11846. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11847. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11848. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11849. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11850. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11851. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11852. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11853. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11854. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11855. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11856. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11857. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11858. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11859. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11860. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11861. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11862. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11863. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11864. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11865. //
  11866. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11867. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11868. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11869. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11870. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11871. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11872. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11873. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11874. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11875. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11876. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11877. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11878. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11879. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11880. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11881. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11882. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11883. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11884. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11885. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11886. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11887. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11888. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11889. //
  11890. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11891. parameters.vertexColors ? '#define USE_COLOR' : '',
  11892. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11893. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11894. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11895. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11896. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11897. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11898. parameters.skinning ? '#define USE_SKINNING' : '',
  11899. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11900. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11901. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  11902. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11903. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11904. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11905. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11906. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11907. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11908. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11909. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11910. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11911. 'uniform mat4 modelMatrix;',
  11912. 'uniform mat4 modelViewMatrix;',
  11913. 'uniform mat4 projectionMatrix;',
  11914. 'uniform mat4 viewMatrix;',
  11915. 'uniform mat3 normalMatrix;',
  11916. 'uniform vec3 cameraPosition;',
  11917. 'uniform bool isOrthographic;',
  11918. '#ifdef USE_INSTANCING',
  11919. ' attribute mat4 instanceMatrix;',
  11920. '#endif',
  11921. '#ifdef USE_INSTANCING_COLOR',
  11922. ' attribute vec3 instanceColor;',
  11923. '#endif',
  11924. '#ifdef USE_INSTANCING_MORPH',
  11925. ' uniform sampler2D morphTexture;',
  11926. '#endif',
  11927. 'attribute vec3 position;',
  11928. 'attribute vec3 normal;',
  11929. 'attribute vec2 uv;',
  11930. '#ifdef USE_UV1',
  11931. ' attribute vec2 uv1;',
  11932. '#endif',
  11933. '#ifdef USE_UV2',
  11934. ' attribute vec2 uv2;',
  11935. '#endif',
  11936. '#ifdef USE_UV3',
  11937. ' attribute vec2 uv3;',
  11938. '#endif',
  11939. '#ifdef USE_TANGENT',
  11940. ' attribute vec4 tangent;',
  11941. '#endif',
  11942. '#if defined( USE_COLOR_ALPHA )',
  11943. ' attribute vec4 color;',
  11944. '#elif defined( USE_COLOR )',
  11945. ' attribute vec3 color;',
  11946. '#endif',
  11947. '#ifdef USE_SKINNING',
  11948. ' attribute vec4 skinIndex;',
  11949. ' attribute vec4 skinWeight;',
  11950. '#endif',
  11951. '\n'
  11952. ].filter( filterEmptyLine ).join( '\n' );
  11953. prefixFragment = [
  11954. generatePrecision( parameters ),
  11955. '#define SHADER_TYPE ' + parameters.shaderType,
  11956. '#define SHADER_NAME ' + parameters.shaderName,
  11957. customDefines,
  11958. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11959. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11960. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  11961. parameters.map ? '#define USE_MAP' : '',
  11962. parameters.matcap ? '#define USE_MATCAP' : '',
  11963. parameters.envMap ? '#define USE_ENVMAP' : '',
  11964. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11965. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11966. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11967. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11968. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11969. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11970. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11971. parameters.aoMap ? '#define USE_AOMAP' : '',
  11972. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11973. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11974. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11975. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11976. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11977. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11978. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11979. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11980. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11981. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11982. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11983. parameters.dispersion ? '#define USE_DISPERSION' : '',
  11984. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11985. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11986. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11987. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11988. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11989. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11990. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11991. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11992. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11993. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11994. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11995. parameters.sheen ? '#define USE_SHEEN' : '',
  11996. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11997. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11998. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11999. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12000. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12001. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  12002. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  12003. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12004. parameters.vertexUv1s ? '#define USE_UV1' : '',
  12005. parameters.vertexUv2s ? '#define USE_UV2' : '',
  12006. parameters.vertexUv3s ? '#define USE_UV3' : '',
  12007. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  12008. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12009. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12010. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12011. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12012. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12013. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12014. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  12015. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  12016. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  12017. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12018. 'uniform mat4 viewMatrix;',
  12019. 'uniform vec3 cameraPosition;',
  12020. 'uniform bool isOrthographic;',
  12021. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  12022. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12023. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  12024. parameters.dithering ? '#define DITHERING' : '',
  12025. parameters.opaque ? '#define OPAQUE' : '',
  12026. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  12027. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  12028. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  12029. '\n'
  12030. ].filter( filterEmptyLine ).join( '\n' );
  12031. }
  12032. vertexShader = resolveIncludes( vertexShader );
  12033. vertexShader = replaceLightNums( vertexShader, parameters );
  12034. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  12035. fragmentShader = resolveIncludes( fragmentShader );
  12036. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12037. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  12038. vertexShader = unrollLoops( vertexShader );
  12039. fragmentShader = unrollLoops( fragmentShader );
  12040. if ( parameters.isRawShaderMaterial !== true ) {
  12041. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  12042. versionString = '#version 300 es\n';
  12043. prefixVertex = [
  12044. customVertexExtensions,
  12045. '#define attribute in',
  12046. '#define varying out',
  12047. '#define texture2D texture'
  12048. ].join( '\n' ) + '\n' + prefixVertex;
  12049. prefixFragment = [
  12050. '#define varying in',
  12051. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  12052. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  12053. '#define gl_FragDepthEXT gl_FragDepth',
  12054. '#define texture2D texture',
  12055. '#define textureCube texture',
  12056. '#define texture2DProj textureProj',
  12057. '#define texture2DLodEXT textureLod',
  12058. '#define texture2DProjLodEXT textureProjLod',
  12059. '#define textureCubeLodEXT textureLod',
  12060. '#define texture2DGradEXT textureGrad',
  12061. '#define texture2DProjGradEXT textureProjGrad',
  12062. '#define textureCubeGradEXT textureGrad'
  12063. ].join( '\n' ) + '\n' + prefixFragment;
  12064. }
  12065. const vertexGlsl = versionString + prefixVertex + vertexShader;
  12066. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  12067. // console.log( '*VERTEX*', vertexGlsl );
  12068. // console.log( '*FRAGMENT*', fragmentGlsl );
  12069. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  12070. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  12071. gl.attachShader( program, glVertexShader );
  12072. gl.attachShader( program, glFragmentShader );
  12073. // Force a particular attribute to index 0.
  12074. if ( parameters.index0AttributeName !== undefined ) {
  12075. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12076. } else if ( parameters.morphTargets === true ) {
  12077. // programs with morphTargets displace position out of attribute 0
  12078. gl.bindAttribLocation( program, 0, 'position' );
  12079. }
  12080. gl.linkProgram( program );
  12081. function onFirstUse( self ) {
  12082. // check for link errors
  12083. if ( renderer.debug.checkShaderErrors ) {
  12084. const programLog = gl.getProgramInfoLog( program ).trim();
  12085. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12086. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12087. let runnable = true;
  12088. let haveDiagnostics = true;
  12089. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12090. runnable = false;
  12091. if ( typeof renderer.debug.onShaderError === 'function' ) {
  12092. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  12093. } else {
  12094. // default error reporting
  12095. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12096. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12097. console.error(
  12098. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12099. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  12100. 'Material Name: ' + self.name + '\n' +
  12101. 'Material Type: ' + self.type + '\n\n' +
  12102. 'Program Info Log: ' + programLog + '\n' +
  12103. vertexErrors + '\n' +
  12104. fragmentErrors
  12105. );
  12106. }
  12107. } else if ( programLog !== '' ) {
  12108. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12109. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12110. haveDiagnostics = false;
  12111. }
  12112. if ( haveDiagnostics ) {
  12113. self.diagnostics = {
  12114. runnable: runnable,
  12115. programLog: programLog,
  12116. vertexShader: {
  12117. log: vertexLog,
  12118. prefix: prefixVertex
  12119. },
  12120. fragmentShader: {
  12121. log: fragmentLog,
  12122. prefix: prefixFragment
  12123. }
  12124. };
  12125. }
  12126. }
  12127. // Clean up
  12128. // Crashes in iOS9 and iOS10. #18402
  12129. // gl.detachShader( program, glVertexShader );
  12130. // gl.detachShader( program, glFragmentShader );
  12131. gl.deleteShader( glVertexShader );
  12132. gl.deleteShader( glFragmentShader );
  12133. cachedUniforms = new WebGLUniforms( gl, program );
  12134. cachedAttributes = fetchAttributeLocations( gl, program );
  12135. }
  12136. // set up caching for uniform locations
  12137. let cachedUniforms;
  12138. this.getUniforms = function () {
  12139. if ( cachedUniforms === undefined ) {
  12140. // Populates cachedUniforms and cachedAttributes
  12141. onFirstUse( this );
  12142. }
  12143. return cachedUniforms;
  12144. };
  12145. // set up caching for attribute locations
  12146. let cachedAttributes;
  12147. this.getAttributes = function () {
  12148. if ( cachedAttributes === undefined ) {
  12149. // Populates cachedAttributes and cachedUniforms
  12150. onFirstUse( this );
  12151. }
  12152. return cachedAttributes;
  12153. };
  12154. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  12155. // flag the program as ready immediately. It may cause a stall when it's first used.
  12156. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  12157. this.isReady = function () {
  12158. if ( programReady === false ) {
  12159. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  12160. }
  12161. return programReady;
  12162. };
  12163. // free resource
  12164. this.destroy = function () {
  12165. bindingStates.releaseStatesOfProgram( this );
  12166. gl.deleteProgram( program );
  12167. this.program = undefined;
  12168. };
  12169. //
  12170. this.type = parameters.shaderType;
  12171. this.name = parameters.shaderName;
  12172. this.id = programIdCount ++;
  12173. this.cacheKey = cacheKey;
  12174. this.usedTimes = 1;
  12175. this.program = program;
  12176. this.vertexShader = glVertexShader;
  12177. this.fragmentShader = glFragmentShader;
  12178. return this;
  12179. }
  12180. let _id$1 = 0;
  12181. class WebGLShaderCache {
  12182. constructor() {
  12183. this.shaderCache = new Map();
  12184. this.materialCache = new Map();
  12185. }
  12186. update( material ) {
  12187. const vertexShader = material.vertexShader;
  12188. const fragmentShader = material.fragmentShader;
  12189. const vertexShaderStage = this._getShaderStage( vertexShader );
  12190. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12191. const materialShaders = this._getShaderCacheForMaterial( material );
  12192. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12193. materialShaders.add( vertexShaderStage );
  12194. vertexShaderStage.usedTimes ++;
  12195. }
  12196. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12197. materialShaders.add( fragmentShaderStage );
  12198. fragmentShaderStage.usedTimes ++;
  12199. }
  12200. return this;
  12201. }
  12202. remove( material ) {
  12203. const materialShaders = this.materialCache.get( material );
  12204. for ( const shaderStage of materialShaders ) {
  12205. shaderStage.usedTimes --;
  12206. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12207. }
  12208. this.materialCache.delete( material );
  12209. return this;
  12210. }
  12211. getVertexShaderID( material ) {
  12212. return this._getShaderStage( material.vertexShader ).id;
  12213. }
  12214. getFragmentShaderID( material ) {
  12215. return this._getShaderStage( material.fragmentShader ).id;
  12216. }
  12217. dispose() {
  12218. this.shaderCache.clear();
  12219. this.materialCache.clear();
  12220. }
  12221. _getShaderCacheForMaterial( material ) {
  12222. const cache = this.materialCache;
  12223. let set = cache.get( material );
  12224. if ( set === undefined ) {
  12225. set = new Set();
  12226. cache.set( material, set );
  12227. }
  12228. return set;
  12229. }
  12230. _getShaderStage( code ) {
  12231. const cache = this.shaderCache;
  12232. let stage = cache.get( code );
  12233. if ( stage === undefined ) {
  12234. stage = new WebGLShaderStage( code );
  12235. cache.set( code, stage );
  12236. }
  12237. return stage;
  12238. }
  12239. }
  12240. class WebGLShaderStage {
  12241. constructor( code ) {
  12242. this.id = _id$1 ++;
  12243. this.code = code;
  12244. this.usedTimes = 0;
  12245. }
  12246. }
  12247. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12248. const _programLayers = new Layers();
  12249. const _customShaders = new WebGLShaderCache();
  12250. const _activeChannels = new Set();
  12251. const programs = [];
  12252. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12253. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12254. let precision = capabilities.precision;
  12255. const shaderIDs = {
  12256. MeshDepthMaterial: 'depth',
  12257. MeshDistanceMaterial: 'distanceRGBA',
  12258. MeshNormalMaterial: 'normal',
  12259. MeshBasicMaterial: 'basic',
  12260. MeshLambertMaterial: 'lambert',
  12261. MeshPhongMaterial: 'phong',
  12262. MeshToonMaterial: 'toon',
  12263. MeshStandardMaterial: 'physical',
  12264. MeshPhysicalMaterial: 'physical',
  12265. MeshMatcapMaterial: 'matcap',
  12266. LineBasicMaterial: 'basic',
  12267. LineDashedMaterial: 'dashed',
  12268. PointsMaterial: 'points',
  12269. ShadowMaterial: 'shadow',
  12270. SpriteMaterial: 'sprite'
  12271. };
  12272. function getChannel( value ) {
  12273. _activeChannels.add( value );
  12274. if ( value === 0 ) return 'uv';
  12275. return `uv${ value }`;
  12276. }
  12277. function getParameters( material, lights, shadows, scene, object ) {
  12278. const fog = scene.fog;
  12279. const geometry = object.geometry;
  12280. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12281. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12282. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12283. const shaderID = shaderIDs[ material.type ];
  12284. // heuristics to create shader parameters according to lights in the scene
  12285. // (not to blow over maxLights budget)
  12286. if ( material.precision !== null ) {
  12287. precision = capabilities.getMaxPrecision( material.precision );
  12288. if ( precision !== material.precision ) {
  12289. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12290. }
  12291. }
  12292. //
  12293. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12294. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12295. let morphTextureStride = 0;
  12296. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12297. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12298. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12299. //
  12300. let vertexShader, fragmentShader;
  12301. let customVertexShaderID, customFragmentShaderID;
  12302. if ( shaderID ) {
  12303. const shader = ShaderLib[ shaderID ];
  12304. vertexShader = shader.vertexShader;
  12305. fragmentShader = shader.fragmentShader;
  12306. } else {
  12307. vertexShader = material.vertexShader;
  12308. fragmentShader = material.fragmentShader;
  12309. _customShaders.update( material );
  12310. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12311. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12312. }
  12313. const currentRenderTarget = renderer.getRenderTarget();
  12314. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12315. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  12316. const HAS_MAP = !! material.map;
  12317. const HAS_MATCAP = !! material.matcap;
  12318. const HAS_ENVMAP = !! envMap;
  12319. const HAS_AOMAP = !! material.aoMap;
  12320. const HAS_LIGHTMAP = !! material.lightMap;
  12321. const HAS_BUMPMAP = !! material.bumpMap;
  12322. const HAS_NORMALMAP = !! material.normalMap;
  12323. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12324. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12325. const HAS_METALNESSMAP = !! material.metalnessMap;
  12326. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12327. const HAS_ANISOTROPY = material.anisotropy > 0;
  12328. const HAS_CLEARCOAT = material.clearcoat > 0;
  12329. const HAS_DISPERSION = material.dispersion > 0;
  12330. const HAS_IRIDESCENCE = material.iridescence > 0;
  12331. const HAS_SHEEN = material.sheen > 0;
  12332. const HAS_TRANSMISSION = material.transmission > 0;
  12333. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12334. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12335. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12336. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12337. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12338. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12339. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12340. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12341. const HAS_SPECULARMAP = !! material.specularMap;
  12342. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12343. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12344. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12345. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12346. const HAS_GRADIENTMAP = !! material.gradientMap;
  12347. const HAS_ALPHAMAP = !! material.alphaMap;
  12348. const HAS_ALPHATEST = material.alphaTest > 0;
  12349. const HAS_ALPHAHASH = !! material.alphaHash;
  12350. const HAS_EXTENSIONS = !! material.extensions;
  12351. let toneMapping = NoToneMapping;
  12352. if ( material.toneMapped ) {
  12353. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12354. toneMapping = renderer.toneMapping;
  12355. }
  12356. }
  12357. const parameters = {
  12358. shaderID: shaderID,
  12359. shaderType: material.type,
  12360. shaderName: material.name,
  12361. vertexShader: vertexShader,
  12362. fragmentShader: fragmentShader,
  12363. defines: material.defines,
  12364. customVertexShaderID: customVertexShaderID,
  12365. customFragmentShaderID: customFragmentShaderID,
  12366. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12367. glslVersion: material.glslVersion,
  12368. precision: precision,
  12369. batching: IS_BATCHEDMESH,
  12370. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  12371. instancing: IS_INSTANCEDMESH,
  12372. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12373. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  12374. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12375. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12376. alphaToCoverage: !! material.alphaToCoverage,
  12377. map: HAS_MAP,
  12378. matcap: HAS_MATCAP,
  12379. envMap: HAS_ENVMAP,
  12380. envMapMode: HAS_ENVMAP && envMap.mapping,
  12381. envMapCubeUVHeight: envMapCubeUVHeight,
  12382. aoMap: HAS_AOMAP,
  12383. lightMap: HAS_LIGHTMAP,
  12384. bumpMap: HAS_BUMPMAP,
  12385. normalMap: HAS_NORMALMAP,
  12386. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12387. emissiveMap: HAS_EMISSIVEMAP,
  12388. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12389. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12390. metalnessMap: HAS_METALNESSMAP,
  12391. roughnessMap: HAS_ROUGHNESSMAP,
  12392. anisotropy: HAS_ANISOTROPY,
  12393. anisotropyMap: HAS_ANISOTROPYMAP,
  12394. clearcoat: HAS_CLEARCOAT,
  12395. clearcoatMap: HAS_CLEARCOATMAP,
  12396. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12397. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12398. dispersion: HAS_DISPERSION,
  12399. iridescence: HAS_IRIDESCENCE,
  12400. iridescenceMap: HAS_IRIDESCENCEMAP,
  12401. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12402. sheen: HAS_SHEEN,
  12403. sheenColorMap: HAS_SHEEN_COLORMAP,
  12404. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12405. specularMap: HAS_SPECULARMAP,
  12406. specularColorMap: HAS_SPECULAR_COLORMAP,
  12407. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12408. transmission: HAS_TRANSMISSION,
  12409. transmissionMap: HAS_TRANSMISSIONMAP,
  12410. thicknessMap: HAS_THICKNESSMAP,
  12411. gradientMap: HAS_GRADIENTMAP,
  12412. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  12413. alphaMap: HAS_ALPHAMAP,
  12414. alphaTest: HAS_ALPHATEST,
  12415. alphaHash: HAS_ALPHAHASH,
  12416. combine: material.combine,
  12417. //
  12418. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12419. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12420. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12421. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12422. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12423. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12424. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12425. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12426. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12427. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12428. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12429. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12430. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12431. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12432. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12433. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12434. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12435. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12436. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12437. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12438. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12439. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12440. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12441. //
  12442. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12443. vertexColors: material.vertexColors,
  12444. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12445. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12446. fog: !! fog,
  12447. useFog: material.fog === true,
  12448. fogExp2: ( !! fog && fog.isFogExp2 ),
  12449. flatShading: material.flatShading === true,
  12450. sizeAttenuation: material.sizeAttenuation === true,
  12451. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12452. skinning: object.isSkinnedMesh === true,
  12453. morphTargets: geometry.morphAttributes.position !== undefined,
  12454. morphNormals: geometry.morphAttributes.normal !== undefined,
  12455. morphColors: geometry.morphAttributes.color !== undefined,
  12456. morphTargetsCount: morphTargetsCount,
  12457. morphTextureStride: morphTextureStride,
  12458. numDirLights: lights.directional.length,
  12459. numPointLights: lights.point.length,
  12460. numSpotLights: lights.spot.length,
  12461. numSpotLightMaps: lights.spotLightMap.length,
  12462. numRectAreaLights: lights.rectArea.length,
  12463. numHemiLights: lights.hemi.length,
  12464. numDirLightShadows: lights.directionalShadowMap.length,
  12465. numPointLightShadows: lights.pointShadowMap.length,
  12466. numSpotLightShadows: lights.spotShadowMap.length,
  12467. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12468. numLightProbes: lights.numLightProbes,
  12469. numClippingPlanes: clipping.numPlanes,
  12470. numClipIntersection: clipping.numIntersection,
  12471. dithering: material.dithering,
  12472. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12473. shadowMapType: renderer.shadowMap.type,
  12474. toneMapping: toneMapping,
  12475. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12476. premultipliedAlpha: material.premultipliedAlpha,
  12477. doubleSided: material.side === DoubleSide,
  12478. flipSided: material.side === BackSide,
  12479. useDepthPacking: material.depthPacking >= 0,
  12480. depthPacking: material.depthPacking || 0,
  12481. index0AttributeName: material.index0AttributeName,
  12482. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  12483. extensionMultiDraw: HAS_EXTENSIONS && material.extensions.multiDraw === true && extensions.has( 'WEBGL_multi_draw' ),
  12484. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  12485. customProgramCacheKey: material.customProgramCacheKey()
  12486. };
  12487. // the usage of getChannel() determines the active texture channels for this shader
  12488. parameters.vertexUv1s = _activeChannels.has( 1 );
  12489. parameters.vertexUv2s = _activeChannels.has( 2 );
  12490. parameters.vertexUv3s = _activeChannels.has( 3 );
  12491. _activeChannels.clear();
  12492. return parameters;
  12493. }
  12494. function getProgramCacheKey( parameters ) {
  12495. const array = [];
  12496. if ( parameters.shaderID ) {
  12497. array.push( parameters.shaderID );
  12498. } else {
  12499. array.push( parameters.customVertexShaderID );
  12500. array.push( parameters.customFragmentShaderID );
  12501. }
  12502. if ( parameters.defines !== undefined ) {
  12503. for ( const name in parameters.defines ) {
  12504. array.push( name );
  12505. array.push( parameters.defines[ name ] );
  12506. }
  12507. }
  12508. if ( parameters.isRawShaderMaterial === false ) {
  12509. getProgramCacheKeyParameters( array, parameters );
  12510. getProgramCacheKeyBooleans( array, parameters );
  12511. array.push( renderer.outputColorSpace );
  12512. }
  12513. array.push( parameters.customProgramCacheKey );
  12514. return array.join();
  12515. }
  12516. function getProgramCacheKeyParameters( array, parameters ) {
  12517. array.push( parameters.precision );
  12518. array.push( parameters.outputColorSpace );
  12519. array.push( parameters.envMapMode );
  12520. array.push( parameters.envMapCubeUVHeight );
  12521. array.push( parameters.mapUv );
  12522. array.push( parameters.alphaMapUv );
  12523. array.push( parameters.lightMapUv );
  12524. array.push( parameters.aoMapUv );
  12525. array.push( parameters.bumpMapUv );
  12526. array.push( parameters.normalMapUv );
  12527. array.push( parameters.displacementMapUv );
  12528. array.push( parameters.emissiveMapUv );
  12529. array.push( parameters.metalnessMapUv );
  12530. array.push( parameters.roughnessMapUv );
  12531. array.push( parameters.anisotropyMapUv );
  12532. array.push( parameters.clearcoatMapUv );
  12533. array.push( parameters.clearcoatNormalMapUv );
  12534. array.push( parameters.clearcoatRoughnessMapUv );
  12535. array.push( parameters.iridescenceMapUv );
  12536. array.push( parameters.iridescenceThicknessMapUv );
  12537. array.push( parameters.sheenColorMapUv );
  12538. array.push( parameters.sheenRoughnessMapUv );
  12539. array.push( parameters.specularMapUv );
  12540. array.push( parameters.specularColorMapUv );
  12541. array.push( parameters.specularIntensityMapUv );
  12542. array.push( parameters.transmissionMapUv );
  12543. array.push( parameters.thicknessMapUv );
  12544. array.push( parameters.combine );
  12545. array.push( parameters.fogExp2 );
  12546. array.push( parameters.sizeAttenuation );
  12547. array.push( parameters.morphTargetsCount );
  12548. array.push( parameters.morphAttributeCount );
  12549. array.push( parameters.numDirLights );
  12550. array.push( parameters.numPointLights );
  12551. array.push( parameters.numSpotLights );
  12552. array.push( parameters.numSpotLightMaps );
  12553. array.push( parameters.numHemiLights );
  12554. array.push( parameters.numRectAreaLights );
  12555. array.push( parameters.numDirLightShadows );
  12556. array.push( parameters.numPointLightShadows );
  12557. array.push( parameters.numSpotLightShadows );
  12558. array.push( parameters.numSpotLightShadowsWithMaps );
  12559. array.push( parameters.numLightProbes );
  12560. array.push( parameters.shadowMapType );
  12561. array.push( parameters.toneMapping );
  12562. array.push( parameters.numClippingPlanes );
  12563. array.push( parameters.numClipIntersection );
  12564. array.push( parameters.depthPacking );
  12565. }
  12566. function getProgramCacheKeyBooleans( array, parameters ) {
  12567. _programLayers.disableAll();
  12568. if ( parameters.supportsVertexTextures )
  12569. _programLayers.enable( 0 );
  12570. if ( parameters.instancing )
  12571. _programLayers.enable( 1 );
  12572. if ( parameters.instancingColor )
  12573. _programLayers.enable( 2 );
  12574. if ( parameters.instancingMorph )
  12575. _programLayers.enable( 3 );
  12576. if ( parameters.matcap )
  12577. _programLayers.enable( 4 );
  12578. if ( parameters.envMap )
  12579. _programLayers.enable( 5 );
  12580. if ( parameters.normalMapObjectSpace )
  12581. _programLayers.enable( 6 );
  12582. if ( parameters.normalMapTangentSpace )
  12583. _programLayers.enable( 7 );
  12584. if ( parameters.clearcoat )
  12585. _programLayers.enable( 8 );
  12586. if ( parameters.iridescence )
  12587. _programLayers.enable( 9 );
  12588. if ( parameters.alphaTest )
  12589. _programLayers.enable( 10 );
  12590. if ( parameters.vertexColors )
  12591. _programLayers.enable( 11 );
  12592. if ( parameters.vertexAlphas )
  12593. _programLayers.enable( 12 );
  12594. if ( parameters.vertexUv1s )
  12595. _programLayers.enable( 13 );
  12596. if ( parameters.vertexUv2s )
  12597. _programLayers.enable( 14 );
  12598. if ( parameters.vertexUv3s )
  12599. _programLayers.enable( 15 );
  12600. if ( parameters.vertexTangents )
  12601. _programLayers.enable( 16 );
  12602. if ( parameters.anisotropy )
  12603. _programLayers.enable( 17 );
  12604. if ( parameters.alphaHash )
  12605. _programLayers.enable( 18 );
  12606. if ( parameters.batching )
  12607. _programLayers.enable( 19 );
  12608. if ( parameters.dispersion )
  12609. _programLayers.enable( 20 );
  12610. if ( parameters.batchingColor )
  12611. _programLayers.enable( 21 );
  12612. array.push( _programLayers.mask );
  12613. _programLayers.disableAll();
  12614. if ( parameters.fog )
  12615. _programLayers.enable( 0 );
  12616. if ( parameters.useFog )
  12617. _programLayers.enable( 1 );
  12618. if ( parameters.flatShading )
  12619. _programLayers.enable( 2 );
  12620. if ( parameters.logarithmicDepthBuffer )
  12621. _programLayers.enable( 3 );
  12622. if ( parameters.skinning )
  12623. _programLayers.enable( 4 );
  12624. if ( parameters.morphTargets )
  12625. _programLayers.enable( 5 );
  12626. if ( parameters.morphNormals )
  12627. _programLayers.enable( 6 );
  12628. if ( parameters.morphColors )
  12629. _programLayers.enable( 7 );
  12630. if ( parameters.premultipliedAlpha )
  12631. _programLayers.enable( 8 );
  12632. if ( parameters.shadowMapEnabled )
  12633. _programLayers.enable( 9 );
  12634. if ( parameters.doubleSided )
  12635. _programLayers.enable( 10 );
  12636. if ( parameters.flipSided )
  12637. _programLayers.enable( 11 );
  12638. if ( parameters.useDepthPacking )
  12639. _programLayers.enable( 12 );
  12640. if ( parameters.dithering )
  12641. _programLayers.enable( 13 );
  12642. if ( parameters.transmission )
  12643. _programLayers.enable( 14 );
  12644. if ( parameters.sheen )
  12645. _programLayers.enable( 15 );
  12646. if ( parameters.opaque )
  12647. _programLayers.enable( 16 );
  12648. if ( parameters.pointsUvs )
  12649. _programLayers.enable( 17 );
  12650. if ( parameters.decodeVideoTexture )
  12651. _programLayers.enable( 18 );
  12652. if ( parameters.alphaToCoverage )
  12653. _programLayers.enable( 19 );
  12654. array.push( _programLayers.mask );
  12655. }
  12656. function getUniforms( material ) {
  12657. const shaderID = shaderIDs[ material.type ];
  12658. let uniforms;
  12659. if ( shaderID ) {
  12660. const shader = ShaderLib[ shaderID ];
  12661. uniforms = UniformsUtils.clone( shader.uniforms );
  12662. } else {
  12663. uniforms = material.uniforms;
  12664. }
  12665. return uniforms;
  12666. }
  12667. function acquireProgram( parameters, cacheKey ) {
  12668. let program;
  12669. // Check if code has been already compiled
  12670. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12671. const preexistingProgram = programs[ p ];
  12672. if ( preexistingProgram.cacheKey === cacheKey ) {
  12673. program = preexistingProgram;
  12674. ++ program.usedTimes;
  12675. break;
  12676. }
  12677. }
  12678. if ( program === undefined ) {
  12679. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12680. programs.push( program );
  12681. }
  12682. return program;
  12683. }
  12684. function releaseProgram( program ) {
  12685. if ( -- program.usedTimes === 0 ) {
  12686. // Remove from unordered set
  12687. const i = programs.indexOf( program );
  12688. programs[ i ] = programs[ programs.length - 1 ];
  12689. programs.pop();
  12690. // Free WebGL resources
  12691. program.destroy();
  12692. }
  12693. }
  12694. function releaseShaderCache( material ) {
  12695. _customShaders.remove( material );
  12696. }
  12697. function dispose() {
  12698. _customShaders.dispose();
  12699. }
  12700. return {
  12701. getParameters: getParameters,
  12702. getProgramCacheKey: getProgramCacheKey,
  12703. getUniforms: getUniforms,
  12704. acquireProgram: acquireProgram,
  12705. releaseProgram: releaseProgram,
  12706. releaseShaderCache: releaseShaderCache,
  12707. // Exposed for resource monitoring & error feedback via renderer.info:
  12708. programs: programs,
  12709. dispose: dispose
  12710. };
  12711. }
  12712. function WebGLProperties() {
  12713. let properties = new WeakMap();
  12714. function get( object ) {
  12715. let map = properties.get( object );
  12716. if ( map === undefined ) {
  12717. map = {};
  12718. properties.set( object, map );
  12719. }
  12720. return map;
  12721. }
  12722. function remove( object ) {
  12723. properties.delete( object );
  12724. }
  12725. function update( object, key, value ) {
  12726. properties.get( object )[ key ] = value;
  12727. }
  12728. function dispose() {
  12729. properties = new WeakMap();
  12730. }
  12731. return {
  12732. get: get,
  12733. remove: remove,
  12734. update: update,
  12735. dispose: dispose
  12736. };
  12737. }
  12738. function painterSortStable( a, b ) {
  12739. if ( a.groupOrder !== b.groupOrder ) {
  12740. return a.groupOrder - b.groupOrder;
  12741. } else if ( a.renderOrder !== b.renderOrder ) {
  12742. return a.renderOrder - b.renderOrder;
  12743. } else if ( a.material.id !== b.material.id ) {
  12744. return a.material.id - b.material.id;
  12745. } else if ( a.z !== b.z ) {
  12746. return a.z - b.z;
  12747. } else {
  12748. return a.id - b.id;
  12749. }
  12750. }
  12751. function reversePainterSortStable( a, b ) {
  12752. if ( a.groupOrder !== b.groupOrder ) {
  12753. return a.groupOrder - b.groupOrder;
  12754. } else if ( a.renderOrder !== b.renderOrder ) {
  12755. return a.renderOrder - b.renderOrder;
  12756. } else if ( a.z !== b.z ) {
  12757. return b.z - a.z;
  12758. } else {
  12759. return a.id - b.id;
  12760. }
  12761. }
  12762. function WebGLRenderList() {
  12763. const renderItems = [];
  12764. let renderItemsIndex = 0;
  12765. const opaque = [];
  12766. const transmissive = [];
  12767. const transparent = [];
  12768. function init() {
  12769. renderItemsIndex = 0;
  12770. opaque.length = 0;
  12771. transmissive.length = 0;
  12772. transparent.length = 0;
  12773. }
  12774. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12775. let renderItem = renderItems[ renderItemsIndex ];
  12776. if ( renderItem === undefined ) {
  12777. renderItem = {
  12778. id: object.id,
  12779. object: object,
  12780. geometry: geometry,
  12781. material: material,
  12782. groupOrder: groupOrder,
  12783. renderOrder: object.renderOrder,
  12784. z: z,
  12785. group: group
  12786. };
  12787. renderItems[ renderItemsIndex ] = renderItem;
  12788. } else {
  12789. renderItem.id = object.id;
  12790. renderItem.object = object;
  12791. renderItem.geometry = geometry;
  12792. renderItem.material = material;
  12793. renderItem.groupOrder = groupOrder;
  12794. renderItem.renderOrder = object.renderOrder;
  12795. renderItem.z = z;
  12796. renderItem.group = group;
  12797. }
  12798. renderItemsIndex ++;
  12799. return renderItem;
  12800. }
  12801. function push( object, geometry, material, groupOrder, z, group ) {
  12802. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12803. if ( material.transmission > 0.0 ) {
  12804. transmissive.push( renderItem );
  12805. } else if ( material.transparent === true ) {
  12806. transparent.push( renderItem );
  12807. } else {
  12808. opaque.push( renderItem );
  12809. }
  12810. }
  12811. function unshift( object, geometry, material, groupOrder, z, group ) {
  12812. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12813. if ( material.transmission > 0.0 ) {
  12814. transmissive.unshift( renderItem );
  12815. } else if ( material.transparent === true ) {
  12816. transparent.unshift( renderItem );
  12817. } else {
  12818. opaque.unshift( renderItem );
  12819. }
  12820. }
  12821. function sort( customOpaqueSort, customTransparentSort ) {
  12822. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12823. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12824. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12825. }
  12826. function finish() {
  12827. // Clear references from inactive renderItems in the list
  12828. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12829. const renderItem = renderItems[ i ];
  12830. if ( renderItem.id === null ) break;
  12831. renderItem.id = null;
  12832. renderItem.object = null;
  12833. renderItem.geometry = null;
  12834. renderItem.material = null;
  12835. renderItem.group = null;
  12836. }
  12837. }
  12838. return {
  12839. opaque: opaque,
  12840. transmissive: transmissive,
  12841. transparent: transparent,
  12842. init: init,
  12843. push: push,
  12844. unshift: unshift,
  12845. finish: finish,
  12846. sort: sort
  12847. };
  12848. }
  12849. function WebGLRenderLists() {
  12850. let lists = new WeakMap();
  12851. function get( scene, renderCallDepth ) {
  12852. const listArray = lists.get( scene );
  12853. let list;
  12854. if ( listArray === undefined ) {
  12855. list = new WebGLRenderList();
  12856. lists.set( scene, [ list ] );
  12857. } else {
  12858. if ( renderCallDepth >= listArray.length ) {
  12859. list = new WebGLRenderList();
  12860. listArray.push( list );
  12861. } else {
  12862. list = listArray[ renderCallDepth ];
  12863. }
  12864. }
  12865. return list;
  12866. }
  12867. function dispose() {
  12868. lists = new WeakMap();
  12869. }
  12870. return {
  12871. get: get,
  12872. dispose: dispose
  12873. };
  12874. }
  12875. function UniformsCache() {
  12876. const lights = {};
  12877. return {
  12878. get: function ( light ) {
  12879. if ( lights[ light.id ] !== undefined ) {
  12880. return lights[ light.id ];
  12881. }
  12882. let uniforms;
  12883. switch ( light.type ) {
  12884. case 'DirectionalLight':
  12885. uniforms = {
  12886. direction: new Vector3(),
  12887. color: new Color()
  12888. };
  12889. break;
  12890. case 'SpotLight':
  12891. uniforms = {
  12892. position: new Vector3(),
  12893. direction: new Vector3(),
  12894. color: new Color(),
  12895. distance: 0,
  12896. coneCos: 0,
  12897. penumbraCos: 0,
  12898. decay: 0
  12899. };
  12900. break;
  12901. case 'PointLight':
  12902. uniforms = {
  12903. position: new Vector3(),
  12904. color: new Color(),
  12905. distance: 0,
  12906. decay: 0
  12907. };
  12908. break;
  12909. case 'HemisphereLight':
  12910. uniforms = {
  12911. direction: new Vector3(),
  12912. skyColor: new Color(),
  12913. groundColor: new Color()
  12914. };
  12915. break;
  12916. case 'RectAreaLight':
  12917. uniforms = {
  12918. color: new Color(),
  12919. position: new Vector3(),
  12920. halfWidth: new Vector3(),
  12921. halfHeight: new Vector3()
  12922. };
  12923. break;
  12924. }
  12925. lights[ light.id ] = uniforms;
  12926. return uniforms;
  12927. }
  12928. };
  12929. }
  12930. function ShadowUniformsCache() {
  12931. const lights = {};
  12932. return {
  12933. get: function ( light ) {
  12934. if ( lights[ light.id ] !== undefined ) {
  12935. return lights[ light.id ];
  12936. }
  12937. let uniforms;
  12938. switch ( light.type ) {
  12939. case 'DirectionalLight':
  12940. uniforms = {
  12941. shadowBias: 0,
  12942. shadowNormalBias: 0,
  12943. shadowRadius: 1,
  12944. shadowMapSize: new Vector2()
  12945. };
  12946. break;
  12947. case 'SpotLight':
  12948. uniforms = {
  12949. shadowBias: 0,
  12950. shadowNormalBias: 0,
  12951. shadowRadius: 1,
  12952. shadowMapSize: new Vector2()
  12953. };
  12954. break;
  12955. case 'PointLight':
  12956. uniforms = {
  12957. shadowBias: 0,
  12958. shadowNormalBias: 0,
  12959. shadowRadius: 1,
  12960. shadowMapSize: new Vector2(),
  12961. shadowCameraNear: 1,
  12962. shadowCameraFar: 1000
  12963. };
  12964. break;
  12965. // TODO (abelnation): set RectAreaLight shadow uniforms
  12966. }
  12967. lights[ light.id ] = uniforms;
  12968. return uniforms;
  12969. }
  12970. };
  12971. }
  12972. let nextVersion = 0;
  12973. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12974. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12975. }
  12976. function WebGLLights( extensions ) {
  12977. const cache = new UniformsCache();
  12978. const shadowCache = ShadowUniformsCache();
  12979. const state = {
  12980. version: 0,
  12981. hash: {
  12982. directionalLength: - 1,
  12983. pointLength: - 1,
  12984. spotLength: - 1,
  12985. rectAreaLength: - 1,
  12986. hemiLength: - 1,
  12987. numDirectionalShadows: - 1,
  12988. numPointShadows: - 1,
  12989. numSpotShadows: - 1,
  12990. numSpotMaps: - 1,
  12991. numLightProbes: - 1
  12992. },
  12993. ambient: [ 0, 0, 0 ],
  12994. probe: [],
  12995. directional: [],
  12996. directionalShadow: [],
  12997. directionalShadowMap: [],
  12998. directionalShadowMatrix: [],
  12999. spot: [],
  13000. spotLightMap: [],
  13001. spotShadow: [],
  13002. spotShadowMap: [],
  13003. spotLightMatrix: [],
  13004. rectArea: [],
  13005. rectAreaLTC1: null,
  13006. rectAreaLTC2: null,
  13007. point: [],
  13008. pointShadow: [],
  13009. pointShadowMap: [],
  13010. pointShadowMatrix: [],
  13011. hemi: [],
  13012. numSpotLightShadowsWithMaps: 0,
  13013. numLightProbes: 0
  13014. };
  13015. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  13016. const vector3 = new Vector3();
  13017. const matrix4 = new Matrix4();
  13018. const matrix42 = new Matrix4();
  13019. function setup( lights ) {
  13020. let r = 0, g = 0, b = 0;
  13021. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  13022. let directionalLength = 0;
  13023. let pointLength = 0;
  13024. let spotLength = 0;
  13025. let rectAreaLength = 0;
  13026. let hemiLength = 0;
  13027. let numDirectionalShadows = 0;
  13028. let numPointShadows = 0;
  13029. let numSpotShadows = 0;
  13030. let numSpotMaps = 0;
  13031. let numSpotShadowsWithMaps = 0;
  13032. let numLightProbes = 0;
  13033. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  13034. lights.sort( shadowCastingAndTexturingLightsFirst );
  13035. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13036. const light = lights[ i ];
  13037. const color = light.color;
  13038. const intensity = light.intensity;
  13039. const distance = light.distance;
  13040. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13041. if ( light.isAmbientLight ) {
  13042. r += color.r * intensity;
  13043. g += color.g * intensity;
  13044. b += color.b * intensity;
  13045. } else if ( light.isLightProbe ) {
  13046. for ( let j = 0; j < 9; j ++ ) {
  13047. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  13048. }
  13049. numLightProbes ++;
  13050. } else if ( light.isDirectionalLight ) {
  13051. const uniforms = cache.get( light );
  13052. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13053. if ( light.castShadow ) {
  13054. const shadow = light.shadow;
  13055. const shadowUniforms = shadowCache.get( light );
  13056. shadowUniforms.shadowBias = shadow.bias;
  13057. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13058. shadowUniforms.shadowRadius = shadow.radius;
  13059. shadowUniforms.shadowMapSize = shadow.mapSize;
  13060. state.directionalShadow[ directionalLength ] = shadowUniforms;
  13061. state.directionalShadowMap[ directionalLength ] = shadowMap;
  13062. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13063. numDirectionalShadows ++;
  13064. }
  13065. state.directional[ directionalLength ] = uniforms;
  13066. directionalLength ++;
  13067. } else if ( light.isSpotLight ) {
  13068. const uniforms = cache.get( light );
  13069. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13070. uniforms.color.copy( color ).multiplyScalar( intensity );
  13071. uniforms.distance = distance;
  13072. uniforms.coneCos = Math.cos( light.angle );
  13073. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13074. uniforms.decay = light.decay;
  13075. state.spot[ spotLength ] = uniforms;
  13076. const shadow = light.shadow;
  13077. if ( light.map ) {
  13078. state.spotLightMap[ numSpotMaps ] = light.map;
  13079. numSpotMaps ++;
  13080. // make sure the lightMatrix is up to date
  13081. // TODO : do it if required only
  13082. shadow.updateMatrices( light );
  13083. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  13084. }
  13085. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  13086. if ( light.castShadow ) {
  13087. const shadowUniforms = shadowCache.get( light );
  13088. shadowUniforms.shadowBias = shadow.bias;
  13089. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13090. shadowUniforms.shadowRadius = shadow.radius;
  13091. shadowUniforms.shadowMapSize = shadow.mapSize;
  13092. state.spotShadow[ spotLength ] = shadowUniforms;
  13093. state.spotShadowMap[ spotLength ] = shadowMap;
  13094. numSpotShadows ++;
  13095. }
  13096. spotLength ++;
  13097. } else if ( light.isRectAreaLight ) {
  13098. const uniforms = cache.get( light );
  13099. uniforms.color.copy( color ).multiplyScalar( intensity );
  13100. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13101. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13102. state.rectArea[ rectAreaLength ] = uniforms;
  13103. rectAreaLength ++;
  13104. } else if ( light.isPointLight ) {
  13105. const uniforms = cache.get( light );
  13106. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  13107. uniforms.distance = light.distance;
  13108. uniforms.decay = light.decay;
  13109. if ( light.castShadow ) {
  13110. const shadow = light.shadow;
  13111. const shadowUniforms = shadowCache.get( light );
  13112. shadowUniforms.shadowBias = shadow.bias;
  13113. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13114. shadowUniforms.shadowRadius = shadow.radius;
  13115. shadowUniforms.shadowMapSize = shadow.mapSize;
  13116. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13117. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13118. state.pointShadow[ pointLength ] = shadowUniforms;
  13119. state.pointShadowMap[ pointLength ] = shadowMap;
  13120. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13121. numPointShadows ++;
  13122. }
  13123. state.point[ pointLength ] = uniforms;
  13124. pointLength ++;
  13125. } else if ( light.isHemisphereLight ) {
  13126. const uniforms = cache.get( light );
  13127. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  13128. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  13129. state.hemi[ hemiLength ] = uniforms;
  13130. hemiLength ++;
  13131. }
  13132. }
  13133. if ( rectAreaLength > 0 ) {
  13134. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13135. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13136. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13137. } else {
  13138. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13139. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13140. }
  13141. }
  13142. state.ambient[ 0 ] = r;
  13143. state.ambient[ 1 ] = g;
  13144. state.ambient[ 2 ] = b;
  13145. const hash = state.hash;
  13146. if ( hash.directionalLength !== directionalLength ||
  13147. hash.pointLength !== pointLength ||
  13148. hash.spotLength !== spotLength ||
  13149. hash.rectAreaLength !== rectAreaLength ||
  13150. hash.hemiLength !== hemiLength ||
  13151. hash.numDirectionalShadows !== numDirectionalShadows ||
  13152. hash.numPointShadows !== numPointShadows ||
  13153. hash.numSpotShadows !== numSpotShadows ||
  13154. hash.numSpotMaps !== numSpotMaps ||
  13155. hash.numLightProbes !== numLightProbes ) {
  13156. state.directional.length = directionalLength;
  13157. state.spot.length = spotLength;
  13158. state.rectArea.length = rectAreaLength;
  13159. state.point.length = pointLength;
  13160. state.hemi.length = hemiLength;
  13161. state.directionalShadow.length = numDirectionalShadows;
  13162. state.directionalShadowMap.length = numDirectionalShadows;
  13163. state.pointShadow.length = numPointShadows;
  13164. state.pointShadowMap.length = numPointShadows;
  13165. state.spotShadow.length = numSpotShadows;
  13166. state.spotShadowMap.length = numSpotShadows;
  13167. state.directionalShadowMatrix.length = numDirectionalShadows;
  13168. state.pointShadowMatrix.length = numPointShadows;
  13169. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13170. state.spotLightMap.length = numSpotMaps;
  13171. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13172. state.numLightProbes = numLightProbes;
  13173. hash.directionalLength = directionalLength;
  13174. hash.pointLength = pointLength;
  13175. hash.spotLength = spotLength;
  13176. hash.rectAreaLength = rectAreaLength;
  13177. hash.hemiLength = hemiLength;
  13178. hash.numDirectionalShadows = numDirectionalShadows;
  13179. hash.numPointShadows = numPointShadows;
  13180. hash.numSpotShadows = numSpotShadows;
  13181. hash.numSpotMaps = numSpotMaps;
  13182. hash.numLightProbes = numLightProbes;
  13183. state.version = nextVersion ++;
  13184. }
  13185. }
  13186. function setupView( lights, camera ) {
  13187. let directionalLength = 0;
  13188. let pointLength = 0;
  13189. let spotLength = 0;
  13190. let rectAreaLength = 0;
  13191. let hemiLength = 0;
  13192. const viewMatrix = camera.matrixWorldInverse;
  13193. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13194. const light = lights[ i ];
  13195. if ( light.isDirectionalLight ) {
  13196. const uniforms = state.directional[ directionalLength ];
  13197. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13198. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13199. uniforms.direction.sub( vector3 );
  13200. uniforms.direction.transformDirection( viewMatrix );
  13201. directionalLength ++;
  13202. } else if ( light.isSpotLight ) {
  13203. const uniforms = state.spot[ spotLength ];
  13204. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13205. uniforms.position.applyMatrix4( viewMatrix );
  13206. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13207. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13208. uniforms.direction.sub( vector3 );
  13209. uniforms.direction.transformDirection( viewMatrix );
  13210. spotLength ++;
  13211. } else if ( light.isRectAreaLight ) {
  13212. const uniforms = state.rectArea[ rectAreaLength ];
  13213. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13214. uniforms.position.applyMatrix4( viewMatrix );
  13215. // extract local rotation of light to derive width/height half vectors
  13216. matrix42.identity();
  13217. matrix4.copy( light.matrixWorld );
  13218. matrix4.premultiply( viewMatrix );
  13219. matrix42.extractRotation( matrix4 );
  13220. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13221. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13222. uniforms.halfWidth.applyMatrix4( matrix42 );
  13223. uniforms.halfHeight.applyMatrix4( matrix42 );
  13224. rectAreaLength ++;
  13225. } else if ( light.isPointLight ) {
  13226. const uniforms = state.point[ pointLength ];
  13227. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13228. uniforms.position.applyMatrix4( viewMatrix );
  13229. pointLength ++;
  13230. } else if ( light.isHemisphereLight ) {
  13231. const uniforms = state.hemi[ hemiLength ];
  13232. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13233. uniforms.direction.transformDirection( viewMatrix );
  13234. hemiLength ++;
  13235. }
  13236. }
  13237. }
  13238. return {
  13239. setup: setup,
  13240. setupView: setupView,
  13241. state: state
  13242. };
  13243. }
  13244. function WebGLRenderState( extensions ) {
  13245. const lights = new WebGLLights( extensions );
  13246. const lightsArray = [];
  13247. const shadowsArray = [];
  13248. function init( camera ) {
  13249. state.camera = camera;
  13250. lightsArray.length = 0;
  13251. shadowsArray.length = 0;
  13252. }
  13253. function pushLight( light ) {
  13254. lightsArray.push( light );
  13255. }
  13256. function pushShadow( shadowLight ) {
  13257. shadowsArray.push( shadowLight );
  13258. }
  13259. function setupLights() {
  13260. lights.setup( lightsArray );
  13261. }
  13262. function setupLightsView( camera ) {
  13263. lights.setupView( lightsArray, camera );
  13264. }
  13265. const state = {
  13266. lightsArray: lightsArray,
  13267. shadowsArray: shadowsArray,
  13268. camera: null,
  13269. lights: lights,
  13270. transmissionRenderTarget: {}
  13271. };
  13272. return {
  13273. init: init,
  13274. state: state,
  13275. setupLights: setupLights,
  13276. setupLightsView: setupLightsView,
  13277. pushLight: pushLight,
  13278. pushShadow: pushShadow
  13279. };
  13280. }
  13281. function WebGLRenderStates( extensions ) {
  13282. let renderStates = new WeakMap();
  13283. function get( scene, renderCallDepth = 0 ) {
  13284. const renderStateArray = renderStates.get( scene );
  13285. let renderState;
  13286. if ( renderStateArray === undefined ) {
  13287. renderState = new WebGLRenderState( extensions );
  13288. renderStates.set( scene, [ renderState ] );
  13289. } else {
  13290. if ( renderCallDepth >= renderStateArray.length ) {
  13291. renderState = new WebGLRenderState( extensions );
  13292. renderStateArray.push( renderState );
  13293. } else {
  13294. renderState = renderStateArray[ renderCallDepth ];
  13295. }
  13296. }
  13297. return renderState;
  13298. }
  13299. function dispose() {
  13300. renderStates = new WeakMap();
  13301. }
  13302. return {
  13303. get: get,
  13304. dispose: dispose
  13305. };
  13306. }
  13307. class MeshDepthMaterial extends Material {
  13308. constructor( parameters ) {
  13309. super();
  13310. this.isMeshDepthMaterial = true;
  13311. this.type = 'MeshDepthMaterial';
  13312. this.depthPacking = BasicDepthPacking;
  13313. this.map = null;
  13314. this.alphaMap = null;
  13315. this.displacementMap = null;
  13316. this.displacementScale = 1;
  13317. this.displacementBias = 0;
  13318. this.wireframe = false;
  13319. this.wireframeLinewidth = 1;
  13320. this.setValues( parameters );
  13321. }
  13322. copy( source ) {
  13323. super.copy( source );
  13324. this.depthPacking = source.depthPacking;
  13325. this.map = source.map;
  13326. this.alphaMap = source.alphaMap;
  13327. this.displacementMap = source.displacementMap;
  13328. this.displacementScale = source.displacementScale;
  13329. this.displacementBias = source.displacementBias;
  13330. this.wireframe = source.wireframe;
  13331. this.wireframeLinewidth = source.wireframeLinewidth;
  13332. return this;
  13333. }
  13334. }
  13335. class MeshDistanceMaterial extends Material {
  13336. constructor( parameters ) {
  13337. super();
  13338. this.isMeshDistanceMaterial = true;
  13339. this.type = 'MeshDistanceMaterial';
  13340. this.map = null;
  13341. this.alphaMap = null;
  13342. this.displacementMap = null;
  13343. this.displacementScale = 1;
  13344. this.displacementBias = 0;
  13345. this.setValues( parameters );
  13346. }
  13347. copy( source ) {
  13348. super.copy( source );
  13349. this.map = source.map;
  13350. this.alphaMap = source.alphaMap;
  13351. this.displacementMap = source.displacementMap;
  13352. this.displacementScale = source.displacementScale;
  13353. this.displacementBias = source.displacementBias;
  13354. return this;
  13355. }
  13356. }
  13357. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13358. 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}";
  13359. function WebGLShadowMap( renderer, objects, capabilities ) {
  13360. let _frustum = new Frustum();
  13361. const _shadowMapSize = new Vector2(),
  13362. _viewportSize = new Vector2(),
  13363. _viewport = new Vector4(),
  13364. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13365. _distanceMaterial = new MeshDistanceMaterial(),
  13366. _materialCache = {},
  13367. _maxTextureSize = capabilities.maxTextureSize;
  13368. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13369. const shadowMaterialVertical = new ShaderMaterial( {
  13370. defines: {
  13371. VSM_SAMPLES: 8
  13372. },
  13373. uniforms: {
  13374. shadow_pass: { value: null },
  13375. resolution: { value: new Vector2() },
  13376. radius: { value: 4.0 }
  13377. },
  13378. vertexShader: vertex,
  13379. fragmentShader: fragment
  13380. } );
  13381. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13382. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13383. const fullScreenTri = new BufferGeometry();
  13384. fullScreenTri.setAttribute(
  13385. 'position',
  13386. new BufferAttribute(
  13387. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13388. 3
  13389. )
  13390. );
  13391. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13392. const scope = this;
  13393. this.enabled = false;
  13394. this.autoUpdate = true;
  13395. this.needsUpdate = false;
  13396. this.type = PCFShadowMap;
  13397. let _previousType = this.type;
  13398. this.render = function ( lights, scene, camera ) {
  13399. if ( scope.enabled === false ) return;
  13400. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13401. if ( lights.length === 0 ) return;
  13402. const currentRenderTarget = renderer.getRenderTarget();
  13403. const activeCubeFace = renderer.getActiveCubeFace();
  13404. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  13405. const _state = renderer.state;
  13406. // Set GL state for depth map.
  13407. _state.setBlending( NoBlending );
  13408. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13409. _state.buffers.depth.setTest( true );
  13410. _state.setScissorTest( false );
  13411. // check for shadow map type changes
  13412. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13413. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13414. // render depth map
  13415. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13416. const light = lights[ i ];
  13417. const shadow = light.shadow;
  13418. if ( shadow === undefined ) {
  13419. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13420. continue;
  13421. }
  13422. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13423. _shadowMapSize.copy( shadow.mapSize );
  13424. const shadowFrameExtents = shadow.getFrameExtents();
  13425. _shadowMapSize.multiply( shadowFrameExtents );
  13426. _viewportSize.copy( shadow.mapSize );
  13427. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13428. if ( _shadowMapSize.x > _maxTextureSize ) {
  13429. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13430. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13431. shadow.mapSize.x = _viewportSize.x;
  13432. }
  13433. if ( _shadowMapSize.y > _maxTextureSize ) {
  13434. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13435. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13436. shadow.mapSize.y = _viewportSize.y;
  13437. }
  13438. }
  13439. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13440. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13441. if ( shadow.map !== null ) {
  13442. shadow.map.dispose();
  13443. }
  13444. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13445. shadow.map.texture.name = light.name + '.shadowMap';
  13446. shadow.camera.updateProjectionMatrix();
  13447. }
  13448. renderer.setRenderTarget( shadow.map );
  13449. renderer.clear();
  13450. const viewportCount = shadow.getViewportCount();
  13451. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13452. const viewport = shadow.getViewport( vp );
  13453. _viewport.set(
  13454. _viewportSize.x * viewport.x,
  13455. _viewportSize.y * viewport.y,
  13456. _viewportSize.x * viewport.z,
  13457. _viewportSize.y * viewport.w
  13458. );
  13459. _state.viewport( _viewport );
  13460. shadow.updateMatrices( light, vp );
  13461. _frustum = shadow.getFrustum();
  13462. renderObject( scene, camera, shadow.camera, light, this.type );
  13463. }
  13464. // do blur pass for VSM
  13465. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13466. VSMPass( shadow, camera );
  13467. }
  13468. shadow.needsUpdate = false;
  13469. }
  13470. _previousType = this.type;
  13471. scope.needsUpdate = false;
  13472. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13473. };
  13474. function VSMPass( shadow, camera ) {
  13475. const geometry = objects.update( fullScreenMesh );
  13476. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13477. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13478. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13479. shadowMaterialVertical.needsUpdate = true;
  13480. shadowMaterialHorizontal.needsUpdate = true;
  13481. }
  13482. if ( shadow.mapPass === null ) {
  13483. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13484. }
  13485. // vertical pass
  13486. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13487. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13488. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13489. renderer.setRenderTarget( shadow.mapPass );
  13490. renderer.clear();
  13491. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13492. // horizontal pass
  13493. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13494. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13495. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13496. renderer.setRenderTarget( shadow.map );
  13497. renderer.clear();
  13498. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13499. }
  13500. function getDepthMaterial( object, material, light, type ) {
  13501. let result = null;
  13502. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13503. if ( customMaterial !== undefined ) {
  13504. result = customMaterial;
  13505. } else {
  13506. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13507. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13508. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13509. ( material.alphaMap && material.alphaTest > 0 ) ||
  13510. ( material.map && material.alphaTest > 0 ) ) {
  13511. // in this case we need a unique material instance reflecting the
  13512. // appropriate state
  13513. const keyA = result.uuid, keyB = material.uuid;
  13514. let materialsForVariant = _materialCache[ keyA ];
  13515. if ( materialsForVariant === undefined ) {
  13516. materialsForVariant = {};
  13517. _materialCache[ keyA ] = materialsForVariant;
  13518. }
  13519. let cachedMaterial = materialsForVariant[ keyB ];
  13520. if ( cachedMaterial === undefined ) {
  13521. cachedMaterial = result.clone();
  13522. materialsForVariant[ keyB ] = cachedMaterial;
  13523. material.addEventListener( 'dispose', onMaterialDispose );
  13524. }
  13525. result = cachedMaterial;
  13526. }
  13527. }
  13528. result.visible = material.visible;
  13529. result.wireframe = material.wireframe;
  13530. if ( type === VSMShadowMap ) {
  13531. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13532. } else {
  13533. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13534. }
  13535. result.alphaMap = material.alphaMap;
  13536. result.alphaTest = material.alphaTest;
  13537. result.map = material.map;
  13538. result.clipShadows = material.clipShadows;
  13539. result.clippingPlanes = material.clippingPlanes;
  13540. result.clipIntersection = material.clipIntersection;
  13541. result.displacementMap = material.displacementMap;
  13542. result.displacementScale = material.displacementScale;
  13543. result.displacementBias = material.displacementBias;
  13544. result.wireframeLinewidth = material.wireframeLinewidth;
  13545. result.linewidth = material.linewidth;
  13546. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13547. const materialProperties = renderer.properties.get( result );
  13548. materialProperties.light = light;
  13549. }
  13550. return result;
  13551. }
  13552. function renderObject( object, camera, shadowCamera, light, type ) {
  13553. if ( object.visible === false ) return;
  13554. const visible = object.layers.test( camera.layers );
  13555. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13556. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13557. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13558. const geometry = objects.update( object );
  13559. const material = object.material;
  13560. if ( Array.isArray( material ) ) {
  13561. const groups = geometry.groups;
  13562. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13563. const group = groups[ k ];
  13564. const groupMaterial = material[ group.materialIndex ];
  13565. if ( groupMaterial && groupMaterial.visible ) {
  13566. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13567. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13568. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13569. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13570. }
  13571. }
  13572. } else if ( material.visible ) {
  13573. const depthMaterial = getDepthMaterial( object, material, light, type );
  13574. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13575. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13576. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13577. }
  13578. }
  13579. }
  13580. const children = object.children;
  13581. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13582. renderObject( children[ i ], camera, shadowCamera, light, type );
  13583. }
  13584. }
  13585. function onMaterialDispose( event ) {
  13586. const material = event.target;
  13587. material.removeEventListener( 'dispose', onMaterialDispose );
  13588. // make sure to remove the unique distance/depth materials used for shadow map rendering
  13589. for ( const id in _materialCache ) {
  13590. const cache = _materialCache[ id ];
  13591. const uuid = event.target.uuid;
  13592. if ( uuid in cache ) {
  13593. const shadowMaterial = cache[ uuid ];
  13594. shadowMaterial.dispose();
  13595. delete cache[ uuid ];
  13596. }
  13597. }
  13598. }
  13599. }
  13600. function WebGLState( gl ) {
  13601. function ColorBuffer() {
  13602. let locked = false;
  13603. const color = new Vector4();
  13604. let currentColorMask = null;
  13605. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13606. return {
  13607. setMask: function ( colorMask ) {
  13608. if ( currentColorMask !== colorMask && ! locked ) {
  13609. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13610. currentColorMask = colorMask;
  13611. }
  13612. },
  13613. setLocked: function ( lock ) {
  13614. locked = lock;
  13615. },
  13616. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13617. if ( premultipliedAlpha === true ) {
  13618. r *= a; g *= a; b *= a;
  13619. }
  13620. color.set( r, g, b, a );
  13621. if ( currentColorClear.equals( color ) === false ) {
  13622. gl.clearColor( r, g, b, a );
  13623. currentColorClear.copy( color );
  13624. }
  13625. },
  13626. reset: function () {
  13627. locked = false;
  13628. currentColorMask = null;
  13629. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13630. }
  13631. };
  13632. }
  13633. function DepthBuffer() {
  13634. let locked = false;
  13635. let currentDepthMask = null;
  13636. let currentDepthFunc = null;
  13637. let currentDepthClear = null;
  13638. return {
  13639. setTest: function ( depthTest ) {
  13640. if ( depthTest ) {
  13641. enable( gl.DEPTH_TEST );
  13642. } else {
  13643. disable( gl.DEPTH_TEST );
  13644. }
  13645. },
  13646. setMask: function ( depthMask ) {
  13647. if ( currentDepthMask !== depthMask && ! locked ) {
  13648. gl.depthMask( depthMask );
  13649. currentDepthMask = depthMask;
  13650. }
  13651. },
  13652. setFunc: function ( depthFunc ) {
  13653. if ( currentDepthFunc !== depthFunc ) {
  13654. switch ( depthFunc ) {
  13655. case NeverDepth:
  13656. gl.depthFunc( gl.NEVER );
  13657. break;
  13658. case AlwaysDepth:
  13659. gl.depthFunc( gl.ALWAYS );
  13660. break;
  13661. case LessDepth:
  13662. gl.depthFunc( gl.LESS );
  13663. break;
  13664. case LessEqualDepth:
  13665. gl.depthFunc( gl.LEQUAL );
  13666. break;
  13667. case EqualDepth:
  13668. gl.depthFunc( gl.EQUAL );
  13669. break;
  13670. case GreaterEqualDepth:
  13671. gl.depthFunc( gl.GEQUAL );
  13672. break;
  13673. case GreaterDepth:
  13674. gl.depthFunc( gl.GREATER );
  13675. break;
  13676. case NotEqualDepth:
  13677. gl.depthFunc( gl.NOTEQUAL );
  13678. break;
  13679. default:
  13680. gl.depthFunc( gl.LEQUAL );
  13681. }
  13682. currentDepthFunc = depthFunc;
  13683. }
  13684. },
  13685. setLocked: function ( lock ) {
  13686. locked = lock;
  13687. },
  13688. setClear: function ( depth ) {
  13689. if ( currentDepthClear !== depth ) {
  13690. gl.clearDepth( depth );
  13691. currentDepthClear = depth;
  13692. }
  13693. },
  13694. reset: function () {
  13695. locked = false;
  13696. currentDepthMask = null;
  13697. currentDepthFunc = null;
  13698. currentDepthClear = null;
  13699. }
  13700. };
  13701. }
  13702. function StencilBuffer() {
  13703. let locked = false;
  13704. let currentStencilMask = null;
  13705. let currentStencilFunc = null;
  13706. let currentStencilRef = null;
  13707. let currentStencilFuncMask = null;
  13708. let currentStencilFail = null;
  13709. let currentStencilZFail = null;
  13710. let currentStencilZPass = null;
  13711. let currentStencilClear = null;
  13712. return {
  13713. setTest: function ( stencilTest ) {
  13714. if ( ! locked ) {
  13715. if ( stencilTest ) {
  13716. enable( gl.STENCIL_TEST );
  13717. } else {
  13718. disable( gl.STENCIL_TEST );
  13719. }
  13720. }
  13721. },
  13722. setMask: function ( stencilMask ) {
  13723. if ( currentStencilMask !== stencilMask && ! locked ) {
  13724. gl.stencilMask( stencilMask );
  13725. currentStencilMask = stencilMask;
  13726. }
  13727. },
  13728. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13729. if ( currentStencilFunc !== stencilFunc ||
  13730. currentStencilRef !== stencilRef ||
  13731. currentStencilFuncMask !== stencilMask ) {
  13732. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13733. currentStencilFunc = stencilFunc;
  13734. currentStencilRef = stencilRef;
  13735. currentStencilFuncMask = stencilMask;
  13736. }
  13737. },
  13738. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13739. if ( currentStencilFail !== stencilFail ||
  13740. currentStencilZFail !== stencilZFail ||
  13741. currentStencilZPass !== stencilZPass ) {
  13742. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13743. currentStencilFail = stencilFail;
  13744. currentStencilZFail = stencilZFail;
  13745. currentStencilZPass = stencilZPass;
  13746. }
  13747. },
  13748. setLocked: function ( lock ) {
  13749. locked = lock;
  13750. },
  13751. setClear: function ( stencil ) {
  13752. if ( currentStencilClear !== stencil ) {
  13753. gl.clearStencil( stencil );
  13754. currentStencilClear = stencil;
  13755. }
  13756. },
  13757. reset: function () {
  13758. locked = false;
  13759. currentStencilMask = null;
  13760. currentStencilFunc = null;
  13761. currentStencilRef = null;
  13762. currentStencilFuncMask = null;
  13763. currentStencilFail = null;
  13764. currentStencilZFail = null;
  13765. currentStencilZPass = null;
  13766. currentStencilClear = null;
  13767. }
  13768. };
  13769. }
  13770. //
  13771. const colorBuffer = new ColorBuffer();
  13772. const depthBuffer = new DepthBuffer();
  13773. const stencilBuffer = new StencilBuffer();
  13774. const uboBindings = new WeakMap();
  13775. const uboProgramMap = new WeakMap();
  13776. let enabledCapabilities = {};
  13777. let currentBoundFramebuffers = {};
  13778. let currentDrawbuffers = new WeakMap();
  13779. let defaultDrawbuffers = [];
  13780. let currentProgram = null;
  13781. let currentBlendingEnabled = false;
  13782. let currentBlending = null;
  13783. let currentBlendEquation = null;
  13784. let currentBlendSrc = null;
  13785. let currentBlendDst = null;
  13786. let currentBlendEquationAlpha = null;
  13787. let currentBlendSrcAlpha = null;
  13788. let currentBlendDstAlpha = null;
  13789. let currentBlendColor = new Color( 0, 0, 0 );
  13790. let currentBlendAlpha = 0;
  13791. let currentPremultipledAlpha = false;
  13792. let currentFlipSided = null;
  13793. let currentCullFace = null;
  13794. let currentLineWidth = null;
  13795. let currentPolygonOffsetFactor = null;
  13796. let currentPolygonOffsetUnits = null;
  13797. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13798. let lineWidthAvailable = false;
  13799. let version = 0;
  13800. const glVersion = gl.getParameter( gl.VERSION );
  13801. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13802. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13803. lineWidthAvailable = ( version >= 1.0 );
  13804. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13805. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13806. lineWidthAvailable = ( version >= 2.0 );
  13807. }
  13808. let currentTextureSlot = null;
  13809. let currentBoundTextures = {};
  13810. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13811. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13812. const currentScissor = new Vector4().fromArray( scissorParam );
  13813. const currentViewport = new Vector4().fromArray( viewportParam );
  13814. function createTexture( type, target, count, dimensions ) {
  13815. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13816. const texture = gl.createTexture();
  13817. gl.bindTexture( type, texture );
  13818. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13819. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13820. for ( let i = 0; i < count; i ++ ) {
  13821. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  13822. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13823. } else {
  13824. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13825. }
  13826. }
  13827. return texture;
  13828. }
  13829. const emptyTextures = {};
  13830. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13831. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13832. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13833. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13834. // init
  13835. colorBuffer.setClear( 0, 0, 0, 1 );
  13836. depthBuffer.setClear( 1 );
  13837. stencilBuffer.setClear( 0 );
  13838. enable( gl.DEPTH_TEST );
  13839. depthBuffer.setFunc( LessEqualDepth );
  13840. setFlipSided( false );
  13841. setCullFace( CullFaceBack );
  13842. enable( gl.CULL_FACE );
  13843. setBlending( NoBlending );
  13844. //
  13845. function enable( id ) {
  13846. if ( enabledCapabilities[ id ] !== true ) {
  13847. gl.enable( id );
  13848. enabledCapabilities[ id ] = true;
  13849. }
  13850. }
  13851. function disable( id ) {
  13852. if ( enabledCapabilities[ id ] !== false ) {
  13853. gl.disable( id );
  13854. enabledCapabilities[ id ] = false;
  13855. }
  13856. }
  13857. function bindFramebuffer( target, framebuffer ) {
  13858. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13859. gl.bindFramebuffer( target, framebuffer );
  13860. currentBoundFramebuffers[ target ] = framebuffer;
  13861. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13862. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13863. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13864. }
  13865. if ( target === gl.FRAMEBUFFER ) {
  13866. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13867. }
  13868. return true;
  13869. }
  13870. return false;
  13871. }
  13872. function drawBuffers( renderTarget, framebuffer ) {
  13873. let drawBuffers = defaultDrawbuffers;
  13874. let needsUpdate = false;
  13875. if ( renderTarget ) {
  13876. drawBuffers = currentDrawbuffers.get( framebuffer );
  13877. if ( drawBuffers === undefined ) {
  13878. drawBuffers = [];
  13879. currentDrawbuffers.set( framebuffer, drawBuffers );
  13880. }
  13881. const textures = renderTarget.textures;
  13882. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13883. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13884. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13885. }
  13886. drawBuffers.length = textures.length;
  13887. needsUpdate = true;
  13888. }
  13889. } else {
  13890. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13891. drawBuffers[ 0 ] = gl.BACK;
  13892. needsUpdate = true;
  13893. }
  13894. }
  13895. if ( needsUpdate ) {
  13896. gl.drawBuffers( drawBuffers );
  13897. }
  13898. }
  13899. function useProgram( program ) {
  13900. if ( currentProgram !== program ) {
  13901. gl.useProgram( program );
  13902. currentProgram = program;
  13903. return true;
  13904. }
  13905. return false;
  13906. }
  13907. const equationToGL = {
  13908. [ AddEquation ]: gl.FUNC_ADD,
  13909. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13910. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13911. };
  13912. equationToGL[ MinEquation ] = gl.MIN;
  13913. equationToGL[ MaxEquation ] = gl.MAX;
  13914. const factorToGL = {
  13915. [ ZeroFactor ]: gl.ZERO,
  13916. [ OneFactor ]: gl.ONE,
  13917. [ SrcColorFactor ]: gl.SRC_COLOR,
  13918. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13919. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13920. [ DstColorFactor ]: gl.DST_COLOR,
  13921. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13922. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13923. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13924. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13925. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  13926. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  13927. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  13928. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  13929. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  13930. };
  13931. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  13932. if ( blending === NoBlending ) {
  13933. if ( currentBlendingEnabled === true ) {
  13934. disable( gl.BLEND );
  13935. currentBlendingEnabled = false;
  13936. }
  13937. return;
  13938. }
  13939. if ( currentBlendingEnabled === false ) {
  13940. enable( gl.BLEND );
  13941. currentBlendingEnabled = true;
  13942. }
  13943. if ( blending !== CustomBlending ) {
  13944. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13945. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13946. gl.blendEquation( gl.FUNC_ADD );
  13947. currentBlendEquation = AddEquation;
  13948. currentBlendEquationAlpha = AddEquation;
  13949. }
  13950. if ( premultipliedAlpha ) {
  13951. switch ( blending ) {
  13952. case NormalBlending:
  13953. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13954. break;
  13955. case AdditiveBlending:
  13956. gl.blendFunc( gl.ONE, gl.ONE );
  13957. break;
  13958. case SubtractiveBlending:
  13959. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13960. break;
  13961. case MultiplyBlending:
  13962. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13963. break;
  13964. default:
  13965. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13966. break;
  13967. }
  13968. } else {
  13969. switch ( blending ) {
  13970. case NormalBlending:
  13971. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13972. break;
  13973. case AdditiveBlending:
  13974. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13975. break;
  13976. case SubtractiveBlending:
  13977. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13978. break;
  13979. case MultiplyBlending:
  13980. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13981. break;
  13982. default:
  13983. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13984. break;
  13985. }
  13986. }
  13987. currentBlendSrc = null;
  13988. currentBlendDst = null;
  13989. currentBlendSrcAlpha = null;
  13990. currentBlendDstAlpha = null;
  13991. currentBlendColor.set( 0, 0, 0 );
  13992. currentBlendAlpha = 0;
  13993. currentBlending = blending;
  13994. currentPremultipledAlpha = premultipliedAlpha;
  13995. }
  13996. return;
  13997. }
  13998. // custom blending
  13999. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14000. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14001. blendDstAlpha = blendDstAlpha || blendDst;
  14002. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14003. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  14004. currentBlendEquation = blendEquation;
  14005. currentBlendEquationAlpha = blendEquationAlpha;
  14006. }
  14007. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14008. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  14009. currentBlendSrc = blendSrc;
  14010. currentBlendDst = blendDst;
  14011. currentBlendSrcAlpha = blendSrcAlpha;
  14012. currentBlendDstAlpha = blendDstAlpha;
  14013. }
  14014. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  14015. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  14016. currentBlendColor.copy( blendColor );
  14017. currentBlendAlpha = blendAlpha;
  14018. }
  14019. currentBlending = blending;
  14020. currentPremultipledAlpha = false;
  14021. }
  14022. function setMaterial( material, frontFaceCW ) {
  14023. material.side === DoubleSide
  14024. ? disable( gl.CULL_FACE )
  14025. : enable( gl.CULL_FACE );
  14026. let flipSided = ( material.side === BackSide );
  14027. if ( frontFaceCW ) flipSided = ! flipSided;
  14028. setFlipSided( flipSided );
  14029. ( material.blending === NormalBlending && material.transparent === false )
  14030. ? setBlending( NoBlending )
  14031. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  14032. depthBuffer.setFunc( material.depthFunc );
  14033. depthBuffer.setTest( material.depthTest );
  14034. depthBuffer.setMask( material.depthWrite );
  14035. colorBuffer.setMask( material.colorWrite );
  14036. const stencilWrite = material.stencilWrite;
  14037. stencilBuffer.setTest( stencilWrite );
  14038. if ( stencilWrite ) {
  14039. stencilBuffer.setMask( material.stencilWriteMask );
  14040. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  14041. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  14042. }
  14043. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14044. material.alphaToCoverage === true
  14045. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  14046. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14047. }
  14048. //
  14049. function setFlipSided( flipSided ) {
  14050. if ( currentFlipSided !== flipSided ) {
  14051. if ( flipSided ) {
  14052. gl.frontFace( gl.CW );
  14053. } else {
  14054. gl.frontFace( gl.CCW );
  14055. }
  14056. currentFlipSided = flipSided;
  14057. }
  14058. }
  14059. function setCullFace( cullFace ) {
  14060. if ( cullFace !== CullFaceNone ) {
  14061. enable( gl.CULL_FACE );
  14062. if ( cullFace !== currentCullFace ) {
  14063. if ( cullFace === CullFaceBack ) {
  14064. gl.cullFace( gl.BACK );
  14065. } else if ( cullFace === CullFaceFront ) {
  14066. gl.cullFace( gl.FRONT );
  14067. } else {
  14068. gl.cullFace( gl.FRONT_AND_BACK );
  14069. }
  14070. }
  14071. } else {
  14072. disable( gl.CULL_FACE );
  14073. }
  14074. currentCullFace = cullFace;
  14075. }
  14076. function setLineWidth( width ) {
  14077. if ( width !== currentLineWidth ) {
  14078. if ( lineWidthAvailable ) gl.lineWidth( width );
  14079. currentLineWidth = width;
  14080. }
  14081. }
  14082. function setPolygonOffset( polygonOffset, factor, units ) {
  14083. if ( polygonOffset ) {
  14084. enable( gl.POLYGON_OFFSET_FILL );
  14085. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14086. gl.polygonOffset( factor, units );
  14087. currentPolygonOffsetFactor = factor;
  14088. currentPolygonOffsetUnits = units;
  14089. }
  14090. } else {
  14091. disable( gl.POLYGON_OFFSET_FILL );
  14092. }
  14093. }
  14094. function setScissorTest( scissorTest ) {
  14095. if ( scissorTest ) {
  14096. enable( gl.SCISSOR_TEST );
  14097. } else {
  14098. disable( gl.SCISSOR_TEST );
  14099. }
  14100. }
  14101. // texture
  14102. function activeTexture( webglSlot ) {
  14103. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14104. if ( currentTextureSlot !== webglSlot ) {
  14105. gl.activeTexture( webglSlot );
  14106. currentTextureSlot = webglSlot;
  14107. }
  14108. }
  14109. function bindTexture( webglType, webglTexture, webglSlot ) {
  14110. if ( webglSlot === undefined ) {
  14111. if ( currentTextureSlot === null ) {
  14112. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14113. } else {
  14114. webglSlot = currentTextureSlot;
  14115. }
  14116. }
  14117. let boundTexture = currentBoundTextures[ webglSlot ];
  14118. if ( boundTexture === undefined ) {
  14119. boundTexture = { type: undefined, texture: undefined };
  14120. currentBoundTextures[ webglSlot ] = boundTexture;
  14121. }
  14122. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14123. if ( currentTextureSlot !== webglSlot ) {
  14124. gl.activeTexture( webglSlot );
  14125. currentTextureSlot = webglSlot;
  14126. }
  14127. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14128. boundTexture.type = webglType;
  14129. boundTexture.texture = webglTexture;
  14130. }
  14131. }
  14132. function unbindTexture() {
  14133. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14134. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14135. gl.bindTexture( boundTexture.type, null );
  14136. boundTexture.type = undefined;
  14137. boundTexture.texture = undefined;
  14138. }
  14139. }
  14140. function compressedTexImage2D() {
  14141. try {
  14142. gl.compressedTexImage2D.apply( gl, arguments );
  14143. } catch ( error ) {
  14144. console.error( 'THREE.WebGLState:', error );
  14145. }
  14146. }
  14147. function compressedTexImage3D() {
  14148. try {
  14149. gl.compressedTexImage3D.apply( gl, arguments );
  14150. } catch ( error ) {
  14151. console.error( 'THREE.WebGLState:', error );
  14152. }
  14153. }
  14154. function texSubImage2D() {
  14155. try {
  14156. gl.texSubImage2D.apply( gl, arguments );
  14157. } catch ( error ) {
  14158. console.error( 'THREE.WebGLState:', error );
  14159. }
  14160. }
  14161. function texSubImage3D() {
  14162. try {
  14163. gl.texSubImage3D.apply( gl, arguments );
  14164. } catch ( error ) {
  14165. console.error( 'THREE.WebGLState:', error );
  14166. }
  14167. }
  14168. function compressedTexSubImage2D() {
  14169. try {
  14170. gl.compressedTexSubImage2D.apply( gl, arguments );
  14171. } catch ( error ) {
  14172. console.error( 'THREE.WebGLState:', error );
  14173. }
  14174. }
  14175. function compressedTexSubImage3D() {
  14176. try {
  14177. gl.compressedTexSubImage3D.apply( gl, arguments );
  14178. } catch ( error ) {
  14179. console.error( 'THREE.WebGLState:', error );
  14180. }
  14181. }
  14182. function texStorage2D() {
  14183. try {
  14184. gl.texStorage2D.apply( gl, arguments );
  14185. } catch ( error ) {
  14186. console.error( 'THREE.WebGLState:', error );
  14187. }
  14188. }
  14189. function texStorage3D() {
  14190. try {
  14191. gl.texStorage3D.apply( gl, arguments );
  14192. } catch ( error ) {
  14193. console.error( 'THREE.WebGLState:', error );
  14194. }
  14195. }
  14196. function texImage2D() {
  14197. try {
  14198. gl.texImage2D.apply( gl, arguments );
  14199. } catch ( error ) {
  14200. console.error( 'THREE.WebGLState:', error );
  14201. }
  14202. }
  14203. function texImage3D() {
  14204. try {
  14205. gl.texImage3D.apply( gl, arguments );
  14206. } catch ( error ) {
  14207. console.error( 'THREE.WebGLState:', error );
  14208. }
  14209. }
  14210. //
  14211. function scissor( scissor ) {
  14212. if ( currentScissor.equals( scissor ) === false ) {
  14213. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14214. currentScissor.copy( scissor );
  14215. }
  14216. }
  14217. function viewport( viewport ) {
  14218. if ( currentViewport.equals( viewport ) === false ) {
  14219. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14220. currentViewport.copy( viewport );
  14221. }
  14222. }
  14223. function updateUBOMapping( uniformsGroup, program ) {
  14224. let mapping = uboProgramMap.get( program );
  14225. if ( mapping === undefined ) {
  14226. mapping = new WeakMap();
  14227. uboProgramMap.set( program, mapping );
  14228. }
  14229. let blockIndex = mapping.get( uniformsGroup );
  14230. if ( blockIndex === undefined ) {
  14231. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14232. mapping.set( uniformsGroup, blockIndex );
  14233. }
  14234. }
  14235. function uniformBlockBinding( uniformsGroup, program ) {
  14236. const mapping = uboProgramMap.get( program );
  14237. const blockIndex = mapping.get( uniformsGroup );
  14238. if ( uboBindings.get( program ) !== blockIndex ) {
  14239. // bind shader specific block index to global block point
  14240. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14241. uboBindings.set( program, blockIndex );
  14242. }
  14243. }
  14244. //
  14245. function reset() {
  14246. // reset state
  14247. gl.disable( gl.BLEND );
  14248. gl.disable( gl.CULL_FACE );
  14249. gl.disable( gl.DEPTH_TEST );
  14250. gl.disable( gl.POLYGON_OFFSET_FILL );
  14251. gl.disable( gl.SCISSOR_TEST );
  14252. gl.disable( gl.STENCIL_TEST );
  14253. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14254. gl.blendEquation( gl.FUNC_ADD );
  14255. gl.blendFunc( gl.ONE, gl.ZERO );
  14256. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14257. gl.blendColor( 0, 0, 0, 0 );
  14258. gl.colorMask( true, true, true, true );
  14259. gl.clearColor( 0, 0, 0, 0 );
  14260. gl.depthMask( true );
  14261. gl.depthFunc( gl.LESS );
  14262. gl.clearDepth( 1 );
  14263. gl.stencilMask( 0xffffffff );
  14264. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14265. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14266. gl.clearStencil( 0 );
  14267. gl.cullFace( gl.BACK );
  14268. gl.frontFace( gl.CCW );
  14269. gl.polygonOffset( 0, 0 );
  14270. gl.activeTexture( gl.TEXTURE0 );
  14271. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14272. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14273. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14274. gl.useProgram( null );
  14275. gl.lineWidth( 1 );
  14276. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14277. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14278. // reset internals
  14279. enabledCapabilities = {};
  14280. currentTextureSlot = null;
  14281. currentBoundTextures = {};
  14282. currentBoundFramebuffers = {};
  14283. currentDrawbuffers = new WeakMap();
  14284. defaultDrawbuffers = [];
  14285. currentProgram = null;
  14286. currentBlendingEnabled = false;
  14287. currentBlending = null;
  14288. currentBlendEquation = null;
  14289. currentBlendSrc = null;
  14290. currentBlendDst = null;
  14291. currentBlendEquationAlpha = null;
  14292. currentBlendSrcAlpha = null;
  14293. currentBlendDstAlpha = null;
  14294. currentBlendColor = new Color( 0, 0, 0 );
  14295. currentBlendAlpha = 0;
  14296. currentPremultipledAlpha = false;
  14297. currentFlipSided = null;
  14298. currentCullFace = null;
  14299. currentLineWidth = null;
  14300. currentPolygonOffsetFactor = null;
  14301. currentPolygonOffsetUnits = null;
  14302. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14303. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14304. colorBuffer.reset();
  14305. depthBuffer.reset();
  14306. stencilBuffer.reset();
  14307. }
  14308. return {
  14309. buffers: {
  14310. color: colorBuffer,
  14311. depth: depthBuffer,
  14312. stencil: stencilBuffer
  14313. },
  14314. enable: enable,
  14315. disable: disable,
  14316. bindFramebuffer: bindFramebuffer,
  14317. drawBuffers: drawBuffers,
  14318. useProgram: useProgram,
  14319. setBlending: setBlending,
  14320. setMaterial: setMaterial,
  14321. setFlipSided: setFlipSided,
  14322. setCullFace: setCullFace,
  14323. setLineWidth: setLineWidth,
  14324. setPolygonOffset: setPolygonOffset,
  14325. setScissorTest: setScissorTest,
  14326. activeTexture: activeTexture,
  14327. bindTexture: bindTexture,
  14328. unbindTexture: unbindTexture,
  14329. compressedTexImage2D: compressedTexImage2D,
  14330. compressedTexImage3D: compressedTexImage3D,
  14331. texImage2D: texImage2D,
  14332. texImage3D: texImage3D,
  14333. updateUBOMapping: updateUBOMapping,
  14334. uniformBlockBinding: uniformBlockBinding,
  14335. texStorage2D: texStorage2D,
  14336. texStorage3D: texStorage3D,
  14337. texSubImage2D: texSubImage2D,
  14338. texSubImage3D: texSubImage3D,
  14339. compressedTexSubImage2D: compressedTexSubImage2D,
  14340. compressedTexSubImage3D: compressedTexSubImage3D,
  14341. scissor: scissor,
  14342. viewport: viewport,
  14343. reset: reset
  14344. };
  14345. }
  14346. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14347. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14348. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14349. const _imageDimensions = new Vector2();
  14350. const _videoTextures = new WeakMap();
  14351. let _canvas;
  14352. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14353. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14354. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14355. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14356. let useOffscreenCanvas = false;
  14357. try {
  14358. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14359. // eslint-disable-next-line compat/compat
  14360. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14361. } catch ( err ) {
  14362. // Ignore any errors
  14363. }
  14364. function createCanvas( width, height ) {
  14365. // Use OffscreenCanvas when available. Specially needed in web workers
  14366. return useOffscreenCanvas ?
  14367. // eslint-disable-next-line compat/compat
  14368. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14369. }
  14370. function resizeImage( image, needsNewCanvas, maxSize ) {
  14371. let scale = 1;
  14372. const dimensions = getDimensions( image );
  14373. // handle case if texture exceeds max size
  14374. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  14375. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  14376. }
  14377. // only perform resize if necessary
  14378. if ( scale < 1 ) {
  14379. // only perform resize for certain image types
  14380. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14381. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14382. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  14383. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  14384. const width = Math.floor( scale * dimensions.width );
  14385. const height = Math.floor( scale * dimensions.height );
  14386. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14387. // cube textures can't reuse the same canvas
  14388. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14389. canvas.width = width;
  14390. canvas.height = height;
  14391. const context = canvas.getContext( '2d' );
  14392. context.drawImage( image, 0, 0, width, height );
  14393. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  14394. return canvas;
  14395. } else {
  14396. if ( 'data' in image ) {
  14397. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  14398. }
  14399. return image;
  14400. }
  14401. }
  14402. return image;
  14403. }
  14404. function textureNeedsGenerateMipmaps( texture ) {
  14405. return texture.generateMipmaps && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14406. }
  14407. function generateMipmap( target ) {
  14408. _gl.generateMipmap( target );
  14409. }
  14410. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14411. if ( internalFormatName !== null ) {
  14412. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14413. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14414. }
  14415. let internalFormat = glFormat;
  14416. if ( glFormat === _gl.RED ) {
  14417. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14418. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14419. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14420. }
  14421. if ( glFormat === _gl.RED_INTEGER ) {
  14422. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14423. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14424. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14425. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14426. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14427. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14428. }
  14429. if ( glFormat === _gl.RG ) {
  14430. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14431. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14432. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14433. }
  14434. if ( glFormat === _gl.RG_INTEGER ) {
  14435. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  14436. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  14437. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  14438. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  14439. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  14440. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  14441. }
  14442. if ( glFormat === _gl.RGB ) {
  14443. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  14444. }
  14445. if ( glFormat === _gl.RGBA ) {
  14446. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14447. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14448. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14449. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14450. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14451. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14452. }
  14453. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14454. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14455. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14456. extensions.get( 'EXT_color_buffer_float' );
  14457. }
  14458. return internalFormat;
  14459. }
  14460. function getInternalDepthFormat( useStencil, depthType ) {
  14461. let glInternalFormat;
  14462. if ( useStencil ) {
  14463. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  14464. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14465. } else if ( depthType === FloatType ) {
  14466. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  14467. } else if ( depthType === UnsignedShortType ) {
  14468. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14469. console.warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  14470. }
  14471. } else {
  14472. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  14473. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14474. } else if ( depthType === FloatType ) {
  14475. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14476. } else if ( depthType === UnsignedShortType ) {
  14477. glInternalFormat = _gl.DEPTH_COMPONENT16;
  14478. }
  14479. }
  14480. return glInternalFormat;
  14481. }
  14482. function getMipLevels( texture, image ) {
  14483. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14484. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14485. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14486. // user-defined mipmaps
  14487. return texture.mipmaps.length;
  14488. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14489. return image.mipmaps.length;
  14490. } else {
  14491. // texture without mipmaps (only base level)
  14492. return 1;
  14493. }
  14494. }
  14495. //
  14496. function onTextureDispose( event ) {
  14497. const texture = event.target;
  14498. texture.removeEventListener( 'dispose', onTextureDispose );
  14499. deallocateTexture( texture );
  14500. if ( texture.isVideoTexture ) {
  14501. _videoTextures.delete( texture );
  14502. }
  14503. }
  14504. function onRenderTargetDispose( event ) {
  14505. const renderTarget = event.target;
  14506. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14507. deallocateRenderTarget( renderTarget );
  14508. }
  14509. //
  14510. function deallocateTexture( texture ) {
  14511. const textureProperties = properties.get( texture );
  14512. if ( textureProperties.__webglInit === undefined ) return;
  14513. // check if it's necessary to remove the WebGLTexture object
  14514. const source = texture.source;
  14515. const webglTextures = _sources.get( source );
  14516. if ( webglTextures ) {
  14517. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14518. webglTexture.usedTimes --;
  14519. // the WebGLTexture object is not used anymore, remove it
  14520. if ( webglTexture.usedTimes === 0 ) {
  14521. deleteTexture( texture );
  14522. }
  14523. // remove the weak map entry if no WebGLTexture uses the source anymore
  14524. if ( Object.keys( webglTextures ).length === 0 ) {
  14525. _sources.delete( source );
  14526. }
  14527. }
  14528. properties.remove( texture );
  14529. }
  14530. function deleteTexture( texture ) {
  14531. const textureProperties = properties.get( texture );
  14532. _gl.deleteTexture( textureProperties.__webglTexture );
  14533. const source = texture.source;
  14534. const webglTextures = _sources.get( source );
  14535. delete webglTextures[ textureProperties.__cacheKey ];
  14536. info.memory.textures --;
  14537. }
  14538. function deallocateRenderTarget( renderTarget ) {
  14539. const renderTargetProperties = properties.get( renderTarget );
  14540. if ( renderTarget.depthTexture ) {
  14541. renderTarget.depthTexture.dispose();
  14542. }
  14543. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14544. for ( let i = 0; i < 6; i ++ ) {
  14545. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14546. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14547. } else {
  14548. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14549. }
  14550. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14551. }
  14552. } else {
  14553. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14554. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14555. } else {
  14556. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14557. }
  14558. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14559. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14560. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14561. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14562. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14563. }
  14564. }
  14565. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14566. }
  14567. const textures = renderTarget.textures;
  14568. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14569. const attachmentProperties = properties.get( textures[ i ] );
  14570. if ( attachmentProperties.__webglTexture ) {
  14571. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14572. info.memory.textures --;
  14573. }
  14574. properties.remove( textures[ i ] );
  14575. }
  14576. properties.remove( renderTarget );
  14577. }
  14578. //
  14579. let textureUnits = 0;
  14580. function resetTextureUnits() {
  14581. textureUnits = 0;
  14582. }
  14583. function allocateTextureUnit() {
  14584. const textureUnit = textureUnits;
  14585. if ( textureUnit >= capabilities.maxTextures ) {
  14586. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  14587. }
  14588. textureUnits += 1;
  14589. return textureUnit;
  14590. }
  14591. function getTextureCacheKey( texture ) {
  14592. const array = [];
  14593. array.push( texture.wrapS );
  14594. array.push( texture.wrapT );
  14595. array.push( texture.wrapR || 0 );
  14596. array.push( texture.magFilter );
  14597. array.push( texture.minFilter );
  14598. array.push( texture.anisotropy );
  14599. array.push( texture.internalFormat );
  14600. array.push( texture.format );
  14601. array.push( texture.type );
  14602. array.push( texture.generateMipmaps );
  14603. array.push( texture.premultiplyAlpha );
  14604. array.push( texture.flipY );
  14605. array.push( texture.unpackAlignment );
  14606. array.push( texture.colorSpace );
  14607. return array.join();
  14608. }
  14609. //
  14610. function setTexture2D( texture, slot ) {
  14611. const textureProperties = properties.get( texture );
  14612. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14613. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14614. const image = texture.image;
  14615. if ( image === null ) {
  14616. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14617. } else if ( image.complete === false ) {
  14618. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14619. } else {
  14620. uploadTexture( textureProperties, texture, slot );
  14621. return;
  14622. }
  14623. }
  14624. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14625. }
  14626. function setTexture2DArray( texture, slot ) {
  14627. const textureProperties = properties.get( texture );
  14628. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14629. uploadTexture( textureProperties, texture, slot );
  14630. return;
  14631. }
  14632. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14633. }
  14634. function setTexture3D( texture, slot ) {
  14635. const textureProperties = properties.get( texture );
  14636. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14637. uploadTexture( textureProperties, texture, slot );
  14638. return;
  14639. }
  14640. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14641. }
  14642. function setTextureCube( texture, slot ) {
  14643. const textureProperties = properties.get( texture );
  14644. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14645. uploadCubeTexture( textureProperties, texture, slot );
  14646. return;
  14647. }
  14648. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14649. }
  14650. const wrappingToGL = {
  14651. [ RepeatWrapping ]: _gl.REPEAT,
  14652. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14653. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14654. };
  14655. const filterToGL = {
  14656. [ NearestFilter ]: _gl.NEAREST,
  14657. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14658. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14659. [ LinearFilter ]: _gl.LINEAR,
  14660. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14661. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14662. };
  14663. const compareToGL = {
  14664. [ NeverCompare ]: _gl.NEVER,
  14665. [ AlwaysCompare ]: _gl.ALWAYS,
  14666. [ LessCompare ]: _gl.LESS,
  14667. [ LessEqualCompare ]: _gl.LEQUAL,
  14668. [ EqualCompare ]: _gl.EQUAL,
  14669. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14670. [ GreaterCompare ]: _gl.GREATER,
  14671. [ NotEqualCompare ]: _gl.NOTEQUAL
  14672. };
  14673. function setTextureParameters( textureType, texture ) {
  14674. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  14675. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14676. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  14677. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  14678. }
  14679. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14680. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14681. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14682. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14683. }
  14684. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14685. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14686. if ( texture.compareFunction ) {
  14687. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14688. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14689. }
  14690. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14691. if ( texture.magFilter === NearestFilter ) return;
  14692. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14693. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  14694. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14695. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14696. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14697. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14698. }
  14699. }
  14700. }
  14701. function initTexture( textureProperties, texture ) {
  14702. let forceUpload = false;
  14703. if ( textureProperties.__webglInit === undefined ) {
  14704. textureProperties.__webglInit = true;
  14705. texture.addEventListener( 'dispose', onTextureDispose );
  14706. }
  14707. // create Source <-> WebGLTextures mapping if necessary
  14708. const source = texture.source;
  14709. let webglTextures = _sources.get( source );
  14710. if ( webglTextures === undefined ) {
  14711. webglTextures = {};
  14712. _sources.set( source, webglTextures );
  14713. }
  14714. // check if there is already a WebGLTexture object for the given texture parameters
  14715. const textureCacheKey = getTextureCacheKey( texture );
  14716. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14717. // if not, create a new instance of WebGLTexture
  14718. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14719. // create new entry
  14720. webglTextures[ textureCacheKey ] = {
  14721. texture: _gl.createTexture(),
  14722. usedTimes: 0
  14723. };
  14724. info.memory.textures ++;
  14725. // when a new instance of WebGLTexture was created, a texture upload is required
  14726. // even if the image contents are identical
  14727. forceUpload = true;
  14728. }
  14729. webglTextures[ textureCacheKey ].usedTimes ++;
  14730. // every time the texture cache key changes, it's necessary to check if an instance of
  14731. // WebGLTexture can be deleted in order to avoid a memory leak.
  14732. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14733. if ( webglTexture !== undefined ) {
  14734. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14735. if ( webglTexture.usedTimes === 0 ) {
  14736. deleteTexture( texture );
  14737. }
  14738. }
  14739. // store references to cache key and WebGLTexture object
  14740. textureProperties.__cacheKey = textureCacheKey;
  14741. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14742. }
  14743. return forceUpload;
  14744. }
  14745. function uploadTexture( textureProperties, texture, slot ) {
  14746. let textureType = _gl.TEXTURE_2D;
  14747. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14748. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14749. const forceUpload = initTexture( textureProperties, texture );
  14750. const source = texture.source;
  14751. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14752. const sourceProperties = properties.get( source );
  14753. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14754. state.activeTexture( _gl.TEXTURE0 + slot );
  14755. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14756. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14757. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14758. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14759. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14760. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14761. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14762. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  14763. image = verifyColorSpace( texture, image );
  14764. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14765. const glType = utils.convert( texture.type );
  14766. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14767. setTextureParameters( textureType, texture );
  14768. let mipmap;
  14769. const mipmaps = texture.mipmaps;
  14770. const useTexStorage = ( texture.isVideoTexture !== true );
  14771. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14772. const dataReady = source.dataReady;
  14773. const levels = getMipLevels( texture, image );
  14774. if ( texture.isDepthTexture ) {
  14775. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  14776. //
  14777. if ( allocateMemory ) {
  14778. if ( useTexStorage ) {
  14779. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14780. } else {
  14781. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14782. }
  14783. }
  14784. } else if ( texture.isDataTexture ) {
  14785. // use manually created mipmaps if available
  14786. // if there are no manual mipmaps
  14787. // set 0 level mipmap and then use GL to generate other mipmap levels
  14788. if ( mipmaps.length > 0 ) {
  14789. if ( useTexStorage && allocateMemory ) {
  14790. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14791. }
  14792. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14793. mipmap = mipmaps[ i ];
  14794. if ( useTexStorage ) {
  14795. if ( dataReady ) {
  14796. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14797. }
  14798. } else {
  14799. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14800. }
  14801. }
  14802. texture.generateMipmaps = false;
  14803. } else {
  14804. if ( useTexStorage ) {
  14805. if ( allocateMemory ) {
  14806. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14807. }
  14808. if ( dataReady ) {
  14809. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14810. }
  14811. } else {
  14812. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14813. }
  14814. }
  14815. } else if ( texture.isCompressedTexture ) {
  14816. if ( texture.isCompressedArrayTexture ) {
  14817. if ( useTexStorage && allocateMemory ) {
  14818. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14819. }
  14820. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14821. mipmap = mipmaps[ i ];
  14822. if ( texture.format !== RGBAFormat ) {
  14823. if ( glFormat !== null ) {
  14824. if ( useTexStorage ) {
  14825. if ( dataReady ) {
  14826. if ( texture.layerUpdates.size > 0 ) {
  14827. for ( const layerIndex of texture.layerUpdates ) {
  14828. const layerSize = mipmap.width * mipmap.height;
  14829. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, mipmap.data.slice( layerSize * layerIndex, layerSize * ( layerIndex + 1 ) ), 0, 0 );
  14830. }
  14831. texture.clearLayerUpdates();
  14832. } else {
  14833. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14834. }
  14835. }
  14836. } else {
  14837. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14838. }
  14839. } else {
  14840. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14841. }
  14842. } else {
  14843. if ( useTexStorage ) {
  14844. if ( dataReady ) {
  14845. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14846. }
  14847. } else {
  14848. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14849. }
  14850. }
  14851. }
  14852. } else {
  14853. if ( useTexStorage && allocateMemory ) {
  14854. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14855. }
  14856. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14857. mipmap = mipmaps[ i ];
  14858. if ( texture.format !== RGBAFormat ) {
  14859. if ( glFormat !== null ) {
  14860. if ( useTexStorage ) {
  14861. if ( dataReady ) {
  14862. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14863. }
  14864. } else {
  14865. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14866. }
  14867. } else {
  14868. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14869. }
  14870. } else {
  14871. if ( useTexStorage ) {
  14872. if ( dataReady ) {
  14873. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14874. }
  14875. } else {
  14876. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14877. }
  14878. }
  14879. }
  14880. }
  14881. } else if ( texture.isDataArrayTexture ) {
  14882. if ( useTexStorage ) {
  14883. if ( allocateMemory ) {
  14884. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14885. }
  14886. if ( dataReady ) {
  14887. if ( texture.layerUpdates.size > 0 ) {
  14888. // When type is GL_UNSIGNED_BYTE, each of these bytes is
  14889. // interpreted as one color component, depending on format. When
  14890. // type is one of GL_UNSIGNED_SHORT_5_6_5,
  14891. // GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1, each
  14892. // unsigned value is interpreted as containing all the components
  14893. // for a single pixel, with the color components arranged
  14894. // according to format.
  14895. //
  14896. // See https://registry.khronos.org/OpenGL-Refpages/es1.1/xhtml/glTexImage2D.xml
  14897. let texelSize;
  14898. switch ( glType ) {
  14899. case _gl.UNSIGNED_BYTE:
  14900. switch ( glFormat ) {
  14901. case _gl.ALPHA:
  14902. texelSize = 1;
  14903. break;
  14904. case _gl.LUMINANCE:
  14905. texelSize = 1;
  14906. break;
  14907. case _gl.LUMINANCE_ALPHA:
  14908. texelSize = 2;
  14909. break;
  14910. case _gl.RGB:
  14911. texelSize = 3;
  14912. break;
  14913. case _gl.RGBA:
  14914. texelSize = 4;
  14915. break;
  14916. default:
  14917. throw new Error( `Unknown texel size for format ${glFormat}.` );
  14918. }
  14919. break;
  14920. case _gl.UNSIGNED_SHORT_4_4_4_4:
  14921. case _gl.UNSIGNED_SHORT_5_5_5_1:
  14922. case _gl.UNSIGNED_SHORT_5_6_5:
  14923. texelSize = 1;
  14924. break;
  14925. default:
  14926. throw new Error( `Unknown texel size for type ${glType}.` );
  14927. }
  14928. const layerSize = image.width * image.height * texelSize;
  14929. for ( const layerIndex of texture.layerUpdates ) {
  14930. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, image.data.slice( layerSize * layerIndex, layerSize * ( layerIndex + 1 ) ) );
  14931. }
  14932. texture.clearLayerUpdates();
  14933. } else {
  14934. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14935. }
  14936. }
  14937. } else {
  14938. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14939. }
  14940. } else if ( texture.isData3DTexture ) {
  14941. if ( useTexStorage ) {
  14942. if ( allocateMemory ) {
  14943. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14944. }
  14945. if ( dataReady ) {
  14946. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14947. }
  14948. } else {
  14949. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14950. }
  14951. } else if ( texture.isFramebufferTexture ) {
  14952. if ( allocateMemory ) {
  14953. if ( useTexStorage ) {
  14954. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14955. } else {
  14956. let width = image.width, height = image.height;
  14957. for ( let i = 0; i < levels; i ++ ) {
  14958. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14959. width >>= 1;
  14960. height >>= 1;
  14961. }
  14962. }
  14963. }
  14964. } else {
  14965. // regular Texture (image, video, canvas)
  14966. // use manually created mipmaps if available
  14967. // if there are no manual mipmaps
  14968. // set 0 level mipmap and then use GL to generate other mipmap levels
  14969. if ( mipmaps.length > 0 ) {
  14970. if ( useTexStorage && allocateMemory ) {
  14971. const dimensions = getDimensions( mipmaps[ 0 ] );
  14972. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  14973. }
  14974. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14975. mipmap = mipmaps[ i ];
  14976. if ( useTexStorage ) {
  14977. if ( dataReady ) {
  14978. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14979. }
  14980. } else {
  14981. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14982. }
  14983. }
  14984. texture.generateMipmaps = false;
  14985. } else {
  14986. if ( useTexStorage ) {
  14987. if ( allocateMemory ) {
  14988. const dimensions = getDimensions( image );
  14989. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  14990. }
  14991. if ( dataReady ) {
  14992. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14993. }
  14994. } else {
  14995. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14996. }
  14997. }
  14998. }
  14999. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15000. generateMipmap( textureType );
  15001. }
  15002. sourceProperties.__version = source.version;
  15003. if ( texture.onUpdate ) texture.onUpdate( texture );
  15004. }
  15005. textureProperties.__version = texture.version;
  15006. }
  15007. function uploadCubeTexture( textureProperties, texture, slot ) {
  15008. if ( texture.image.length !== 6 ) return;
  15009. const forceUpload = initTexture( textureProperties, texture );
  15010. const source = texture.source;
  15011. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  15012. const sourceProperties = properties.get( source );
  15013. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  15014. state.activeTexture( _gl.TEXTURE0 + slot );
  15015. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  15016. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  15017. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  15018. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15019. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15020. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15021. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  15022. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  15023. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15024. const cubeImage = [];
  15025. for ( let i = 0; i < 6; i ++ ) {
  15026. if ( ! isCompressed && ! isDataTexture ) {
  15027. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  15028. } else {
  15029. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15030. }
  15031. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  15032. }
  15033. const image = cubeImage[ 0 ],
  15034. glFormat = utils.convert( texture.format, texture.colorSpace ),
  15035. glType = utils.convert( texture.type ),
  15036. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15037. const useTexStorage = ( texture.isVideoTexture !== true );
  15038. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  15039. const dataReady = source.dataReady;
  15040. let levels = getMipLevels( texture, image );
  15041. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15042. let mipmaps;
  15043. if ( isCompressed ) {
  15044. if ( useTexStorage && allocateMemory ) {
  15045. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  15046. }
  15047. for ( let i = 0; i < 6; i ++ ) {
  15048. mipmaps = cubeImage[ i ].mipmaps;
  15049. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15050. const mipmap = mipmaps[ j ];
  15051. if ( texture.format !== RGBAFormat ) {
  15052. if ( glFormat !== null ) {
  15053. if ( useTexStorage ) {
  15054. if ( dataReady ) {
  15055. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15056. }
  15057. } else {
  15058. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15059. }
  15060. } else {
  15061. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15062. }
  15063. } else {
  15064. if ( useTexStorage ) {
  15065. if ( dataReady ) {
  15066. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15067. }
  15068. } else {
  15069. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15070. }
  15071. }
  15072. }
  15073. }
  15074. } else {
  15075. mipmaps = texture.mipmaps;
  15076. if ( useTexStorage && allocateMemory ) {
  15077. // TODO: Uniformly handle mipmap definitions
  15078. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  15079. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  15080. if ( mipmaps.length > 0 ) levels ++;
  15081. const dimensions = getDimensions( cubeImage[ 0 ] );
  15082. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  15083. }
  15084. for ( let i = 0; i < 6; i ++ ) {
  15085. if ( isDataTexture ) {
  15086. if ( useTexStorage ) {
  15087. if ( dataReady ) {
  15088. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  15089. }
  15090. } else {
  15091. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15092. }
  15093. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15094. const mipmap = mipmaps[ j ];
  15095. const mipmapImage = mipmap.image[ i ].image;
  15096. if ( useTexStorage ) {
  15097. if ( dataReady ) {
  15098. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  15099. }
  15100. } else {
  15101. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  15102. }
  15103. }
  15104. } else {
  15105. if ( useTexStorage ) {
  15106. if ( dataReady ) {
  15107. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  15108. }
  15109. } else {
  15110. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  15111. }
  15112. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15113. const mipmap = mipmaps[ j ];
  15114. if ( useTexStorage ) {
  15115. if ( dataReady ) {
  15116. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  15117. }
  15118. } else {
  15119. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  15120. }
  15121. }
  15122. }
  15123. }
  15124. }
  15125. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15126. // We assume images for cube map have the same size.
  15127. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15128. }
  15129. sourceProperties.__version = source.version;
  15130. if ( texture.onUpdate ) texture.onUpdate( texture );
  15131. }
  15132. textureProperties.__version = texture.version;
  15133. }
  15134. // Render targets
  15135. // Setup storage for target texture and bind it to correct framebuffer
  15136. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  15137. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15138. const glType = utils.convert( texture.type );
  15139. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15140. const renderTargetProperties = properties.get( renderTarget );
  15141. if ( ! renderTargetProperties.__hasExternalTextures ) {
  15142. const width = Math.max( 1, renderTarget.width >> level );
  15143. const height = Math.max( 1, renderTarget.height >> level );
  15144. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  15145. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  15146. } else {
  15147. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  15148. }
  15149. }
  15150. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15151. if ( useMultisampledRTT( renderTarget ) ) {
  15152. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  15153. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  15154. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  15155. }
  15156. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15157. }
  15158. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15159. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  15160. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15161. if ( renderTarget.depthBuffer ) {
  15162. // retrieve the depth attachment types
  15163. const depthTexture = renderTarget.depthTexture;
  15164. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  15165. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  15166. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15167. // set up the attachment
  15168. const samples = getRenderTargetSamples( renderTarget );
  15169. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  15170. if ( isUseMultisampledRTT ) {
  15171. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15172. } else if ( isMultisample ) {
  15173. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15174. } else {
  15175. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15176. }
  15177. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  15178. } else {
  15179. const textures = renderTarget.textures;
  15180. for ( let i = 0; i < textures.length; i ++ ) {
  15181. const texture = textures[ i ];
  15182. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15183. const glType = utils.convert( texture.type );
  15184. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15185. const samples = getRenderTargetSamples( renderTarget );
  15186. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15187. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15188. } else if ( useMultisampledRTT( renderTarget ) ) {
  15189. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15190. } else {
  15191. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15192. }
  15193. }
  15194. }
  15195. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15196. }
  15197. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15198. function setupDepthTexture( framebuffer, renderTarget ) {
  15199. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15200. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15201. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15202. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15203. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15204. }
  15205. // upload an empty depth texture with framebuffer size
  15206. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15207. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15208. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15209. renderTarget.depthTexture.image.width = renderTarget.width;
  15210. renderTarget.depthTexture.image.height = renderTarget.height;
  15211. renderTarget.depthTexture.needsUpdate = true;
  15212. }
  15213. setTexture2D( renderTarget.depthTexture, 0 );
  15214. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15215. const samples = getRenderTargetSamples( renderTarget );
  15216. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15217. if ( useMultisampledRTT( renderTarget ) ) {
  15218. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15219. } else {
  15220. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15221. }
  15222. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15223. if ( useMultisampledRTT( renderTarget ) ) {
  15224. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15225. } else {
  15226. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15227. }
  15228. } else {
  15229. throw new Error( 'Unknown depthTexture format' );
  15230. }
  15231. }
  15232. // Setup GL resources for a non-texture depth buffer
  15233. function setupDepthRenderbuffer( renderTarget ) {
  15234. const renderTargetProperties = properties.get( renderTarget );
  15235. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15236. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15237. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15238. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15239. } else {
  15240. if ( isCube ) {
  15241. renderTargetProperties.__webglDepthbuffer = [];
  15242. for ( let i = 0; i < 6; i ++ ) {
  15243. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15244. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15245. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15246. }
  15247. } else {
  15248. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15249. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15250. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15251. }
  15252. }
  15253. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15254. }
  15255. // rebind framebuffer with external textures
  15256. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15257. const renderTargetProperties = properties.get( renderTarget );
  15258. if ( colorTexture !== undefined ) {
  15259. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15260. }
  15261. if ( depthTexture !== undefined ) {
  15262. setupDepthRenderbuffer( renderTarget );
  15263. }
  15264. }
  15265. // Set up GL resources for the render target
  15266. function setupRenderTarget( renderTarget ) {
  15267. const texture = renderTarget.texture;
  15268. const renderTargetProperties = properties.get( renderTarget );
  15269. const textureProperties = properties.get( texture );
  15270. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15271. const textures = renderTarget.textures;
  15272. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15273. const isMultipleRenderTargets = ( textures.length > 1 );
  15274. if ( ! isMultipleRenderTargets ) {
  15275. if ( textureProperties.__webglTexture === undefined ) {
  15276. textureProperties.__webglTexture = _gl.createTexture();
  15277. }
  15278. textureProperties.__version = texture.version;
  15279. info.memory.textures ++;
  15280. }
  15281. // Setup framebuffer
  15282. if ( isCube ) {
  15283. renderTargetProperties.__webglFramebuffer = [];
  15284. for ( let i = 0; i < 6; i ++ ) {
  15285. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15286. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15287. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15288. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15289. }
  15290. } else {
  15291. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15292. }
  15293. }
  15294. } else {
  15295. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15296. renderTargetProperties.__webglFramebuffer = [];
  15297. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15298. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15299. }
  15300. } else {
  15301. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15302. }
  15303. if ( isMultipleRenderTargets ) {
  15304. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15305. const attachmentProperties = properties.get( textures[ i ] );
  15306. if ( attachmentProperties.__webglTexture === undefined ) {
  15307. attachmentProperties.__webglTexture = _gl.createTexture();
  15308. info.memory.textures ++;
  15309. }
  15310. }
  15311. }
  15312. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15313. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15314. renderTargetProperties.__webglColorRenderbuffer = [];
  15315. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15316. for ( let i = 0; i < textures.length; i ++ ) {
  15317. const texture = textures[ i ];
  15318. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15319. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15320. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15321. const glType = utils.convert( texture.type );
  15322. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15323. const samples = getRenderTargetSamples( renderTarget );
  15324. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15325. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15326. }
  15327. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15328. if ( renderTarget.depthBuffer ) {
  15329. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15330. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15331. }
  15332. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15333. }
  15334. }
  15335. // Setup color buffer
  15336. if ( isCube ) {
  15337. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15338. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15339. for ( let i = 0; i < 6; i ++ ) {
  15340. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15341. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15342. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15343. }
  15344. } else {
  15345. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15346. }
  15347. }
  15348. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15349. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15350. }
  15351. state.unbindTexture();
  15352. } else if ( isMultipleRenderTargets ) {
  15353. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15354. const attachment = textures[ i ];
  15355. const attachmentProperties = properties.get( attachment );
  15356. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15357. setTextureParameters( _gl.TEXTURE_2D, attachment );
  15358. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15359. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  15360. generateMipmap( _gl.TEXTURE_2D );
  15361. }
  15362. }
  15363. state.unbindTexture();
  15364. } else {
  15365. let glTextureType = _gl.TEXTURE_2D;
  15366. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15367. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15368. }
  15369. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15370. setTextureParameters( glTextureType, texture );
  15371. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15372. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15373. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15374. }
  15375. } else {
  15376. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15377. }
  15378. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15379. generateMipmap( glTextureType );
  15380. }
  15381. state.unbindTexture();
  15382. }
  15383. // Setup depth and stencil buffers
  15384. if ( renderTarget.depthBuffer ) {
  15385. setupDepthRenderbuffer( renderTarget );
  15386. }
  15387. }
  15388. function updateRenderTargetMipmap( renderTarget ) {
  15389. const textures = renderTarget.textures;
  15390. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15391. const texture = textures[ i ];
  15392. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15393. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15394. const webglTexture = properties.get( texture ).__webglTexture;
  15395. state.bindTexture( target, webglTexture );
  15396. generateMipmap( target );
  15397. state.unbindTexture();
  15398. }
  15399. }
  15400. }
  15401. const invalidationArrayRead = [];
  15402. const invalidationArrayDraw = [];
  15403. function updateMultisampleRenderTarget( renderTarget ) {
  15404. if ( renderTarget.samples > 0 ) {
  15405. if ( useMultisampledRTT( renderTarget ) === false ) {
  15406. const textures = renderTarget.textures;
  15407. const width = renderTarget.width;
  15408. const height = renderTarget.height;
  15409. let mask = _gl.COLOR_BUFFER_BIT;
  15410. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15411. const renderTargetProperties = properties.get( renderTarget );
  15412. const isMultipleRenderTargets = ( textures.length > 1 );
  15413. // If MRT we need to remove FBO attachments
  15414. if ( isMultipleRenderTargets ) {
  15415. for ( let i = 0; i < textures.length; i ++ ) {
  15416. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15417. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15418. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15419. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15420. }
  15421. }
  15422. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15423. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15424. for ( let i = 0; i < textures.length; i ++ ) {
  15425. if ( renderTarget.resolveDepthBuffer ) {
  15426. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15427. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  15428. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15429. }
  15430. if ( isMultipleRenderTargets ) {
  15431. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15432. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15433. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15434. }
  15435. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15436. if ( supportsInvalidateFramebuffer === true ) {
  15437. invalidationArrayRead.length = 0;
  15438. invalidationArrayDraw.length = 0;
  15439. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  15440. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  15441. invalidationArrayRead.push( depthStyle );
  15442. invalidationArrayDraw.push( depthStyle );
  15443. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  15444. }
  15445. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  15446. }
  15447. }
  15448. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15449. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15450. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15451. if ( isMultipleRenderTargets ) {
  15452. for ( let i = 0; i < textures.length; i ++ ) {
  15453. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15454. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15455. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15456. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15457. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15458. }
  15459. }
  15460. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15461. } else {
  15462. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  15463. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15464. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15465. }
  15466. }
  15467. }
  15468. }
  15469. function getRenderTargetSamples( renderTarget ) {
  15470. return Math.min( capabilities.maxSamples, renderTarget.samples );
  15471. }
  15472. function useMultisampledRTT( renderTarget ) {
  15473. const renderTargetProperties = properties.get( renderTarget );
  15474. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15475. }
  15476. function updateVideoTexture( texture ) {
  15477. const frame = info.render.frame;
  15478. // Check the last frame we updated the VideoTexture
  15479. if ( _videoTextures.get( texture ) !== frame ) {
  15480. _videoTextures.set( texture, frame );
  15481. texture.update();
  15482. }
  15483. }
  15484. function verifyColorSpace( texture, image ) {
  15485. const colorSpace = texture.colorSpace;
  15486. const format = texture.format;
  15487. const type = texture.type;
  15488. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  15489. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15490. // sRGB
  15491. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15492. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15493. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15494. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15495. }
  15496. } else {
  15497. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15498. }
  15499. }
  15500. return image;
  15501. }
  15502. function getDimensions( image ) {
  15503. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  15504. // if intrinsic data are not available, fallback to width/height
  15505. _imageDimensions.width = image.naturalWidth || image.width;
  15506. _imageDimensions.height = image.naturalHeight || image.height;
  15507. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  15508. _imageDimensions.width = image.displayWidth;
  15509. _imageDimensions.height = image.displayHeight;
  15510. } else {
  15511. _imageDimensions.width = image.width;
  15512. _imageDimensions.height = image.height;
  15513. }
  15514. return _imageDimensions;
  15515. }
  15516. //
  15517. this.allocateTextureUnit = allocateTextureUnit;
  15518. this.resetTextureUnits = resetTextureUnits;
  15519. this.setTexture2D = setTexture2D;
  15520. this.setTexture2DArray = setTexture2DArray;
  15521. this.setTexture3D = setTexture3D;
  15522. this.setTextureCube = setTextureCube;
  15523. this.rebindTextures = rebindTextures;
  15524. this.setupRenderTarget = setupRenderTarget;
  15525. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15526. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15527. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15528. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15529. this.useMultisampledRTT = useMultisampledRTT;
  15530. }
  15531. function WebGLUtils( gl, extensions ) {
  15532. function convert( p, colorSpace = NoColorSpace ) {
  15533. let extension;
  15534. const transfer = ColorManagement.getTransfer( colorSpace );
  15535. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15536. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15537. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15538. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  15539. if ( p === ByteType ) return gl.BYTE;
  15540. if ( p === ShortType ) return gl.SHORT;
  15541. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15542. if ( p === IntType ) return gl.INT;
  15543. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15544. if ( p === FloatType ) return gl.FLOAT;
  15545. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  15546. if ( p === AlphaFormat ) return gl.ALPHA;
  15547. if ( p === RGBFormat ) return gl.RGB;
  15548. if ( p === RGBAFormat ) return gl.RGBA;
  15549. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15550. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15551. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15552. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15553. // WebGL2 formats.
  15554. if ( p === RedFormat ) return gl.RED;
  15555. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15556. if ( p === RGFormat ) return gl.RG;
  15557. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15558. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15559. // S3TC
  15560. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15561. if ( transfer === SRGBTransfer ) {
  15562. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15563. if ( extension !== null ) {
  15564. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15565. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15566. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15567. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15568. } else {
  15569. return null;
  15570. }
  15571. } else {
  15572. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15573. if ( extension !== null ) {
  15574. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15575. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15576. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15577. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15578. } else {
  15579. return null;
  15580. }
  15581. }
  15582. }
  15583. // PVRTC
  15584. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15585. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15586. if ( extension !== null ) {
  15587. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15588. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15589. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15590. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15591. } else {
  15592. return null;
  15593. }
  15594. }
  15595. // ETC
  15596. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15597. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15598. if ( extension !== null ) {
  15599. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15600. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15601. } else {
  15602. return null;
  15603. }
  15604. }
  15605. // ASTC
  15606. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15607. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15608. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15609. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15610. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15611. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15612. if ( extension !== null ) {
  15613. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15614. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15615. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15616. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15617. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15618. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15619. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15620. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15621. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15622. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15623. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15624. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15625. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15626. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15627. } else {
  15628. return null;
  15629. }
  15630. }
  15631. // BPTC
  15632. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15633. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15634. if ( extension !== null ) {
  15635. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15636. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15637. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15638. } else {
  15639. return null;
  15640. }
  15641. }
  15642. // RGTC
  15643. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15644. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15645. if ( extension !== null ) {
  15646. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15647. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15648. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15649. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15650. } else {
  15651. return null;
  15652. }
  15653. }
  15654. //
  15655. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  15656. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15657. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15658. }
  15659. return { convert: convert };
  15660. }
  15661. class ArrayCamera extends PerspectiveCamera {
  15662. constructor( array = [] ) {
  15663. super();
  15664. this.isArrayCamera = true;
  15665. this.cameras = array;
  15666. }
  15667. }
  15668. class Group extends Object3D {
  15669. constructor() {
  15670. super();
  15671. this.isGroup = true;
  15672. this.type = 'Group';
  15673. }
  15674. }
  15675. const _moveEvent = { type: 'move' };
  15676. class WebXRController {
  15677. constructor() {
  15678. this._targetRay = null;
  15679. this._grip = null;
  15680. this._hand = null;
  15681. }
  15682. getHandSpace() {
  15683. if ( this._hand === null ) {
  15684. this._hand = new Group();
  15685. this._hand.matrixAutoUpdate = false;
  15686. this._hand.visible = false;
  15687. this._hand.joints = {};
  15688. this._hand.inputState = { pinching: false };
  15689. }
  15690. return this._hand;
  15691. }
  15692. getTargetRaySpace() {
  15693. if ( this._targetRay === null ) {
  15694. this._targetRay = new Group();
  15695. this._targetRay.matrixAutoUpdate = false;
  15696. this._targetRay.visible = false;
  15697. this._targetRay.hasLinearVelocity = false;
  15698. this._targetRay.linearVelocity = new Vector3();
  15699. this._targetRay.hasAngularVelocity = false;
  15700. this._targetRay.angularVelocity = new Vector3();
  15701. }
  15702. return this._targetRay;
  15703. }
  15704. getGripSpace() {
  15705. if ( this._grip === null ) {
  15706. this._grip = new Group();
  15707. this._grip.matrixAutoUpdate = false;
  15708. this._grip.visible = false;
  15709. this._grip.hasLinearVelocity = false;
  15710. this._grip.linearVelocity = new Vector3();
  15711. this._grip.hasAngularVelocity = false;
  15712. this._grip.angularVelocity = new Vector3();
  15713. }
  15714. return this._grip;
  15715. }
  15716. dispatchEvent( event ) {
  15717. if ( this._targetRay !== null ) {
  15718. this._targetRay.dispatchEvent( event );
  15719. }
  15720. if ( this._grip !== null ) {
  15721. this._grip.dispatchEvent( event );
  15722. }
  15723. if ( this._hand !== null ) {
  15724. this._hand.dispatchEvent( event );
  15725. }
  15726. return this;
  15727. }
  15728. connect( inputSource ) {
  15729. if ( inputSource && inputSource.hand ) {
  15730. const hand = this._hand;
  15731. if ( hand ) {
  15732. for ( const inputjoint of inputSource.hand.values() ) {
  15733. // Initialize hand with joints when connected
  15734. this._getHandJoint( hand, inputjoint );
  15735. }
  15736. }
  15737. }
  15738. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15739. return this;
  15740. }
  15741. disconnect( inputSource ) {
  15742. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15743. if ( this._targetRay !== null ) {
  15744. this._targetRay.visible = false;
  15745. }
  15746. if ( this._grip !== null ) {
  15747. this._grip.visible = false;
  15748. }
  15749. if ( this._hand !== null ) {
  15750. this._hand.visible = false;
  15751. }
  15752. return this;
  15753. }
  15754. update( inputSource, frame, referenceSpace ) {
  15755. let inputPose = null;
  15756. let gripPose = null;
  15757. let handPose = null;
  15758. const targetRay = this._targetRay;
  15759. const grip = this._grip;
  15760. const hand = this._hand;
  15761. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15762. if ( hand && inputSource.hand ) {
  15763. handPose = true;
  15764. for ( const inputjoint of inputSource.hand.values() ) {
  15765. // Update the joints groups with the XRJoint poses
  15766. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15767. // The transform of this joint will be updated with the joint pose on each frame
  15768. const joint = this._getHandJoint( hand, inputjoint );
  15769. if ( jointPose !== null ) {
  15770. joint.matrix.fromArray( jointPose.transform.matrix );
  15771. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15772. joint.matrixWorldNeedsUpdate = true;
  15773. joint.jointRadius = jointPose.radius;
  15774. }
  15775. joint.visible = jointPose !== null;
  15776. }
  15777. // Custom events
  15778. // Check pinchz
  15779. const indexTip = hand.joints[ 'index-finger-tip' ];
  15780. const thumbTip = hand.joints[ 'thumb-tip' ];
  15781. const distance = indexTip.position.distanceTo( thumbTip.position );
  15782. const distanceToPinch = 0.02;
  15783. const threshold = 0.005;
  15784. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15785. hand.inputState.pinching = false;
  15786. this.dispatchEvent( {
  15787. type: 'pinchend',
  15788. handedness: inputSource.handedness,
  15789. target: this
  15790. } );
  15791. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15792. hand.inputState.pinching = true;
  15793. this.dispatchEvent( {
  15794. type: 'pinchstart',
  15795. handedness: inputSource.handedness,
  15796. target: this
  15797. } );
  15798. }
  15799. } else {
  15800. if ( grip !== null && inputSource.gripSpace ) {
  15801. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15802. if ( gripPose !== null ) {
  15803. grip.matrix.fromArray( gripPose.transform.matrix );
  15804. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15805. grip.matrixWorldNeedsUpdate = true;
  15806. if ( gripPose.linearVelocity ) {
  15807. grip.hasLinearVelocity = true;
  15808. grip.linearVelocity.copy( gripPose.linearVelocity );
  15809. } else {
  15810. grip.hasLinearVelocity = false;
  15811. }
  15812. if ( gripPose.angularVelocity ) {
  15813. grip.hasAngularVelocity = true;
  15814. grip.angularVelocity.copy( gripPose.angularVelocity );
  15815. } else {
  15816. grip.hasAngularVelocity = false;
  15817. }
  15818. }
  15819. }
  15820. }
  15821. if ( targetRay !== null ) {
  15822. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15823. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15824. if ( inputPose === null && gripPose !== null ) {
  15825. inputPose = gripPose;
  15826. }
  15827. if ( inputPose !== null ) {
  15828. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15829. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15830. targetRay.matrixWorldNeedsUpdate = true;
  15831. if ( inputPose.linearVelocity ) {
  15832. targetRay.hasLinearVelocity = true;
  15833. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15834. } else {
  15835. targetRay.hasLinearVelocity = false;
  15836. }
  15837. if ( inputPose.angularVelocity ) {
  15838. targetRay.hasAngularVelocity = true;
  15839. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15840. } else {
  15841. targetRay.hasAngularVelocity = false;
  15842. }
  15843. this.dispatchEvent( _moveEvent );
  15844. }
  15845. }
  15846. }
  15847. if ( targetRay !== null ) {
  15848. targetRay.visible = ( inputPose !== null );
  15849. }
  15850. if ( grip !== null ) {
  15851. grip.visible = ( gripPose !== null );
  15852. }
  15853. if ( hand !== null ) {
  15854. hand.visible = ( handPose !== null );
  15855. }
  15856. return this;
  15857. }
  15858. // private method
  15859. _getHandJoint( hand, inputjoint ) {
  15860. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15861. const joint = new Group();
  15862. joint.matrixAutoUpdate = false;
  15863. joint.visible = false;
  15864. hand.joints[ inputjoint.jointName ] = joint;
  15865. hand.add( joint );
  15866. }
  15867. return hand.joints[ inputjoint.jointName ];
  15868. }
  15869. }
  15870. const _occlusion_vertex = `
  15871. void main() {
  15872. gl_Position = vec4( position, 1.0 );
  15873. }`;
  15874. const _occlusion_fragment = `
  15875. uniform sampler2DArray depthColor;
  15876. uniform float depthWidth;
  15877. uniform float depthHeight;
  15878. void main() {
  15879. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  15880. if ( coord.x >= 1.0 ) {
  15881. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  15882. } else {
  15883. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  15884. }
  15885. }`;
  15886. class WebXRDepthSensing {
  15887. constructor() {
  15888. this.texture = null;
  15889. this.mesh = null;
  15890. this.depthNear = 0;
  15891. this.depthFar = 0;
  15892. }
  15893. init( renderer, depthData, renderState ) {
  15894. if ( this.texture === null ) {
  15895. const texture = new Texture();
  15896. const texProps = renderer.properties.get( texture );
  15897. texProps.__webglTexture = depthData.texture;
  15898. if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) {
  15899. this.depthNear = depthData.depthNear;
  15900. this.depthFar = depthData.depthFar;
  15901. }
  15902. this.texture = texture;
  15903. }
  15904. }
  15905. getMesh( cameraXR ) {
  15906. if ( this.texture !== null ) {
  15907. if ( this.mesh === null ) {
  15908. const viewport = cameraXR.cameras[ 0 ].viewport;
  15909. const material = new ShaderMaterial( {
  15910. vertexShader: _occlusion_vertex,
  15911. fragmentShader: _occlusion_fragment,
  15912. uniforms: {
  15913. depthColor: { value: this.texture },
  15914. depthWidth: { value: viewport.z },
  15915. depthHeight: { value: viewport.w }
  15916. }
  15917. } );
  15918. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  15919. }
  15920. }
  15921. return this.mesh;
  15922. }
  15923. reset() {
  15924. this.texture = null;
  15925. this.mesh = null;
  15926. }
  15927. }
  15928. class WebXRManager extends EventDispatcher {
  15929. constructor( renderer, gl ) {
  15930. super();
  15931. const scope = this;
  15932. let session = null;
  15933. let framebufferScaleFactor = 1.0;
  15934. let referenceSpace = null;
  15935. let referenceSpaceType = 'local-floor';
  15936. // Set default foveation to maximum.
  15937. let foveation = 1.0;
  15938. let customReferenceSpace = null;
  15939. let pose = null;
  15940. let glBinding = null;
  15941. let glProjLayer = null;
  15942. let glBaseLayer = null;
  15943. let xrFrame = null;
  15944. const depthSensing = new WebXRDepthSensing();
  15945. const attributes = gl.getContextAttributes();
  15946. let initialRenderTarget = null;
  15947. let newRenderTarget = null;
  15948. const controllers = [];
  15949. const controllerInputSources = [];
  15950. const currentSize = new Vector2();
  15951. let currentPixelRatio = null;
  15952. //
  15953. const cameraL = new PerspectiveCamera();
  15954. cameraL.layers.enable( 1 );
  15955. cameraL.viewport = new Vector4();
  15956. const cameraR = new PerspectiveCamera();
  15957. cameraR.layers.enable( 2 );
  15958. cameraR.viewport = new Vector4();
  15959. const cameras = [ cameraL, cameraR ];
  15960. const cameraXR = new ArrayCamera();
  15961. cameraXR.layers.enable( 1 );
  15962. cameraXR.layers.enable( 2 );
  15963. let _currentDepthNear = null;
  15964. let _currentDepthFar = null;
  15965. //
  15966. this.cameraAutoUpdate = true;
  15967. this.enabled = false;
  15968. this.isPresenting = false;
  15969. this.getController = function ( index ) {
  15970. let controller = controllers[ index ];
  15971. if ( controller === undefined ) {
  15972. controller = new WebXRController();
  15973. controllers[ index ] = controller;
  15974. }
  15975. return controller.getTargetRaySpace();
  15976. };
  15977. this.getControllerGrip = function ( index ) {
  15978. let controller = controllers[ index ];
  15979. if ( controller === undefined ) {
  15980. controller = new WebXRController();
  15981. controllers[ index ] = controller;
  15982. }
  15983. return controller.getGripSpace();
  15984. };
  15985. this.getHand = function ( index ) {
  15986. let controller = controllers[ index ];
  15987. if ( controller === undefined ) {
  15988. controller = new WebXRController();
  15989. controllers[ index ] = controller;
  15990. }
  15991. return controller.getHandSpace();
  15992. };
  15993. //
  15994. function onSessionEvent( event ) {
  15995. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15996. if ( controllerIndex === - 1 ) {
  15997. return;
  15998. }
  15999. const controller = controllers[ controllerIndex ];
  16000. if ( controller !== undefined ) {
  16001. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  16002. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  16003. }
  16004. }
  16005. function onSessionEnd() {
  16006. session.removeEventListener( 'select', onSessionEvent );
  16007. session.removeEventListener( 'selectstart', onSessionEvent );
  16008. session.removeEventListener( 'selectend', onSessionEvent );
  16009. session.removeEventListener( 'squeeze', onSessionEvent );
  16010. session.removeEventListener( 'squeezestart', onSessionEvent );
  16011. session.removeEventListener( 'squeezeend', onSessionEvent );
  16012. session.removeEventListener( 'end', onSessionEnd );
  16013. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  16014. for ( let i = 0; i < controllers.length; i ++ ) {
  16015. const inputSource = controllerInputSources[ i ];
  16016. if ( inputSource === null ) continue;
  16017. controllerInputSources[ i ] = null;
  16018. controllers[ i ].disconnect( inputSource );
  16019. }
  16020. _currentDepthNear = null;
  16021. _currentDepthFar = null;
  16022. depthSensing.reset();
  16023. // restore framebuffer/rendering state
  16024. renderer.setRenderTarget( initialRenderTarget );
  16025. glBaseLayer = null;
  16026. glProjLayer = null;
  16027. glBinding = null;
  16028. session = null;
  16029. newRenderTarget = null;
  16030. //
  16031. animation.stop();
  16032. scope.isPresenting = false;
  16033. renderer.setPixelRatio( currentPixelRatio );
  16034. renderer.setSize( currentSize.width, currentSize.height, false );
  16035. scope.dispatchEvent( { type: 'sessionend' } );
  16036. }
  16037. this.setFramebufferScaleFactor = function ( value ) {
  16038. framebufferScaleFactor = value;
  16039. if ( scope.isPresenting === true ) {
  16040. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  16041. }
  16042. };
  16043. this.setReferenceSpaceType = function ( value ) {
  16044. referenceSpaceType = value;
  16045. if ( scope.isPresenting === true ) {
  16046. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  16047. }
  16048. };
  16049. this.getReferenceSpace = function () {
  16050. return customReferenceSpace || referenceSpace;
  16051. };
  16052. this.setReferenceSpace = function ( space ) {
  16053. customReferenceSpace = space;
  16054. };
  16055. this.getBaseLayer = function () {
  16056. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  16057. };
  16058. this.getBinding = function () {
  16059. return glBinding;
  16060. };
  16061. this.getFrame = function () {
  16062. return xrFrame;
  16063. };
  16064. this.getSession = function () {
  16065. return session;
  16066. };
  16067. this.setSession = async function ( value ) {
  16068. session = value;
  16069. if ( session !== null ) {
  16070. initialRenderTarget = renderer.getRenderTarget();
  16071. session.addEventListener( 'select', onSessionEvent );
  16072. session.addEventListener( 'selectstart', onSessionEvent );
  16073. session.addEventListener( 'selectend', onSessionEvent );
  16074. session.addEventListener( 'squeeze', onSessionEvent );
  16075. session.addEventListener( 'squeezestart', onSessionEvent );
  16076. session.addEventListener( 'squeezeend', onSessionEvent );
  16077. session.addEventListener( 'end', onSessionEnd );
  16078. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  16079. if ( attributes.xrCompatible !== true ) {
  16080. await gl.makeXRCompatible();
  16081. }
  16082. currentPixelRatio = renderer.getPixelRatio();
  16083. renderer.getSize( currentSize );
  16084. if ( session.renderState.layers === undefined ) {
  16085. const layerInit = {
  16086. antialias: attributes.antialias,
  16087. alpha: true,
  16088. depth: attributes.depth,
  16089. stencil: attributes.stencil,
  16090. framebufferScaleFactor: framebufferScaleFactor
  16091. };
  16092. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  16093. session.updateRenderState( { baseLayer: glBaseLayer } );
  16094. renderer.setPixelRatio( 1 );
  16095. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  16096. newRenderTarget = new WebGLRenderTarget(
  16097. glBaseLayer.framebufferWidth,
  16098. glBaseLayer.framebufferHeight,
  16099. {
  16100. format: RGBAFormat,
  16101. type: UnsignedByteType,
  16102. colorSpace: renderer.outputColorSpace,
  16103. stencilBuffer: attributes.stencil
  16104. }
  16105. );
  16106. } else {
  16107. let depthFormat = null;
  16108. let depthType = null;
  16109. let glDepthFormat = null;
  16110. if ( attributes.depth ) {
  16111. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  16112. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  16113. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  16114. }
  16115. const projectionlayerInit = {
  16116. colorFormat: gl.RGBA8,
  16117. depthFormat: glDepthFormat,
  16118. scaleFactor: framebufferScaleFactor
  16119. };
  16120. glBinding = new XRWebGLBinding( session, gl );
  16121. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  16122. session.updateRenderState( { layers: [ glProjLayer ] } );
  16123. renderer.setPixelRatio( 1 );
  16124. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  16125. newRenderTarget = new WebGLRenderTarget(
  16126. glProjLayer.textureWidth,
  16127. glProjLayer.textureHeight,
  16128. {
  16129. format: RGBAFormat,
  16130. type: UnsignedByteType,
  16131. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  16132. stencilBuffer: attributes.stencil,
  16133. colorSpace: renderer.outputColorSpace,
  16134. samples: attributes.antialias ? 4 : 0,
  16135. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false )
  16136. } );
  16137. }
  16138. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  16139. this.setFoveation( foveation );
  16140. customReferenceSpace = null;
  16141. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  16142. animation.setContext( session );
  16143. animation.start();
  16144. scope.isPresenting = true;
  16145. scope.dispatchEvent( { type: 'sessionstart' } );
  16146. }
  16147. };
  16148. this.getEnvironmentBlendMode = function () {
  16149. if ( session !== null ) {
  16150. return session.environmentBlendMode;
  16151. }
  16152. };
  16153. function onInputSourcesChange( event ) {
  16154. // Notify disconnected
  16155. for ( let i = 0; i < event.removed.length; i ++ ) {
  16156. const inputSource = event.removed[ i ];
  16157. const index = controllerInputSources.indexOf( inputSource );
  16158. if ( index >= 0 ) {
  16159. controllerInputSources[ index ] = null;
  16160. controllers[ index ].disconnect( inputSource );
  16161. }
  16162. }
  16163. // Notify connected
  16164. for ( let i = 0; i < event.added.length; i ++ ) {
  16165. const inputSource = event.added[ i ];
  16166. let controllerIndex = controllerInputSources.indexOf( inputSource );
  16167. if ( controllerIndex === - 1 ) {
  16168. // Assign input source a controller that currently has no input source
  16169. for ( let i = 0; i < controllers.length; i ++ ) {
  16170. if ( i >= controllerInputSources.length ) {
  16171. controllerInputSources.push( inputSource );
  16172. controllerIndex = i;
  16173. break;
  16174. } else if ( controllerInputSources[ i ] === null ) {
  16175. controllerInputSources[ i ] = inputSource;
  16176. controllerIndex = i;
  16177. break;
  16178. }
  16179. }
  16180. // If all controllers do currently receive input we ignore new ones
  16181. if ( controllerIndex === - 1 ) break;
  16182. }
  16183. const controller = controllers[ controllerIndex ];
  16184. if ( controller ) {
  16185. controller.connect( inputSource );
  16186. }
  16187. }
  16188. }
  16189. //
  16190. const cameraLPos = new Vector3();
  16191. const cameraRPos = new Vector3();
  16192. /**
  16193. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16194. * the cameras' projection and world matrices have already been set.
  16195. * And that near and far planes are identical for both cameras.
  16196. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16197. */
  16198. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16199. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16200. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16201. const ipd = cameraLPos.distanceTo( cameraRPos );
  16202. const projL = cameraL.projectionMatrix.elements;
  16203. const projR = cameraR.projectionMatrix.elements;
  16204. // VR systems will have identical far and near planes, and
  16205. // most likely identical top and bottom frustum extents.
  16206. // Use the left camera for these values.
  16207. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16208. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16209. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16210. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16211. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16212. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16213. const left = near * leftFov;
  16214. const right = near * rightFov;
  16215. // Calculate the new camera's position offset from the
  16216. // left camera. xOffset should be roughly half `ipd`.
  16217. const zOffset = ipd / ( - leftFov + rightFov );
  16218. const xOffset = zOffset * - leftFov;
  16219. // TODO: Better way to apply this offset?
  16220. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16221. camera.translateX( xOffset );
  16222. camera.translateZ( zOffset );
  16223. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16224. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16225. // Find the union of the frustum values of the cameras and scale
  16226. // the values so that the near plane's position does not change in world space,
  16227. // although must now be relative to the new union camera.
  16228. const near2 = near + zOffset;
  16229. const far2 = far + zOffset;
  16230. const left2 = left - xOffset;
  16231. const right2 = right + ( ipd - xOffset );
  16232. const top2 = topFov * far / far2 * near2;
  16233. const bottom2 = bottomFov * far / far2 * near2;
  16234. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16235. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16236. }
  16237. function updateCamera( camera, parent ) {
  16238. if ( parent === null ) {
  16239. camera.matrixWorld.copy( camera.matrix );
  16240. } else {
  16241. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16242. }
  16243. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16244. }
  16245. this.updateCamera = function ( camera ) {
  16246. if ( session === null ) return;
  16247. if ( depthSensing.texture !== null ) {
  16248. camera.near = depthSensing.depthNear;
  16249. camera.far = depthSensing.depthFar;
  16250. }
  16251. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  16252. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  16253. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16254. // Note that the new renderState won't apply until the next frame. See #18320
  16255. session.updateRenderState( {
  16256. depthNear: cameraXR.near,
  16257. depthFar: cameraXR.far
  16258. } );
  16259. _currentDepthNear = cameraXR.near;
  16260. _currentDepthFar = cameraXR.far;
  16261. cameraL.near = _currentDepthNear;
  16262. cameraL.far = _currentDepthFar;
  16263. cameraR.near = _currentDepthNear;
  16264. cameraR.far = _currentDepthFar;
  16265. cameraL.updateProjectionMatrix();
  16266. cameraR.updateProjectionMatrix();
  16267. camera.updateProjectionMatrix();
  16268. }
  16269. const parent = camera.parent;
  16270. const cameras = cameraXR.cameras;
  16271. updateCamera( cameraXR, parent );
  16272. for ( let i = 0; i < cameras.length; i ++ ) {
  16273. updateCamera( cameras[ i ], parent );
  16274. }
  16275. // update projection matrix for proper view frustum culling
  16276. if ( cameras.length === 2 ) {
  16277. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16278. } else {
  16279. // assume single camera setup (AR)
  16280. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16281. }
  16282. // update user camera and its children
  16283. updateUserCamera( camera, cameraXR, parent );
  16284. };
  16285. function updateUserCamera( camera, cameraXR, parent ) {
  16286. if ( parent === null ) {
  16287. camera.matrix.copy( cameraXR.matrixWorld );
  16288. } else {
  16289. camera.matrix.copy( parent.matrixWorld );
  16290. camera.matrix.invert();
  16291. camera.matrix.multiply( cameraXR.matrixWorld );
  16292. }
  16293. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16294. camera.updateMatrixWorld( true );
  16295. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16296. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16297. if ( camera.isPerspectiveCamera ) {
  16298. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16299. camera.zoom = 1;
  16300. }
  16301. }
  16302. this.getCamera = function () {
  16303. return cameraXR;
  16304. };
  16305. this.getFoveation = function () {
  16306. if ( glProjLayer === null && glBaseLayer === null ) {
  16307. return undefined;
  16308. }
  16309. return foveation;
  16310. };
  16311. this.setFoveation = function ( value ) {
  16312. // 0 = no foveation = full resolution
  16313. // 1 = maximum foveation = the edges render at lower resolution
  16314. foveation = value;
  16315. if ( glProjLayer !== null ) {
  16316. glProjLayer.fixedFoveation = value;
  16317. }
  16318. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16319. glBaseLayer.fixedFoveation = value;
  16320. }
  16321. };
  16322. this.hasDepthSensing = function () {
  16323. return depthSensing.texture !== null;
  16324. };
  16325. this.getDepthSensingMesh = function () {
  16326. return depthSensing.getMesh( cameraXR );
  16327. };
  16328. // Animation Loop
  16329. let onAnimationFrameCallback = null;
  16330. function onAnimationFrame( time, frame ) {
  16331. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16332. xrFrame = frame;
  16333. if ( pose !== null ) {
  16334. const views = pose.views;
  16335. if ( glBaseLayer !== null ) {
  16336. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16337. renderer.setRenderTarget( newRenderTarget );
  16338. }
  16339. let cameraXRNeedsUpdate = false;
  16340. // check if it's necessary to rebuild cameraXR's camera list
  16341. if ( views.length !== cameraXR.cameras.length ) {
  16342. cameraXR.cameras.length = 0;
  16343. cameraXRNeedsUpdate = true;
  16344. }
  16345. for ( let i = 0; i < views.length; i ++ ) {
  16346. const view = views[ i ];
  16347. let viewport = null;
  16348. if ( glBaseLayer !== null ) {
  16349. viewport = glBaseLayer.getViewport( view );
  16350. } else {
  16351. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16352. viewport = glSubImage.viewport;
  16353. // For side-by-side projection, we only produce a single texture for both eyes.
  16354. if ( i === 0 ) {
  16355. renderer.setRenderTargetTextures(
  16356. newRenderTarget,
  16357. glSubImage.colorTexture,
  16358. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16359. renderer.setRenderTarget( newRenderTarget );
  16360. }
  16361. }
  16362. let camera = cameras[ i ];
  16363. if ( camera === undefined ) {
  16364. camera = new PerspectiveCamera();
  16365. camera.layers.enable( i );
  16366. camera.viewport = new Vector4();
  16367. cameras[ i ] = camera;
  16368. }
  16369. camera.matrix.fromArray( view.transform.matrix );
  16370. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16371. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16372. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16373. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16374. if ( i === 0 ) {
  16375. cameraXR.matrix.copy( camera.matrix );
  16376. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16377. }
  16378. if ( cameraXRNeedsUpdate === true ) {
  16379. cameraXR.cameras.push( camera );
  16380. }
  16381. }
  16382. //
  16383. const enabledFeatures = session.enabledFeatures;
  16384. if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) {
  16385. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  16386. if ( depthData && depthData.isValid && depthData.texture ) {
  16387. depthSensing.init( renderer, depthData, session.renderState );
  16388. }
  16389. }
  16390. }
  16391. //
  16392. for ( let i = 0; i < controllers.length; i ++ ) {
  16393. const inputSource = controllerInputSources[ i ];
  16394. const controller = controllers[ i ];
  16395. if ( inputSource !== null && controller !== undefined ) {
  16396. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16397. }
  16398. }
  16399. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16400. if ( frame.detectedPlanes ) {
  16401. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16402. }
  16403. xrFrame = null;
  16404. }
  16405. const animation = new WebGLAnimation();
  16406. animation.setAnimationLoop( onAnimationFrame );
  16407. this.setAnimationLoop = function ( callback ) {
  16408. onAnimationFrameCallback = callback;
  16409. };
  16410. this.dispose = function () {};
  16411. }
  16412. }
  16413. const _e1 = /*@__PURE__*/ new Euler();
  16414. const _m1 = /*@__PURE__*/ new Matrix4();
  16415. function WebGLMaterials( renderer, properties ) {
  16416. function refreshTransformUniform( map, uniform ) {
  16417. if ( map.matrixAutoUpdate === true ) {
  16418. map.updateMatrix();
  16419. }
  16420. uniform.value.copy( map.matrix );
  16421. }
  16422. function refreshFogUniforms( uniforms, fog ) {
  16423. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16424. if ( fog.isFog ) {
  16425. uniforms.fogNear.value = fog.near;
  16426. uniforms.fogFar.value = fog.far;
  16427. } else if ( fog.isFogExp2 ) {
  16428. uniforms.fogDensity.value = fog.density;
  16429. }
  16430. }
  16431. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16432. if ( material.isMeshBasicMaterial ) {
  16433. refreshUniformsCommon( uniforms, material );
  16434. } else if ( material.isMeshLambertMaterial ) {
  16435. refreshUniformsCommon( uniforms, material );
  16436. } else if ( material.isMeshToonMaterial ) {
  16437. refreshUniformsCommon( uniforms, material );
  16438. refreshUniformsToon( uniforms, material );
  16439. } else if ( material.isMeshPhongMaterial ) {
  16440. refreshUniformsCommon( uniforms, material );
  16441. refreshUniformsPhong( uniforms, material );
  16442. } else if ( material.isMeshStandardMaterial ) {
  16443. refreshUniformsCommon( uniforms, material );
  16444. refreshUniformsStandard( uniforms, material );
  16445. if ( material.isMeshPhysicalMaterial ) {
  16446. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16447. }
  16448. } else if ( material.isMeshMatcapMaterial ) {
  16449. refreshUniformsCommon( uniforms, material );
  16450. refreshUniformsMatcap( uniforms, material );
  16451. } else if ( material.isMeshDepthMaterial ) {
  16452. refreshUniformsCommon( uniforms, material );
  16453. } else if ( material.isMeshDistanceMaterial ) {
  16454. refreshUniformsCommon( uniforms, material );
  16455. refreshUniformsDistance( uniforms, material );
  16456. } else if ( material.isMeshNormalMaterial ) {
  16457. refreshUniformsCommon( uniforms, material );
  16458. } else if ( material.isLineBasicMaterial ) {
  16459. refreshUniformsLine( uniforms, material );
  16460. if ( material.isLineDashedMaterial ) {
  16461. refreshUniformsDash( uniforms, material );
  16462. }
  16463. } else if ( material.isPointsMaterial ) {
  16464. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16465. } else if ( material.isSpriteMaterial ) {
  16466. refreshUniformsSprites( uniforms, material );
  16467. } else if ( material.isShadowMaterial ) {
  16468. uniforms.color.value.copy( material.color );
  16469. uniforms.opacity.value = material.opacity;
  16470. } else if ( material.isShaderMaterial ) {
  16471. material.uniformsNeedUpdate = false; // #15581
  16472. }
  16473. }
  16474. function refreshUniformsCommon( uniforms, material ) {
  16475. uniforms.opacity.value = material.opacity;
  16476. if ( material.color ) {
  16477. uniforms.diffuse.value.copy( material.color );
  16478. }
  16479. if ( material.emissive ) {
  16480. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16481. }
  16482. if ( material.map ) {
  16483. uniforms.map.value = material.map;
  16484. refreshTransformUniform( material.map, uniforms.mapTransform );
  16485. }
  16486. if ( material.alphaMap ) {
  16487. uniforms.alphaMap.value = material.alphaMap;
  16488. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16489. }
  16490. if ( material.bumpMap ) {
  16491. uniforms.bumpMap.value = material.bumpMap;
  16492. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16493. uniforms.bumpScale.value = material.bumpScale;
  16494. if ( material.side === BackSide ) {
  16495. uniforms.bumpScale.value *= - 1;
  16496. }
  16497. }
  16498. if ( material.normalMap ) {
  16499. uniforms.normalMap.value = material.normalMap;
  16500. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16501. uniforms.normalScale.value.copy( material.normalScale );
  16502. if ( material.side === BackSide ) {
  16503. uniforms.normalScale.value.negate();
  16504. }
  16505. }
  16506. if ( material.displacementMap ) {
  16507. uniforms.displacementMap.value = material.displacementMap;
  16508. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16509. uniforms.displacementScale.value = material.displacementScale;
  16510. uniforms.displacementBias.value = material.displacementBias;
  16511. }
  16512. if ( material.emissiveMap ) {
  16513. uniforms.emissiveMap.value = material.emissiveMap;
  16514. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16515. }
  16516. if ( material.specularMap ) {
  16517. uniforms.specularMap.value = material.specularMap;
  16518. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16519. }
  16520. if ( material.alphaTest > 0 ) {
  16521. uniforms.alphaTest.value = material.alphaTest;
  16522. }
  16523. const materialProperties = properties.get( material );
  16524. const envMap = materialProperties.envMap;
  16525. const envMapRotation = materialProperties.envMapRotation;
  16526. if ( envMap ) {
  16527. uniforms.envMap.value = envMap;
  16528. _e1.copy( envMapRotation );
  16529. // accommodate left-handed frame
  16530. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  16531. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  16532. // environment maps which are not cube render targets or PMREMs follow a different convention
  16533. _e1.y *= - 1;
  16534. _e1.z *= - 1;
  16535. }
  16536. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  16537. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16538. uniforms.reflectivity.value = material.reflectivity;
  16539. uniforms.ior.value = material.ior;
  16540. uniforms.refractionRatio.value = material.refractionRatio;
  16541. }
  16542. if ( material.lightMap ) {
  16543. uniforms.lightMap.value = material.lightMap;
  16544. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  16545. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16546. }
  16547. if ( material.aoMap ) {
  16548. uniforms.aoMap.value = material.aoMap;
  16549. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16550. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16551. }
  16552. }
  16553. function refreshUniformsLine( uniforms, material ) {
  16554. uniforms.diffuse.value.copy( material.color );
  16555. uniforms.opacity.value = material.opacity;
  16556. if ( material.map ) {
  16557. uniforms.map.value = material.map;
  16558. refreshTransformUniform( material.map, uniforms.mapTransform );
  16559. }
  16560. }
  16561. function refreshUniformsDash( uniforms, material ) {
  16562. uniforms.dashSize.value = material.dashSize;
  16563. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16564. uniforms.scale.value = material.scale;
  16565. }
  16566. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16567. uniforms.diffuse.value.copy( material.color );
  16568. uniforms.opacity.value = material.opacity;
  16569. uniforms.size.value = material.size * pixelRatio;
  16570. uniforms.scale.value = height * 0.5;
  16571. if ( material.map ) {
  16572. uniforms.map.value = material.map;
  16573. refreshTransformUniform( material.map, uniforms.uvTransform );
  16574. }
  16575. if ( material.alphaMap ) {
  16576. uniforms.alphaMap.value = material.alphaMap;
  16577. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16578. }
  16579. if ( material.alphaTest > 0 ) {
  16580. uniforms.alphaTest.value = material.alphaTest;
  16581. }
  16582. }
  16583. function refreshUniformsSprites( uniforms, material ) {
  16584. uniforms.diffuse.value.copy( material.color );
  16585. uniforms.opacity.value = material.opacity;
  16586. uniforms.rotation.value = material.rotation;
  16587. if ( material.map ) {
  16588. uniforms.map.value = material.map;
  16589. refreshTransformUniform( material.map, uniforms.mapTransform );
  16590. }
  16591. if ( material.alphaMap ) {
  16592. uniforms.alphaMap.value = material.alphaMap;
  16593. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16594. }
  16595. if ( material.alphaTest > 0 ) {
  16596. uniforms.alphaTest.value = material.alphaTest;
  16597. }
  16598. }
  16599. function refreshUniformsPhong( uniforms, material ) {
  16600. uniforms.specular.value.copy( material.specular );
  16601. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16602. }
  16603. function refreshUniformsToon( uniforms, material ) {
  16604. if ( material.gradientMap ) {
  16605. uniforms.gradientMap.value = material.gradientMap;
  16606. }
  16607. }
  16608. function refreshUniformsStandard( uniforms, material ) {
  16609. uniforms.metalness.value = material.metalness;
  16610. if ( material.metalnessMap ) {
  16611. uniforms.metalnessMap.value = material.metalnessMap;
  16612. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16613. }
  16614. uniforms.roughness.value = material.roughness;
  16615. if ( material.roughnessMap ) {
  16616. uniforms.roughnessMap.value = material.roughnessMap;
  16617. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16618. }
  16619. if ( material.envMap ) {
  16620. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16621. uniforms.envMapIntensity.value = material.envMapIntensity;
  16622. }
  16623. }
  16624. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16625. uniforms.ior.value = material.ior; // also part of uniforms common
  16626. if ( material.sheen > 0 ) {
  16627. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16628. uniforms.sheenRoughness.value = material.sheenRoughness;
  16629. if ( material.sheenColorMap ) {
  16630. uniforms.sheenColorMap.value = material.sheenColorMap;
  16631. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16632. }
  16633. if ( material.sheenRoughnessMap ) {
  16634. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16635. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16636. }
  16637. }
  16638. if ( material.clearcoat > 0 ) {
  16639. uniforms.clearcoat.value = material.clearcoat;
  16640. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16641. if ( material.clearcoatMap ) {
  16642. uniforms.clearcoatMap.value = material.clearcoatMap;
  16643. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16644. }
  16645. if ( material.clearcoatRoughnessMap ) {
  16646. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16647. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16648. }
  16649. if ( material.clearcoatNormalMap ) {
  16650. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16651. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16652. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16653. if ( material.side === BackSide ) {
  16654. uniforms.clearcoatNormalScale.value.negate();
  16655. }
  16656. }
  16657. }
  16658. if ( material.dispersion > 0 ) {
  16659. uniforms.dispersion.value = material.dispersion;
  16660. }
  16661. if ( material.iridescence > 0 ) {
  16662. uniforms.iridescence.value = material.iridescence;
  16663. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16664. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16665. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16666. if ( material.iridescenceMap ) {
  16667. uniforms.iridescenceMap.value = material.iridescenceMap;
  16668. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16669. }
  16670. if ( material.iridescenceThicknessMap ) {
  16671. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16672. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16673. }
  16674. }
  16675. if ( material.transmission > 0 ) {
  16676. uniforms.transmission.value = material.transmission;
  16677. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16678. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16679. if ( material.transmissionMap ) {
  16680. uniforms.transmissionMap.value = material.transmissionMap;
  16681. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16682. }
  16683. uniforms.thickness.value = material.thickness;
  16684. if ( material.thicknessMap ) {
  16685. uniforms.thicknessMap.value = material.thicknessMap;
  16686. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16687. }
  16688. uniforms.attenuationDistance.value = material.attenuationDistance;
  16689. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16690. }
  16691. if ( material.anisotropy > 0 ) {
  16692. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16693. if ( material.anisotropyMap ) {
  16694. uniforms.anisotropyMap.value = material.anisotropyMap;
  16695. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16696. }
  16697. }
  16698. uniforms.specularIntensity.value = material.specularIntensity;
  16699. uniforms.specularColor.value.copy( material.specularColor );
  16700. if ( material.specularColorMap ) {
  16701. uniforms.specularColorMap.value = material.specularColorMap;
  16702. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16703. }
  16704. if ( material.specularIntensityMap ) {
  16705. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16706. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16707. }
  16708. }
  16709. function refreshUniformsMatcap( uniforms, material ) {
  16710. if ( material.matcap ) {
  16711. uniforms.matcap.value = material.matcap;
  16712. }
  16713. }
  16714. function refreshUniformsDistance( uniforms, material ) {
  16715. const light = properties.get( material ).light;
  16716. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16717. uniforms.nearDistance.value = light.shadow.camera.near;
  16718. uniforms.farDistance.value = light.shadow.camera.far;
  16719. }
  16720. return {
  16721. refreshFogUniforms: refreshFogUniforms,
  16722. refreshMaterialUniforms: refreshMaterialUniforms
  16723. };
  16724. }
  16725. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16726. let buffers = {};
  16727. let updateList = {};
  16728. let allocatedBindingPoints = [];
  16729. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  16730. function bind( uniformsGroup, program ) {
  16731. const webglProgram = program.program;
  16732. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16733. }
  16734. function update( uniformsGroup, program ) {
  16735. let buffer = buffers[ uniformsGroup.id ];
  16736. if ( buffer === undefined ) {
  16737. prepareUniformsGroup( uniformsGroup );
  16738. buffer = createBuffer( uniformsGroup );
  16739. buffers[ uniformsGroup.id ] = buffer;
  16740. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16741. }
  16742. // ensure to update the binding points/block indices mapping for this program
  16743. const webglProgram = program.program;
  16744. state.updateUBOMapping( uniformsGroup, webglProgram );
  16745. // update UBO once per frame
  16746. const frame = info.render.frame;
  16747. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16748. updateBufferData( uniformsGroup );
  16749. updateList[ uniformsGroup.id ] = frame;
  16750. }
  16751. }
  16752. function createBuffer( uniformsGroup ) {
  16753. // the setup of an UBO is independent of a particular shader program but global
  16754. const bindingPointIndex = allocateBindingPointIndex();
  16755. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16756. const buffer = gl.createBuffer();
  16757. const size = uniformsGroup.__size;
  16758. const usage = uniformsGroup.usage;
  16759. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16760. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16761. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16762. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16763. return buffer;
  16764. }
  16765. function allocateBindingPointIndex() {
  16766. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16767. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16768. allocatedBindingPoints.push( i );
  16769. return i;
  16770. }
  16771. }
  16772. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16773. return 0;
  16774. }
  16775. function updateBufferData( uniformsGroup ) {
  16776. const buffer = buffers[ uniformsGroup.id ];
  16777. const uniforms = uniformsGroup.uniforms;
  16778. const cache = uniformsGroup.__cache;
  16779. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16780. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16781. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16782. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16783. const uniform = uniformArray[ j ];
  16784. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  16785. const offset = uniform.__offset;
  16786. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16787. let arrayOffset = 0;
  16788. for ( let k = 0; k < values.length; k ++ ) {
  16789. const value = values[ k ];
  16790. const info = getUniformSize( value );
  16791. // TODO add integer and struct support
  16792. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16793. uniform.__data[ 0 ] = value;
  16794. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16795. } else if ( value.isMatrix3 ) {
  16796. // manually converting 3x3 to 3x4
  16797. uniform.__data[ 0 ] = value.elements[ 0 ];
  16798. uniform.__data[ 1 ] = value.elements[ 1 ];
  16799. uniform.__data[ 2 ] = value.elements[ 2 ];
  16800. uniform.__data[ 3 ] = 0;
  16801. uniform.__data[ 4 ] = value.elements[ 3 ];
  16802. uniform.__data[ 5 ] = value.elements[ 4 ];
  16803. uniform.__data[ 6 ] = value.elements[ 5 ];
  16804. uniform.__data[ 7 ] = 0;
  16805. uniform.__data[ 8 ] = value.elements[ 6 ];
  16806. uniform.__data[ 9 ] = value.elements[ 7 ];
  16807. uniform.__data[ 10 ] = value.elements[ 8 ];
  16808. uniform.__data[ 11 ] = 0;
  16809. } else {
  16810. value.toArray( uniform.__data, arrayOffset );
  16811. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16812. }
  16813. }
  16814. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16815. }
  16816. }
  16817. }
  16818. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16819. }
  16820. function hasUniformChanged( uniform, index, indexArray, cache ) {
  16821. const value = uniform.value;
  16822. const indexString = index + '_' + indexArray;
  16823. if ( cache[ indexString ] === undefined ) {
  16824. // cache entry does not exist so far
  16825. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16826. cache[ indexString ] = value;
  16827. } else {
  16828. cache[ indexString ] = value.clone();
  16829. }
  16830. return true;
  16831. } else {
  16832. const cachedObject = cache[ indexString ];
  16833. // compare current value with cached entry
  16834. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16835. if ( cachedObject !== value ) {
  16836. cache[ indexString ] = value;
  16837. return true;
  16838. }
  16839. } else {
  16840. if ( cachedObject.equals( value ) === false ) {
  16841. cachedObject.copy( value );
  16842. return true;
  16843. }
  16844. }
  16845. }
  16846. return false;
  16847. }
  16848. function prepareUniformsGroup( uniformsGroup ) {
  16849. // determine total buffer size according to the STD140 layout
  16850. // Hint: STD140 is the only supported layout in WebGL 2
  16851. const uniforms = uniformsGroup.uniforms;
  16852. let offset = 0; // global buffer offset in bytes
  16853. const chunkSize = 16; // size of a chunk in bytes
  16854. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16855. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16856. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16857. const uniform = uniformArray[ j ];
  16858. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16859. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  16860. const value = values[ k ];
  16861. const info = getUniformSize( value );
  16862. // Calculate the chunk offset
  16863. const chunkOffsetUniform = offset % chunkSize;
  16864. // Check for chunk overflow
  16865. if ( chunkOffsetUniform !== 0 && ( chunkSize - chunkOffsetUniform ) < info.boundary ) {
  16866. // Add padding and adjust offset
  16867. offset += ( chunkSize - chunkOffsetUniform );
  16868. }
  16869. // the following two properties will be used for partial buffer updates
  16870. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  16871. uniform.__offset = offset;
  16872. // Update the global offset
  16873. offset += info.storage;
  16874. }
  16875. }
  16876. }
  16877. // ensure correct final padding
  16878. const chunkOffset = offset % chunkSize;
  16879. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16880. //
  16881. uniformsGroup.__size = offset;
  16882. uniformsGroup.__cache = {};
  16883. return this;
  16884. }
  16885. function getUniformSize( value ) {
  16886. const info = {
  16887. boundary: 0, // bytes
  16888. storage: 0 // bytes
  16889. };
  16890. // determine sizes according to STD140
  16891. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16892. // float/int/bool
  16893. info.boundary = 4;
  16894. info.storage = 4;
  16895. } else if ( value.isVector2 ) {
  16896. // vec2
  16897. info.boundary = 8;
  16898. info.storage = 8;
  16899. } else if ( value.isVector3 || value.isColor ) {
  16900. // vec3
  16901. info.boundary = 16;
  16902. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16903. } else if ( value.isVector4 ) {
  16904. // vec4
  16905. info.boundary = 16;
  16906. info.storage = 16;
  16907. } else if ( value.isMatrix3 ) {
  16908. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16909. info.boundary = 48;
  16910. info.storage = 48;
  16911. } else if ( value.isMatrix4 ) {
  16912. // mat4
  16913. info.boundary = 64;
  16914. info.storage = 64;
  16915. } else if ( value.isTexture ) {
  16916. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16917. } else {
  16918. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16919. }
  16920. return info;
  16921. }
  16922. function onUniformsGroupsDispose( event ) {
  16923. const uniformsGroup = event.target;
  16924. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16925. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16926. allocatedBindingPoints.splice( index, 1 );
  16927. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16928. delete buffers[ uniformsGroup.id ];
  16929. delete updateList[ uniformsGroup.id ];
  16930. }
  16931. function dispose() {
  16932. for ( const id in buffers ) {
  16933. gl.deleteBuffer( buffers[ id ] );
  16934. }
  16935. allocatedBindingPoints = [];
  16936. buffers = {};
  16937. updateList = {};
  16938. }
  16939. return {
  16940. bind: bind,
  16941. update: update,
  16942. dispose: dispose
  16943. };
  16944. }
  16945. class WebGLRenderer {
  16946. constructor( parameters = {} ) {
  16947. const {
  16948. canvas = createCanvasElement(),
  16949. context = null,
  16950. depth = true,
  16951. stencil = false,
  16952. alpha = false,
  16953. antialias = false,
  16954. premultipliedAlpha = true,
  16955. preserveDrawingBuffer = false,
  16956. powerPreference = 'default',
  16957. failIfMajorPerformanceCaveat = false,
  16958. } = parameters;
  16959. this.isWebGLRenderer = true;
  16960. let _alpha;
  16961. if ( context !== null ) {
  16962. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  16963. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  16964. }
  16965. _alpha = context.getContextAttributes().alpha;
  16966. } else {
  16967. _alpha = alpha;
  16968. }
  16969. const uintClearColor = new Uint32Array( 4 );
  16970. const intClearColor = new Int32Array( 4 );
  16971. let currentRenderList = null;
  16972. let currentRenderState = null;
  16973. // render() can be called from within a callback triggered by another render.
  16974. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16975. const renderListStack = [];
  16976. const renderStateStack = [];
  16977. // public properties
  16978. this.domElement = canvas;
  16979. // Debug configuration container
  16980. this.debug = {
  16981. /**
  16982. * Enables error checking and reporting when shader programs are being compiled
  16983. * @type {boolean}
  16984. */
  16985. checkShaderErrors: true,
  16986. /**
  16987. * Callback for custom error reporting.
  16988. * @type {?Function}
  16989. */
  16990. onShaderError: null
  16991. };
  16992. // clearing
  16993. this.autoClear = true;
  16994. this.autoClearColor = true;
  16995. this.autoClearDepth = true;
  16996. this.autoClearStencil = true;
  16997. // scene graph
  16998. this.sortObjects = true;
  16999. // user-defined clipping
  17000. this.clippingPlanes = [];
  17001. this.localClippingEnabled = false;
  17002. // physically based shading
  17003. this._outputColorSpace = SRGBColorSpace;
  17004. // tone mapping
  17005. this.toneMapping = NoToneMapping;
  17006. this.toneMappingExposure = 1.0;
  17007. // internal properties
  17008. const _this = this;
  17009. let _isContextLost = false;
  17010. // internal state cache
  17011. let _currentActiveCubeFace = 0;
  17012. let _currentActiveMipmapLevel = 0;
  17013. let _currentRenderTarget = null;
  17014. let _currentMaterialId = - 1;
  17015. let _currentCamera = null;
  17016. const _currentViewport = new Vector4();
  17017. const _currentScissor = new Vector4();
  17018. let _currentScissorTest = null;
  17019. const _currentClearColor = new Color( 0x000000 );
  17020. let _currentClearAlpha = 0;
  17021. //
  17022. let _width = canvas.width;
  17023. let _height = canvas.height;
  17024. let _pixelRatio = 1;
  17025. let _opaqueSort = null;
  17026. let _transparentSort = null;
  17027. const _viewport = new Vector4( 0, 0, _width, _height );
  17028. const _scissor = new Vector4( 0, 0, _width, _height );
  17029. let _scissorTest = false;
  17030. // frustum
  17031. const _frustum = new Frustum();
  17032. // clipping
  17033. let _clippingEnabled = false;
  17034. let _localClippingEnabled = false;
  17035. // camera matrices cache
  17036. const _projScreenMatrix = new Matrix4();
  17037. const _vector3 = new Vector3();
  17038. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  17039. let _renderBackground = false;
  17040. function getTargetPixelRatio() {
  17041. return _currentRenderTarget === null ? _pixelRatio : 1;
  17042. }
  17043. // initialize
  17044. let _gl = context;
  17045. function getContext( contextName, contextAttributes ) {
  17046. return canvas.getContext( contextName, contextAttributes );
  17047. }
  17048. try {
  17049. const contextAttributes = {
  17050. alpha: true,
  17051. depth,
  17052. stencil,
  17053. antialias,
  17054. premultipliedAlpha,
  17055. preserveDrawingBuffer,
  17056. powerPreference,
  17057. failIfMajorPerformanceCaveat,
  17058. };
  17059. // OffscreenCanvas does not have setAttribute, see #22811
  17060. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  17061. // event listeners must be registered before WebGL context is created, see #12753
  17062. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17063. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17064. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17065. if ( _gl === null ) {
  17066. const contextName = 'webgl2';
  17067. _gl = getContext( contextName, contextAttributes );
  17068. if ( _gl === null ) {
  17069. if ( getContext( contextName ) ) {
  17070. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17071. } else {
  17072. throw new Error( 'Error creating WebGL context.' );
  17073. }
  17074. }
  17075. }
  17076. } catch ( error ) {
  17077. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17078. throw error;
  17079. }
  17080. let extensions, capabilities, state, info;
  17081. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  17082. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  17083. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17084. let utils, bindingStates, uniformsGroups;
  17085. function initGLContext() {
  17086. extensions = new WebGLExtensions( _gl );
  17087. extensions.init();
  17088. utils = new WebGLUtils( _gl, extensions );
  17089. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  17090. state = new WebGLState( _gl );
  17091. info = new WebGLInfo( _gl );
  17092. properties = new WebGLProperties();
  17093. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  17094. cubemaps = new WebGLCubeMaps( _this );
  17095. cubeuvmaps = new WebGLCubeUVMaps( _this );
  17096. attributes = new WebGLAttributes( _gl );
  17097. bindingStates = new WebGLBindingStates( _gl, attributes );
  17098. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  17099. objects = new WebGLObjects( _gl, geometries, attributes, info );
  17100. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  17101. clipping = new WebGLClipping( properties );
  17102. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  17103. materials = new WebGLMaterials( _this, properties );
  17104. renderLists = new WebGLRenderLists();
  17105. renderStates = new WebGLRenderStates( extensions );
  17106. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  17107. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  17108. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  17109. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  17110. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  17111. info.programs = programCache.programs;
  17112. _this.capabilities = capabilities;
  17113. _this.extensions = extensions;
  17114. _this.properties = properties;
  17115. _this.renderLists = renderLists;
  17116. _this.shadowMap = shadowMap;
  17117. _this.state = state;
  17118. _this.info = info;
  17119. }
  17120. initGLContext();
  17121. // xr
  17122. const xr = new WebXRManager( _this, _gl );
  17123. this.xr = xr;
  17124. // API
  17125. this.getContext = function () {
  17126. return _gl;
  17127. };
  17128. this.getContextAttributes = function () {
  17129. return _gl.getContextAttributes();
  17130. };
  17131. this.forceContextLoss = function () {
  17132. const extension = extensions.get( 'WEBGL_lose_context' );
  17133. if ( extension ) extension.loseContext();
  17134. };
  17135. this.forceContextRestore = function () {
  17136. const extension = extensions.get( 'WEBGL_lose_context' );
  17137. if ( extension ) extension.restoreContext();
  17138. };
  17139. this.getPixelRatio = function () {
  17140. return _pixelRatio;
  17141. };
  17142. this.setPixelRatio = function ( value ) {
  17143. if ( value === undefined ) return;
  17144. _pixelRatio = value;
  17145. this.setSize( _width, _height, false );
  17146. };
  17147. this.getSize = function ( target ) {
  17148. return target.set( _width, _height );
  17149. };
  17150. this.setSize = function ( width, height, updateStyle = true ) {
  17151. if ( xr.isPresenting ) {
  17152. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17153. return;
  17154. }
  17155. _width = width;
  17156. _height = height;
  17157. canvas.width = Math.floor( width * _pixelRatio );
  17158. canvas.height = Math.floor( height * _pixelRatio );
  17159. if ( updateStyle === true ) {
  17160. canvas.style.width = width + 'px';
  17161. canvas.style.height = height + 'px';
  17162. }
  17163. this.setViewport( 0, 0, width, height );
  17164. };
  17165. this.getDrawingBufferSize = function ( target ) {
  17166. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  17167. };
  17168. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17169. _width = width;
  17170. _height = height;
  17171. _pixelRatio = pixelRatio;
  17172. canvas.width = Math.floor( width * pixelRatio );
  17173. canvas.height = Math.floor( height * pixelRatio );
  17174. this.setViewport( 0, 0, width, height );
  17175. };
  17176. this.getCurrentViewport = function ( target ) {
  17177. return target.copy( _currentViewport );
  17178. };
  17179. this.getViewport = function ( target ) {
  17180. return target.copy( _viewport );
  17181. };
  17182. this.setViewport = function ( x, y, width, height ) {
  17183. if ( x.isVector4 ) {
  17184. _viewport.set( x.x, x.y, x.z, x.w );
  17185. } else {
  17186. _viewport.set( x, y, width, height );
  17187. }
  17188. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  17189. };
  17190. this.getScissor = function ( target ) {
  17191. return target.copy( _scissor );
  17192. };
  17193. this.setScissor = function ( x, y, width, height ) {
  17194. if ( x.isVector4 ) {
  17195. _scissor.set( x.x, x.y, x.z, x.w );
  17196. } else {
  17197. _scissor.set( x, y, width, height );
  17198. }
  17199. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  17200. };
  17201. this.getScissorTest = function () {
  17202. return _scissorTest;
  17203. };
  17204. this.setScissorTest = function ( boolean ) {
  17205. state.setScissorTest( _scissorTest = boolean );
  17206. };
  17207. this.setOpaqueSort = function ( method ) {
  17208. _opaqueSort = method;
  17209. };
  17210. this.setTransparentSort = function ( method ) {
  17211. _transparentSort = method;
  17212. };
  17213. // Clearing
  17214. this.getClearColor = function ( target ) {
  17215. return target.copy( background.getClearColor() );
  17216. };
  17217. this.setClearColor = function () {
  17218. background.setClearColor.apply( background, arguments );
  17219. };
  17220. this.getClearAlpha = function () {
  17221. return background.getClearAlpha();
  17222. };
  17223. this.setClearAlpha = function () {
  17224. background.setClearAlpha.apply( background, arguments );
  17225. };
  17226. this.clear = function ( color = true, depth = true, stencil = true ) {
  17227. let bits = 0;
  17228. if ( color ) {
  17229. // check if we're trying to clear an integer target
  17230. let isIntegerFormat = false;
  17231. if ( _currentRenderTarget !== null ) {
  17232. const targetFormat = _currentRenderTarget.texture.format;
  17233. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17234. targetFormat === RGIntegerFormat ||
  17235. targetFormat === RedIntegerFormat;
  17236. }
  17237. // use the appropriate clear functions to clear the target if it's a signed
  17238. // or unsigned integer target
  17239. if ( isIntegerFormat ) {
  17240. const targetType = _currentRenderTarget.texture.type;
  17241. const isUnsignedType = targetType === UnsignedByteType ||
  17242. targetType === UnsignedIntType ||
  17243. targetType === UnsignedShortType ||
  17244. targetType === UnsignedInt248Type ||
  17245. targetType === UnsignedShort4444Type ||
  17246. targetType === UnsignedShort5551Type;
  17247. const clearColor = background.getClearColor();
  17248. const a = background.getClearAlpha();
  17249. const r = clearColor.r;
  17250. const g = clearColor.g;
  17251. const b = clearColor.b;
  17252. if ( isUnsignedType ) {
  17253. uintClearColor[ 0 ] = r;
  17254. uintClearColor[ 1 ] = g;
  17255. uintClearColor[ 2 ] = b;
  17256. uintClearColor[ 3 ] = a;
  17257. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17258. } else {
  17259. intClearColor[ 0 ] = r;
  17260. intClearColor[ 1 ] = g;
  17261. intClearColor[ 2 ] = b;
  17262. intClearColor[ 3 ] = a;
  17263. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17264. }
  17265. } else {
  17266. bits |= _gl.COLOR_BUFFER_BIT;
  17267. }
  17268. }
  17269. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17270. if ( stencil ) {
  17271. bits |= _gl.STENCIL_BUFFER_BIT;
  17272. this.state.buffers.stencil.setMask( 0xffffffff );
  17273. }
  17274. _gl.clear( bits );
  17275. };
  17276. this.clearColor = function () {
  17277. this.clear( true, false, false );
  17278. };
  17279. this.clearDepth = function () {
  17280. this.clear( false, true, false );
  17281. };
  17282. this.clearStencil = function () {
  17283. this.clear( false, false, true );
  17284. };
  17285. //
  17286. this.dispose = function () {
  17287. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17288. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17289. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17290. renderLists.dispose();
  17291. renderStates.dispose();
  17292. properties.dispose();
  17293. cubemaps.dispose();
  17294. cubeuvmaps.dispose();
  17295. objects.dispose();
  17296. bindingStates.dispose();
  17297. uniformsGroups.dispose();
  17298. programCache.dispose();
  17299. xr.dispose();
  17300. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17301. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17302. animation.stop();
  17303. };
  17304. // Events
  17305. function onContextLost( event ) {
  17306. event.preventDefault();
  17307. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17308. _isContextLost = true;
  17309. }
  17310. function onContextRestore( /* event */ ) {
  17311. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17312. _isContextLost = false;
  17313. const infoAutoReset = info.autoReset;
  17314. const shadowMapEnabled = shadowMap.enabled;
  17315. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17316. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17317. const shadowMapType = shadowMap.type;
  17318. initGLContext();
  17319. info.autoReset = infoAutoReset;
  17320. shadowMap.enabled = shadowMapEnabled;
  17321. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17322. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17323. shadowMap.type = shadowMapType;
  17324. }
  17325. function onContextCreationError( event ) {
  17326. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17327. }
  17328. function onMaterialDispose( event ) {
  17329. const material = event.target;
  17330. material.removeEventListener( 'dispose', onMaterialDispose );
  17331. deallocateMaterial( material );
  17332. }
  17333. // Buffer deallocation
  17334. function deallocateMaterial( material ) {
  17335. releaseMaterialProgramReferences( material );
  17336. properties.remove( material );
  17337. }
  17338. function releaseMaterialProgramReferences( material ) {
  17339. const programs = properties.get( material ).programs;
  17340. if ( programs !== undefined ) {
  17341. programs.forEach( function ( program ) {
  17342. programCache.releaseProgram( program );
  17343. } );
  17344. if ( material.isShaderMaterial ) {
  17345. programCache.releaseShaderCache( material );
  17346. }
  17347. }
  17348. }
  17349. // Buffer rendering
  17350. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17351. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17352. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17353. const program = setProgram( camera, scene, geometry, material, object );
  17354. state.setMaterial( material, frontFaceCW );
  17355. //
  17356. let index = geometry.index;
  17357. let rangeFactor = 1;
  17358. if ( material.wireframe === true ) {
  17359. index = geometries.getWireframeAttribute( geometry );
  17360. if ( index === undefined ) return;
  17361. rangeFactor = 2;
  17362. }
  17363. //
  17364. const drawRange = geometry.drawRange;
  17365. const position = geometry.attributes.position;
  17366. let drawStart = drawRange.start * rangeFactor;
  17367. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17368. if ( group !== null ) {
  17369. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17370. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17371. }
  17372. if ( index !== null ) {
  17373. drawStart = Math.max( drawStart, 0 );
  17374. drawEnd = Math.min( drawEnd, index.count );
  17375. } else if ( position !== undefined && position !== null ) {
  17376. drawStart = Math.max( drawStart, 0 );
  17377. drawEnd = Math.min( drawEnd, position.count );
  17378. }
  17379. const drawCount = drawEnd - drawStart;
  17380. if ( drawCount < 0 || drawCount === Infinity ) return;
  17381. //
  17382. bindingStates.setup( object, material, program, geometry, index );
  17383. let attribute;
  17384. let renderer = bufferRenderer;
  17385. if ( index !== null ) {
  17386. attribute = attributes.get( index );
  17387. renderer = indexedBufferRenderer;
  17388. renderer.setIndex( attribute );
  17389. }
  17390. //
  17391. if ( object.isMesh ) {
  17392. if ( material.wireframe === true ) {
  17393. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17394. renderer.setMode( _gl.LINES );
  17395. } else {
  17396. renderer.setMode( _gl.TRIANGLES );
  17397. }
  17398. } else if ( object.isLine ) {
  17399. let lineWidth = material.linewidth;
  17400. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17401. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17402. if ( object.isLineSegments ) {
  17403. renderer.setMode( _gl.LINES );
  17404. } else if ( object.isLineLoop ) {
  17405. renderer.setMode( _gl.LINE_LOOP );
  17406. } else {
  17407. renderer.setMode( _gl.LINE_STRIP );
  17408. }
  17409. } else if ( object.isPoints ) {
  17410. renderer.setMode( _gl.POINTS );
  17411. } else if ( object.isSprite ) {
  17412. renderer.setMode( _gl.TRIANGLES );
  17413. }
  17414. if ( object.isBatchedMesh ) {
  17415. if ( object._multiDrawInstances !== null ) {
  17416. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  17417. } else {
  17418. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  17419. }
  17420. } else if ( object.isInstancedMesh ) {
  17421. renderer.renderInstances( drawStart, drawCount, object.count );
  17422. } else if ( geometry.isInstancedBufferGeometry ) {
  17423. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17424. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17425. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17426. } else {
  17427. renderer.render( drawStart, drawCount );
  17428. }
  17429. };
  17430. // Compile
  17431. function prepareMaterial( material, scene, object ) {
  17432. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17433. material.side = BackSide;
  17434. material.needsUpdate = true;
  17435. getProgram( material, scene, object );
  17436. material.side = FrontSide;
  17437. material.needsUpdate = true;
  17438. getProgram( material, scene, object );
  17439. material.side = DoubleSide;
  17440. } else {
  17441. getProgram( material, scene, object );
  17442. }
  17443. }
  17444. this.compile = function ( scene, camera, targetScene = null ) {
  17445. if ( targetScene === null ) targetScene = scene;
  17446. currentRenderState = renderStates.get( targetScene );
  17447. currentRenderState.init( camera );
  17448. renderStateStack.push( currentRenderState );
  17449. // gather lights from both the target scene and the new object that will be added to the scene.
  17450. targetScene.traverseVisible( function ( object ) {
  17451. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17452. currentRenderState.pushLight( object );
  17453. if ( object.castShadow ) {
  17454. currentRenderState.pushShadow( object );
  17455. }
  17456. }
  17457. } );
  17458. if ( scene !== targetScene ) {
  17459. scene.traverseVisible( function ( object ) {
  17460. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17461. currentRenderState.pushLight( object );
  17462. if ( object.castShadow ) {
  17463. currentRenderState.pushShadow( object );
  17464. }
  17465. }
  17466. } );
  17467. }
  17468. currentRenderState.setupLights();
  17469. // Only initialize materials in the new scene, not the targetScene.
  17470. const materials = new Set();
  17471. scene.traverse( function ( object ) {
  17472. const material = object.material;
  17473. if ( material ) {
  17474. if ( Array.isArray( material ) ) {
  17475. for ( let i = 0; i < material.length; i ++ ) {
  17476. const material2 = material[ i ];
  17477. prepareMaterial( material2, targetScene, object );
  17478. materials.add( material2 );
  17479. }
  17480. } else {
  17481. prepareMaterial( material, targetScene, object );
  17482. materials.add( material );
  17483. }
  17484. }
  17485. } );
  17486. renderStateStack.pop();
  17487. currentRenderState = null;
  17488. return materials;
  17489. };
  17490. // compileAsync
  17491. this.compileAsync = function ( scene, camera, targetScene = null ) {
  17492. const materials = this.compile( scene, camera, targetScene );
  17493. // Wait for all the materials in the new object to indicate that they're
  17494. // ready to be used before resolving the promise.
  17495. return new Promise( ( resolve ) => {
  17496. function checkMaterialsReady() {
  17497. materials.forEach( function ( material ) {
  17498. const materialProperties = properties.get( material );
  17499. const program = materialProperties.currentProgram;
  17500. if ( program.isReady() ) {
  17501. // remove any programs that report they're ready to use from the list
  17502. materials.delete( material );
  17503. }
  17504. } );
  17505. // once the list of compiling materials is empty, call the callback
  17506. if ( materials.size === 0 ) {
  17507. resolve( scene );
  17508. return;
  17509. }
  17510. // if some materials are still not ready, wait a bit and check again
  17511. setTimeout( checkMaterialsReady, 10 );
  17512. }
  17513. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  17514. // If we can check the compilation status of the materials without
  17515. // blocking then do so right away.
  17516. checkMaterialsReady();
  17517. } else {
  17518. // Otherwise start by waiting a bit to give the materials we just
  17519. // initialized a chance to finish.
  17520. setTimeout( checkMaterialsReady, 10 );
  17521. }
  17522. } );
  17523. };
  17524. // Animation Loop
  17525. let onAnimationFrameCallback = null;
  17526. function onAnimationFrame( time ) {
  17527. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17528. }
  17529. function onXRSessionStart() {
  17530. animation.stop();
  17531. }
  17532. function onXRSessionEnd() {
  17533. animation.start();
  17534. }
  17535. const animation = new WebGLAnimation();
  17536. animation.setAnimationLoop( onAnimationFrame );
  17537. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17538. this.setAnimationLoop = function ( callback ) {
  17539. onAnimationFrameCallback = callback;
  17540. xr.setAnimationLoop( callback );
  17541. ( callback === null ) ? animation.stop() : animation.start();
  17542. };
  17543. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17544. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17545. // Rendering
  17546. this.render = function ( scene, camera ) {
  17547. if ( camera !== undefined && camera.isCamera !== true ) {
  17548. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17549. return;
  17550. }
  17551. if ( _isContextLost === true ) return;
  17552. // update scene graph
  17553. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17554. // update camera matrices and frustum
  17555. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17556. if ( xr.enabled === true && xr.isPresenting === true ) {
  17557. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17558. camera = xr.getCamera(); // use XR camera for rendering
  17559. }
  17560. //
  17561. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17562. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17563. currentRenderState.init( camera );
  17564. renderStateStack.push( currentRenderState );
  17565. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17566. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17567. _localClippingEnabled = this.localClippingEnabled;
  17568. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17569. currentRenderList = renderLists.get( scene, renderListStack.length );
  17570. currentRenderList.init();
  17571. renderListStack.push( currentRenderList );
  17572. if ( xr.enabled === true && xr.isPresenting === true ) {
  17573. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  17574. if ( depthSensingMesh !== null ) {
  17575. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  17576. }
  17577. }
  17578. projectObject( scene, camera, 0, _this.sortObjects );
  17579. currentRenderList.finish();
  17580. if ( _this.sortObjects === true ) {
  17581. currentRenderList.sort( _opaqueSort, _transparentSort );
  17582. }
  17583. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  17584. if ( _renderBackground ) {
  17585. background.addToRenderList( currentRenderList, scene );
  17586. }
  17587. //
  17588. this.info.render.frame ++;
  17589. if ( _clippingEnabled === true ) clipping.beginShadows();
  17590. const shadowsArray = currentRenderState.state.shadowsArray;
  17591. shadowMap.render( shadowsArray, scene, camera );
  17592. if ( _clippingEnabled === true ) clipping.endShadows();
  17593. //
  17594. if ( this.info.autoReset === true ) this.info.reset();
  17595. // render scene
  17596. const opaqueObjects = currentRenderList.opaque;
  17597. const transmissiveObjects = currentRenderList.transmissive;
  17598. currentRenderState.setupLights();
  17599. if ( camera.isArrayCamera ) {
  17600. const cameras = camera.cameras;
  17601. if ( transmissiveObjects.length > 0 ) {
  17602. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17603. const camera2 = cameras[ i ];
  17604. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  17605. }
  17606. }
  17607. if ( _renderBackground ) background.render( scene );
  17608. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17609. const camera2 = cameras[ i ];
  17610. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17611. }
  17612. } else {
  17613. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17614. if ( _renderBackground ) background.render( scene );
  17615. renderScene( currentRenderList, scene, camera );
  17616. }
  17617. //
  17618. if ( _currentRenderTarget !== null ) {
  17619. // resolve multisample renderbuffers to a single-sample texture if necessary
  17620. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17621. // Generate mipmap if we're using any kind of mipmap filtering
  17622. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17623. }
  17624. //
  17625. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17626. // _gl.finish();
  17627. bindingStates.resetDefaultState();
  17628. _currentMaterialId = - 1;
  17629. _currentCamera = null;
  17630. renderStateStack.pop();
  17631. if ( renderStateStack.length > 0 ) {
  17632. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17633. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  17634. } else {
  17635. currentRenderState = null;
  17636. }
  17637. renderListStack.pop();
  17638. if ( renderListStack.length > 0 ) {
  17639. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17640. } else {
  17641. currentRenderList = null;
  17642. }
  17643. };
  17644. function projectObject( object, camera, groupOrder, sortObjects ) {
  17645. if ( object.visible === false ) return;
  17646. const visible = object.layers.test( camera.layers );
  17647. if ( visible ) {
  17648. if ( object.isGroup ) {
  17649. groupOrder = object.renderOrder;
  17650. } else if ( object.isLOD ) {
  17651. if ( object.autoUpdate === true ) object.update( camera );
  17652. } else if ( object.isLight ) {
  17653. currentRenderState.pushLight( object );
  17654. if ( object.castShadow ) {
  17655. currentRenderState.pushShadow( object );
  17656. }
  17657. } else if ( object.isSprite ) {
  17658. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17659. if ( sortObjects ) {
  17660. _vector3.setFromMatrixPosition( object.matrixWorld )
  17661. .applyMatrix4( _projScreenMatrix );
  17662. }
  17663. const geometry = objects.update( object );
  17664. const material = object.material;
  17665. if ( material.visible ) {
  17666. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17667. }
  17668. }
  17669. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17670. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17671. const geometry = objects.update( object );
  17672. const material = object.material;
  17673. if ( sortObjects ) {
  17674. if ( object.boundingSphere !== undefined ) {
  17675. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17676. _vector3.copy( object.boundingSphere.center );
  17677. } else {
  17678. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17679. _vector3.copy( geometry.boundingSphere.center );
  17680. }
  17681. _vector3
  17682. .applyMatrix4( object.matrixWorld )
  17683. .applyMatrix4( _projScreenMatrix );
  17684. }
  17685. if ( Array.isArray( material ) ) {
  17686. const groups = geometry.groups;
  17687. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17688. const group = groups[ i ];
  17689. const groupMaterial = material[ group.materialIndex ];
  17690. if ( groupMaterial && groupMaterial.visible ) {
  17691. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17692. }
  17693. }
  17694. } else if ( material.visible ) {
  17695. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17696. }
  17697. }
  17698. }
  17699. }
  17700. const children = object.children;
  17701. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17702. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17703. }
  17704. }
  17705. function renderScene( currentRenderList, scene, camera, viewport ) {
  17706. const opaqueObjects = currentRenderList.opaque;
  17707. const transmissiveObjects = currentRenderList.transmissive;
  17708. const transparentObjects = currentRenderList.transparent;
  17709. currentRenderState.setupLightsView( camera );
  17710. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17711. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17712. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17713. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17714. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17715. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17716. state.buffers.depth.setTest( true );
  17717. state.buffers.depth.setMask( true );
  17718. state.buffers.color.setMask( true );
  17719. state.setPolygonOffset( false );
  17720. }
  17721. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17722. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17723. if ( overrideMaterial !== null ) {
  17724. return;
  17725. }
  17726. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  17727. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  17728. generateMipmaps: true,
  17729. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  17730. minFilter: LinearMipmapLinearFilter,
  17731. samples: 4,
  17732. stencilBuffer: stencil,
  17733. resolveDepthBuffer: false,
  17734. resolveStencilBuffer: false,
  17735. colorSpace: ColorManagement.workingColorSpace,
  17736. } );
  17737. // debug
  17738. /*
  17739. const geometry = new PlaneGeometry();
  17740. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17741. const mesh = new Mesh( geometry, material );
  17742. scene.add( mesh );
  17743. */
  17744. }
  17745. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  17746. const activeViewport = camera.viewport || _currentViewport;
  17747. transmissionRenderTarget.setSize( activeViewport.z, activeViewport.w );
  17748. //
  17749. const currentRenderTarget = _this.getRenderTarget();
  17750. _this.setRenderTarget( transmissionRenderTarget );
  17751. _this.getClearColor( _currentClearColor );
  17752. _currentClearAlpha = _this.getClearAlpha();
  17753. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17754. if ( _renderBackground ) {
  17755. background.render( scene );
  17756. } else {
  17757. _this.clear();
  17758. }
  17759. // Turn off the features which can affect the frag color for opaque objects pass.
  17760. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17761. const currentToneMapping = _this.toneMapping;
  17762. _this.toneMapping = NoToneMapping;
  17763. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  17764. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  17765. const currentCameraViewport = camera.viewport;
  17766. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  17767. currentRenderState.setupLightsView( camera );
  17768. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17769. renderObjects( opaqueObjects, scene, camera );
  17770. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17771. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17772. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  17773. let renderTargetNeedsUpdate = false;
  17774. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17775. const renderItem = transmissiveObjects[ i ];
  17776. const object = renderItem.object;
  17777. const geometry = renderItem.geometry;
  17778. const material = renderItem.material;
  17779. const group = renderItem.group;
  17780. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17781. const currentSide = material.side;
  17782. material.side = BackSide;
  17783. material.needsUpdate = true;
  17784. renderObject( object, scene, camera, geometry, material, group );
  17785. material.side = currentSide;
  17786. material.needsUpdate = true;
  17787. renderTargetNeedsUpdate = true;
  17788. }
  17789. }
  17790. if ( renderTargetNeedsUpdate === true ) {
  17791. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17792. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17793. }
  17794. }
  17795. _this.setRenderTarget( currentRenderTarget );
  17796. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17797. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  17798. _this.toneMapping = currentToneMapping;
  17799. }
  17800. function renderObjects( renderList, scene, camera ) {
  17801. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17802. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17803. const renderItem = renderList[ i ];
  17804. const object = renderItem.object;
  17805. const geometry = renderItem.geometry;
  17806. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17807. const group = renderItem.group;
  17808. if ( object.layers.test( camera.layers ) ) {
  17809. renderObject( object, scene, camera, geometry, material, group );
  17810. }
  17811. }
  17812. }
  17813. function renderObject( object, scene, camera, geometry, material, group ) {
  17814. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17815. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17816. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17817. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17818. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17819. material.side = BackSide;
  17820. material.needsUpdate = true;
  17821. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17822. material.side = FrontSide;
  17823. material.needsUpdate = true;
  17824. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17825. material.side = DoubleSide;
  17826. } else {
  17827. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17828. }
  17829. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17830. }
  17831. function getProgram( material, scene, object ) {
  17832. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17833. const materialProperties = properties.get( material );
  17834. const lights = currentRenderState.state.lights;
  17835. const shadowsArray = currentRenderState.state.shadowsArray;
  17836. const lightsStateVersion = lights.state.version;
  17837. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17838. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17839. let programs = materialProperties.programs;
  17840. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17841. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17842. materialProperties.fog = scene.fog;
  17843. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17844. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  17845. if ( programs === undefined ) {
  17846. // new material
  17847. material.addEventListener( 'dispose', onMaterialDispose );
  17848. programs = new Map();
  17849. materialProperties.programs = programs;
  17850. }
  17851. let program = programs.get( programCacheKey );
  17852. if ( program !== undefined ) {
  17853. // early out if program and light state is identical
  17854. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17855. updateCommonMaterialProperties( material, parameters );
  17856. return program;
  17857. }
  17858. } else {
  17859. parameters.uniforms = programCache.getUniforms( material );
  17860. material.onBuild( object, parameters, _this );
  17861. material.onBeforeCompile( parameters, _this );
  17862. program = programCache.acquireProgram( parameters, programCacheKey );
  17863. programs.set( programCacheKey, program );
  17864. materialProperties.uniforms = parameters.uniforms;
  17865. }
  17866. const uniforms = materialProperties.uniforms;
  17867. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17868. uniforms.clippingPlanes = clipping.uniform;
  17869. }
  17870. updateCommonMaterialProperties( material, parameters );
  17871. // store the light setup it was created for
  17872. materialProperties.needsLights = materialNeedsLights( material );
  17873. materialProperties.lightsStateVersion = lightsStateVersion;
  17874. if ( materialProperties.needsLights ) {
  17875. // wire up the material to this renderer's lighting state
  17876. uniforms.ambientLightColor.value = lights.state.ambient;
  17877. uniforms.lightProbe.value = lights.state.probe;
  17878. uniforms.directionalLights.value = lights.state.directional;
  17879. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17880. uniforms.spotLights.value = lights.state.spot;
  17881. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17882. uniforms.rectAreaLights.value = lights.state.rectArea;
  17883. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17884. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17885. uniforms.pointLights.value = lights.state.point;
  17886. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17887. uniforms.hemisphereLights.value = lights.state.hemi;
  17888. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17889. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17890. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17891. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17892. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17893. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17894. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17895. // TODO (abelnation): add area lights shadow info to uniforms
  17896. }
  17897. materialProperties.currentProgram = program;
  17898. materialProperties.uniformsList = null;
  17899. return program;
  17900. }
  17901. function getUniformList( materialProperties ) {
  17902. if ( materialProperties.uniformsList === null ) {
  17903. const progUniforms = materialProperties.currentProgram.getUniforms();
  17904. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  17905. }
  17906. return materialProperties.uniformsList;
  17907. }
  17908. function updateCommonMaterialProperties( material, parameters ) {
  17909. const materialProperties = properties.get( material );
  17910. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17911. materialProperties.batching = parameters.batching;
  17912. materialProperties.batchingColor = parameters.batchingColor;
  17913. materialProperties.instancing = parameters.instancing;
  17914. materialProperties.instancingColor = parameters.instancingColor;
  17915. materialProperties.instancingMorph = parameters.instancingMorph;
  17916. materialProperties.skinning = parameters.skinning;
  17917. materialProperties.morphTargets = parameters.morphTargets;
  17918. materialProperties.morphNormals = parameters.morphNormals;
  17919. materialProperties.morphColors = parameters.morphColors;
  17920. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17921. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17922. materialProperties.numIntersection = parameters.numClipIntersection;
  17923. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17924. materialProperties.vertexTangents = parameters.vertexTangents;
  17925. materialProperties.toneMapping = parameters.toneMapping;
  17926. }
  17927. function setProgram( camera, scene, geometry, material, object ) {
  17928. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17929. textures.resetTextureUnits();
  17930. const fog = scene.fog;
  17931. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17932. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17933. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17934. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17935. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  17936. const morphTargets = !! geometry.morphAttributes.position;
  17937. const morphNormals = !! geometry.morphAttributes.normal;
  17938. const morphColors = !! geometry.morphAttributes.color;
  17939. let toneMapping = NoToneMapping;
  17940. if ( material.toneMapped ) {
  17941. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  17942. toneMapping = _this.toneMapping;
  17943. }
  17944. }
  17945. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17946. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17947. const materialProperties = properties.get( material );
  17948. const lights = currentRenderState.state.lights;
  17949. if ( _clippingEnabled === true ) {
  17950. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17951. const useCache =
  17952. camera === _currentCamera &&
  17953. material.id === _currentMaterialId;
  17954. // we might want to call this function with some ClippingGroup
  17955. // object instead of the material, once it becomes feasible
  17956. // (#8465, #8379)
  17957. clipping.setState( material, camera, useCache );
  17958. }
  17959. }
  17960. //
  17961. let needsProgramChange = false;
  17962. if ( material.version === materialProperties.__version ) {
  17963. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17964. needsProgramChange = true;
  17965. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17966. needsProgramChange = true;
  17967. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  17968. needsProgramChange = true;
  17969. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  17970. needsProgramChange = true;
  17971. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  17972. needsProgramChange = true;
  17973. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  17974. needsProgramChange = true;
  17975. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17976. needsProgramChange = true;
  17977. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17978. needsProgramChange = true;
  17979. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17980. needsProgramChange = true;
  17981. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17982. needsProgramChange = true;
  17983. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  17984. needsProgramChange = true;
  17985. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  17986. needsProgramChange = true;
  17987. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  17988. needsProgramChange = true;
  17989. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  17990. needsProgramChange = true;
  17991. } else if ( materialProperties.envMap !== envMap ) {
  17992. needsProgramChange = true;
  17993. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17994. needsProgramChange = true;
  17995. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17996. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17997. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17998. needsProgramChange = true;
  17999. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  18000. needsProgramChange = true;
  18001. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  18002. needsProgramChange = true;
  18003. } else if ( materialProperties.morphTargets !== morphTargets ) {
  18004. needsProgramChange = true;
  18005. } else if ( materialProperties.morphNormals !== morphNormals ) {
  18006. needsProgramChange = true;
  18007. } else if ( materialProperties.morphColors !== morphColors ) {
  18008. needsProgramChange = true;
  18009. } else if ( materialProperties.toneMapping !== toneMapping ) {
  18010. needsProgramChange = true;
  18011. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  18012. needsProgramChange = true;
  18013. }
  18014. } else {
  18015. needsProgramChange = true;
  18016. materialProperties.__version = material.version;
  18017. }
  18018. //
  18019. let program = materialProperties.currentProgram;
  18020. if ( needsProgramChange === true ) {
  18021. program = getProgram( material, scene, object );
  18022. }
  18023. let refreshProgram = false;
  18024. let refreshMaterial = false;
  18025. let refreshLights = false;
  18026. const p_uniforms = program.getUniforms(),
  18027. m_uniforms = materialProperties.uniforms;
  18028. if ( state.useProgram( program.program ) ) {
  18029. refreshProgram = true;
  18030. refreshMaterial = true;
  18031. refreshLights = true;
  18032. }
  18033. if ( material.id !== _currentMaterialId ) {
  18034. _currentMaterialId = material.id;
  18035. refreshMaterial = true;
  18036. }
  18037. if ( refreshProgram || _currentCamera !== camera ) {
  18038. // common camera uniforms
  18039. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  18040. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  18041. const uCamPos = p_uniforms.map.cameraPosition;
  18042. if ( uCamPos !== undefined ) {
  18043. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  18044. }
  18045. if ( capabilities.logarithmicDepthBuffer ) {
  18046. p_uniforms.setValue( _gl, 'logDepthBufFC',
  18047. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  18048. }
  18049. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  18050. if ( material.isMeshPhongMaterial ||
  18051. material.isMeshToonMaterial ||
  18052. material.isMeshLambertMaterial ||
  18053. material.isMeshBasicMaterial ||
  18054. material.isMeshStandardMaterial ||
  18055. material.isShaderMaterial ) {
  18056. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  18057. }
  18058. if ( _currentCamera !== camera ) {
  18059. _currentCamera = camera;
  18060. // lighting uniforms depend on the camera so enforce an update
  18061. // now, in case this material supports lights - or later, when
  18062. // the next material that does gets activated:
  18063. refreshMaterial = true; // set to true on material change
  18064. refreshLights = true; // remains set until update done
  18065. }
  18066. }
  18067. // skinning and morph target uniforms must be set even if material didn't change
  18068. // auto-setting of texture unit for bone and morph texture must go before other textures
  18069. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  18070. if ( object.isSkinnedMesh ) {
  18071. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  18072. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  18073. const skeleton = object.skeleton;
  18074. if ( skeleton ) {
  18075. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  18076. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  18077. }
  18078. }
  18079. if ( object.isBatchedMesh ) {
  18080. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  18081. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  18082. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  18083. if ( object._colorsTexture !== null ) {
  18084. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  18085. }
  18086. }
  18087. const morphAttributes = geometry.morphAttributes;
  18088. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  18089. morphtargets.update( object, geometry, program );
  18090. }
  18091. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  18092. materialProperties.receiveShadow = object.receiveShadow;
  18093. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  18094. }
  18095. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  18096. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  18097. m_uniforms.envMap.value = envMap;
  18098. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  18099. }
  18100. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  18101. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  18102. }
  18103. if ( refreshMaterial ) {
  18104. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  18105. if ( materialProperties.needsLights ) {
  18106. // the current material requires lighting info
  18107. // note: all lighting uniforms are always set correctly
  18108. // they simply reference the renderer's state for their
  18109. // values
  18110. //
  18111. // use the current material's .needsUpdate flags to set
  18112. // the GL state when required
  18113. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18114. }
  18115. // refresh uniforms common to several materials
  18116. if ( fog && material.fog === true ) {
  18117. materials.refreshFogUniforms( m_uniforms, fog );
  18118. }
  18119. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  18120. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18121. }
  18122. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  18123. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18124. material.uniformsNeedUpdate = false;
  18125. }
  18126. if ( material.isSpriteMaterial ) {
  18127. p_uniforms.setValue( _gl, 'center', object.center );
  18128. }
  18129. // common matrices
  18130. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18131. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18132. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18133. // UBOs
  18134. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  18135. const groups = material.uniformsGroups;
  18136. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  18137. const group = groups[ i ];
  18138. uniformsGroups.update( group, program );
  18139. uniformsGroups.bind( group, program );
  18140. }
  18141. }
  18142. return program;
  18143. }
  18144. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18145. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18146. uniforms.ambientLightColor.needsUpdate = value;
  18147. uniforms.lightProbe.needsUpdate = value;
  18148. uniforms.directionalLights.needsUpdate = value;
  18149. uniforms.directionalLightShadows.needsUpdate = value;
  18150. uniforms.pointLights.needsUpdate = value;
  18151. uniforms.pointLightShadows.needsUpdate = value;
  18152. uniforms.spotLights.needsUpdate = value;
  18153. uniforms.spotLightShadows.needsUpdate = value;
  18154. uniforms.rectAreaLights.needsUpdate = value;
  18155. uniforms.hemisphereLights.needsUpdate = value;
  18156. }
  18157. function materialNeedsLights( material ) {
  18158. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  18159. material.isMeshStandardMaterial || material.isShadowMaterial ||
  18160. ( material.isShaderMaterial && material.lights === true );
  18161. }
  18162. this.getActiveCubeFace = function () {
  18163. return _currentActiveCubeFace;
  18164. };
  18165. this.getActiveMipmapLevel = function () {
  18166. return _currentActiveMipmapLevel;
  18167. };
  18168. this.getRenderTarget = function () {
  18169. return _currentRenderTarget;
  18170. };
  18171. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  18172. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  18173. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  18174. const renderTargetProperties = properties.get( renderTarget );
  18175. renderTargetProperties.__hasExternalTextures = true;
  18176. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  18177. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  18178. // The multisample_render_to_texture extension doesn't work properly if there
  18179. // are midframe flushes and an external depth buffer. Disable use of the extension.
  18180. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  18181. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  18182. renderTargetProperties.__useRenderToTexture = false;
  18183. }
  18184. }
  18185. };
  18186. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  18187. const renderTargetProperties = properties.get( renderTarget );
  18188. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  18189. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  18190. };
  18191. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  18192. _currentRenderTarget = renderTarget;
  18193. _currentActiveCubeFace = activeCubeFace;
  18194. _currentActiveMipmapLevel = activeMipmapLevel;
  18195. let useDefaultFramebuffer = true;
  18196. let framebuffer = null;
  18197. let isCube = false;
  18198. let isRenderTarget3D = false;
  18199. if ( renderTarget ) {
  18200. const renderTargetProperties = properties.get( renderTarget );
  18201. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  18202. // We need to make sure to rebind the framebuffer.
  18203. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  18204. useDefaultFramebuffer = false;
  18205. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  18206. textures.setupRenderTarget( renderTarget );
  18207. } else if ( renderTargetProperties.__hasExternalTextures ) {
  18208. // Color and depth texture must be rebound in order for the swapchain to update.
  18209. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  18210. }
  18211. const texture = renderTarget.texture;
  18212. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18213. isRenderTarget3D = true;
  18214. }
  18215. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18216. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18217. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  18218. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  18219. } else {
  18220. framebuffer = __webglFramebuffer[ activeCubeFace ];
  18221. }
  18222. isCube = true;
  18223. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  18224. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  18225. } else {
  18226. if ( Array.isArray( __webglFramebuffer ) ) {
  18227. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  18228. } else {
  18229. framebuffer = __webglFramebuffer;
  18230. }
  18231. }
  18232. _currentViewport.copy( renderTarget.viewport );
  18233. _currentScissor.copy( renderTarget.scissor );
  18234. _currentScissorTest = renderTarget.scissorTest;
  18235. } else {
  18236. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  18237. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  18238. _currentScissorTest = _scissorTest;
  18239. }
  18240. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18241. if ( framebufferBound && useDefaultFramebuffer ) {
  18242. state.drawBuffers( renderTarget, framebuffer );
  18243. }
  18244. state.viewport( _currentViewport );
  18245. state.scissor( _currentScissor );
  18246. state.setScissorTest( _currentScissorTest );
  18247. if ( isCube ) {
  18248. const textureProperties = properties.get( renderTarget.texture );
  18249. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  18250. } else if ( isRenderTarget3D ) {
  18251. const textureProperties = properties.get( renderTarget.texture );
  18252. const layer = activeCubeFace || 0;
  18253. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  18254. }
  18255. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  18256. };
  18257. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18258. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18259. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18260. return;
  18261. }
  18262. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18263. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18264. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18265. }
  18266. if ( framebuffer ) {
  18267. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18268. try {
  18269. const texture = renderTarget.texture;
  18270. const textureFormat = texture.format;
  18271. const textureType = texture.type;
  18272. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  18273. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18274. return;
  18275. }
  18276. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  18277. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18278. return;
  18279. }
  18280. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18281. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18282. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18283. }
  18284. } finally {
  18285. // restore framebuffer of current render target if necessary
  18286. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18287. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18288. }
  18289. }
  18290. };
  18291. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18292. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18293. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18294. }
  18295. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18296. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18297. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18298. }
  18299. if ( framebuffer ) {
  18300. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18301. try {
  18302. const texture = renderTarget.texture;
  18303. const textureFormat = texture.format;
  18304. const textureType = texture.type;
  18305. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  18306. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  18307. }
  18308. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  18309. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18310. }
  18311. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18312. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18313. const glBuffer = _gl.createBuffer();
  18314. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  18315. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  18316. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  18317. _gl.flush();
  18318. // check if the commands have finished every 8 ms
  18319. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  18320. await probeAsync( _gl, sync, 4 );
  18321. try {
  18322. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  18323. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  18324. } finally {
  18325. _gl.deleteBuffer( glBuffer );
  18326. _gl.deleteSync( sync );
  18327. }
  18328. return buffer;
  18329. }
  18330. } finally {
  18331. // restore framebuffer of current render target if necessary
  18332. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18333. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18334. }
  18335. }
  18336. };
  18337. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  18338. // support previous signature with position first
  18339. if ( texture.isTexture !== true ) {
  18340. // @deprecated, r165
  18341. console.warn( 'WebGLRenderer: copyFramebufferToTexture function signature has changed.' );
  18342. position = arguments[ 0 ] || null;
  18343. texture = arguments[ 1 ];
  18344. }
  18345. const levelScale = Math.pow( 2, - level );
  18346. const width = Math.floor( texture.image.width * levelScale );
  18347. const height = Math.floor( texture.image.height * levelScale );
  18348. const x = position !== null ? position.x : 0;
  18349. const y = position !== null ? position.y : 0;
  18350. textures.setTexture2D( texture, 0 );
  18351. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  18352. state.unbindTexture();
  18353. };
  18354. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  18355. // support previous signature with dstPosition first
  18356. if ( srcTexture.isTexture !== true ) {
  18357. // @deprecated, r165
  18358. console.warn( 'WebGLRenderer: copyTextureToTexture function signature has changed.' );
  18359. dstPosition = arguments[ 0 ] || null;
  18360. srcTexture = arguments[ 1 ];
  18361. dstTexture = arguments[ 2 ];
  18362. level = arguments[ 3 ] || 0;
  18363. srcRegion = null;
  18364. }
  18365. let width, height, minX, minY;
  18366. let dstX, dstY;
  18367. if ( srcRegion !== null ) {
  18368. width = srcRegion.max.x - srcRegion.min.x;
  18369. height = srcRegion.max.y - srcRegion.min.y;
  18370. minX = srcRegion.min.x;
  18371. minY = srcRegion.min.y;
  18372. } else {
  18373. width = srcTexture.image.width;
  18374. height = srcTexture.image.height;
  18375. minX = 0;
  18376. minY = 0;
  18377. }
  18378. if ( dstPosition !== null ) {
  18379. dstX = dstPosition.x;
  18380. dstY = dstPosition.y;
  18381. } else {
  18382. dstX = 0;
  18383. dstY = 0;
  18384. }
  18385. const glFormat = utils.convert( dstTexture.format );
  18386. const glType = utils.convert( dstTexture.type );
  18387. textures.setTexture2D( dstTexture, 0 );
  18388. // As another texture upload may have changed pixelStorei
  18389. // parameters, make sure they are correct for the dstTexture
  18390. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18391. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18392. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18393. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18394. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18395. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18396. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18397. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18398. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18399. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18400. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18401. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  18402. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  18403. if ( srcTexture.isDataTexture ) {
  18404. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  18405. } else {
  18406. if ( srcTexture.isCompressedTexture ) {
  18407. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  18408. } else {
  18409. _gl.texSubImage2D( _gl.TEXTURE_2D, level, dstX, dstY, glFormat, glType, image );
  18410. }
  18411. }
  18412. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  18413. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  18414. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  18415. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  18416. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  18417. // Generate mipmaps only when copying level 0
  18418. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18419. state.unbindTexture();
  18420. };
  18421. this.copyTextureToTexture3D = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  18422. // support previous signature with source box first
  18423. if ( srcTexture.isTexture !== true ) {
  18424. // @deprecated, r165
  18425. console.warn( 'WebGLRenderer: copyTextureToTexture3D function signature has changed.' );
  18426. srcRegion = arguments[ 0 ] || null;
  18427. dstPosition = arguments[ 1 ] || null;
  18428. srcTexture = arguments[ 2 ];
  18429. dstTexture = arguments[ 3 ];
  18430. level = arguments[ 4 ] || 0;
  18431. }
  18432. let width, height, depth, minX, minY, minZ;
  18433. let dstX, dstY, dstZ;
  18434. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18435. if ( srcRegion !== null ) {
  18436. width = srcRegion.max.x - srcRegion.min.x;
  18437. height = srcRegion.max.y - srcRegion.min.y;
  18438. depth = srcRegion.max.z - srcRegion.min.z;
  18439. minX = srcRegion.min.x;
  18440. minY = srcRegion.min.y;
  18441. minZ = srcRegion.min.z;
  18442. } else {
  18443. width = image.width;
  18444. height = image.height;
  18445. depth = image.depth;
  18446. minX = 0;
  18447. minY = 0;
  18448. minZ = 0;
  18449. }
  18450. if ( dstPosition !== null ) {
  18451. dstX = dstPosition.x;
  18452. dstY = dstPosition.y;
  18453. dstZ = dstPosition.z;
  18454. } else {
  18455. dstX = 0;
  18456. dstY = 0;
  18457. dstZ = 0;
  18458. }
  18459. const glFormat = utils.convert( dstTexture.format );
  18460. const glType = utils.convert( dstTexture.type );
  18461. let glTarget;
  18462. if ( dstTexture.isData3DTexture ) {
  18463. textures.setTexture3D( dstTexture, 0 );
  18464. glTarget = _gl.TEXTURE_3D;
  18465. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  18466. textures.setTexture2DArray( dstTexture, 0 );
  18467. glTarget = _gl.TEXTURE_2D_ARRAY;
  18468. } else {
  18469. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18470. return;
  18471. }
  18472. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18473. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18474. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18475. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18476. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18477. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18478. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18479. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18480. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18481. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18482. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  18483. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  18484. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  18485. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18486. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  18487. } else {
  18488. if ( dstTexture.isCompressedArrayTexture ) {
  18489. _gl.compressedTexSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  18490. } else {
  18491. _gl.texSubImage3D( glTarget, level, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  18492. }
  18493. }
  18494. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  18495. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  18496. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  18497. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  18498. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  18499. // Generate mipmaps only when copying level 0
  18500. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18501. state.unbindTexture();
  18502. };
  18503. this.initRenderTarget = function ( target ) {
  18504. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  18505. textures.setupRenderTarget( target );
  18506. }
  18507. };
  18508. this.initTexture = function ( texture ) {
  18509. if ( texture.isCubeTexture ) {
  18510. textures.setTextureCube( texture, 0 );
  18511. } else if ( texture.isData3DTexture ) {
  18512. textures.setTexture3D( texture, 0 );
  18513. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18514. textures.setTexture2DArray( texture, 0 );
  18515. } else {
  18516. textures.setTexture2D( texture, 0 );
  18517. }
  18518. state.unbindTexture();
  18519. };
  18520. this.resetState = function () {
  18521. _currentActiveCubeFace = 0;
  18522. _currentActiveMipmapLevel = 0;
  18523. _currentRenderTarget = null;
  18524. state.reset();
  18525. bindingStates.reset();
  18526. };
  18527. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18528. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18529. }
  18530. }
  18531. get coordinateSystem() {
  18532. return WebGLCoordinateSystem;
  18533. }
  18534. get outputColorSpace() {
  18535. return this._outputColorSpace;
  18536. }
  18537. set outputColorSpace( colorSpace ) {
  18538. this._outputColorSpace = colorSpace;
  18539. const gl = this.getContext();
  18540. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18541. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18542. }
  18543. }
  18544. class FogExp2 {
  18545. constructor( color, density = 0.00025 ) {
  18546. this.isFogExp2 = true;
  18547. this.name = '';
  18548. this.color = new Color( color );
  18549. this.density = density;
  18550. }
  18551. clone() {
  18552. return new FogExp2( this.color, this.density );
  18553. }
  18554. toJSON( /* meta */ ) {
  18555. return {
  18556. type: 'FogExp2',
  18557. name: this.name,
  18558. color: this.color.getHex(),
  18559. density: this.density
  18560. };
  18561. }
  18562. }
  18563. class Fog {
  18564. constructor( color, near = 1, far = 1000 ) {
  18565. this.isFog = true;
  18566. this.name = '';
  18567. this.color = new Color( color );
  18568. this.near = near;
  18569. this.far = far;
  18570. }
  18571. clone() {
  18572. return new Fog( this.color, this.near, this.far );
  18573. }
  18574. toJSON( /* meta */ ) {
  18575. return {
  18576. type: 'Fog',
  18577. name: this.name,
  18578. color: this.color.getHex(),
  18579. near: this.near,
  18580. far: this.far
  18581. };
  18582. }
  18583. }
  18584. class Scene extends Object3D {
  18585. constructor() {
  18586. super();
  18587. this.isScene = true;
  18588. this.type = 'Scene';
  18589. this.background = null;
  18590. this.environment = null;
  18591. this.fog = null;
  18592. this.backgroundBlurriness = 0;
  18593. this.backgroundIntensity = 1;
  18594. this.backgroundRotation = new Euler();
  18595. this.environmentIntensity = 1;
  18596. this.environmentRotation = new Euler();
  18597. this.overrideMaterial = null;
  18598. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18599. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18600. }
  18601. }
  18602. copy( source, recursive ) {
  18603. super.copy( source, recursive );
  18604. if ( source.background !== null ) this.background = source.background.clone();
  18605. if ( source.environment !== null ) this.environment = source.environment.clone();
  18606. if ( source.fog !== null ) this.fog = source.fog.clone();
  18607. this.backgroundBlurriness = source.backgroundBlurriness;
  18608. this.backgroundIntensity = source.backgroundIntensity;
  18609. this.backgroundRotation.copy( source.backgroundRotation );
  18610. this.environmentIntensity = source.environmentIntensity;
  18611. this.environmentRotation.copy( source.environmentRotation );
  18612. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18613. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18614. return this;
  18615. }
  18616. toJSON( meta ) {
  18617. const data = super.toJSON( meta );
  18618. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18619. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18620. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18621. data.object.backgroundRotation = this.backgroundRotation.toArray();
  18622. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  18623. data.object.environmentRotation = this.environmentRotation.toArray();
  18624. return data;
  18625. }
  18626. }
  18627. class InterleavedBuffer {
  18628. constructor( array, stride ) {
  18629. this.isInterleavedBuffer = true;
  18630. this.array = array;
  18631. this.stride = stride;
  18632. this.count = array !== undefined ? array.length / stride : 0;
  18633. this.usage = StaticDrawUsage;
  18634. this._updateRange = { offset: 0, count: - 1 };
  18635. this.updateRanges = [];
  18636. this.version = 0;
  18637. this.uuid = generateUUID();
  18638. }
  18639. onUploadCallback() {}
  18640. set needsUpdate( value ) {
  18641. if ( value === true ) this.version ++;
  18642. }
  18643. get updateRange() {
  18644. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  18645. return this._updateRange;
  18646. }
  18647. setUsage( value ) {
  18648. this.usage = value;
  18649. return this;
  18650. }
  18651. addUpdateRange( start, count ) {
  18652. this.updateRanges.push( { start, count } );
  18653. }
  18654. clearUpdateRanges() {
  18655. this.updateRanges.length = 0;
  18656. }
  18657. copy( source ) {
  18658. this.array = new source.array.constructor( source.array );
  18659. this.count = source.count;
  18660. this.stride = source.stride;
  18661. this.usage = source.usage;
  18662. return this;
  18663. }
  18664. copyAt( index1, attribute, index2 ) {
  18665. index1 *= this.stride;
  18666. index2 *= attribute.stride;
  18667. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18668. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18669. }
  18670. return this;
  18671. }
  18672. set( value, offset = 0 ) {
  18673. this.array.set( value, offset );
  18674. return this;
  18675. }
  18676. clone( data ) {
  18677. if ( data.arrayBuffers === undefined ) {
  18678. data.arrayBuffers = {};
  18679. }
  18680. if ( this.array.buffer._uuid === undefined ) {
  18681. this.array.buffer._uuid = generateUUID();
  18682. }
  18683. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18684. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18685. }
  18686. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18687. const ib = new this.constructor( array, this.stride );
  18688. ib.setUsage( this.usage );
  18689. return ib;
  18690. }
  18691. onUpload( callback ) {
  18692. this.onUploadCallback = callback;
  18693. return this;
  18694. }
  18695. toJSON( data ) {
  18696. if ( data.arrayBuffers === undefined ) {
  18697. data.arrayBuffers = {};
  18698. }
  18699. // generate UUID for array buffer if necessary
  18700. if ( this.array.buffer._uuid === undefined ) {
  18701. this.array.buffer._uuid = generateUUID();
  18702. }
  18703. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18704. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18705. }
  18706. //
  18707. return {
  18708. uuid: this.uuid,
  18709. buffer: this.array.buffer._uuid,
  18710. type: this.array.constructor.name,
  18711. stride: this.stride
  18712. };
  18713. }
  18714. }
  18715. const _vector$6 = /*@__PURE__*/ new Vector3();
  18716. class InterleavedBufferAttribute {
  18717. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18718. this.isInterleavedBufferAttribute = true;
  18719. this.name = '';
  18720. this.data = interleavedBuffer;
  18721. this.itemSize = itemSize;
  18722. this.offset = offset;
  18723. this.normalized = normalized;
  18724. }
  18725. get count() {
  18726. return this.data.count;
  18727. }
  18728. get array() {
  18729. return this.data.array;
  18730. }
  18731. set needsUpdate( value ) {
  18732. this.data.needsUpdate = value;
  18733. }
  18734. applyMatrix4( m ) {
  18735. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18736. _vector$6.fromBufferAttribute( this, i );
  18737. _vector$6.applyMatrix4( m );
  18738. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18739. }
  18740. return this;
  18741. }
  18742. applyNormalMatrix( m ) {
  18743. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18744. _vector$6.fromBufferAttribute( this, i );
  18745. _vector$6.applyNormalMatrix( m );
  18746. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18747. }
  18748. return this;
  18749. }
  18750. transformDirection( m ) {
  18751. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18752. _vector$6.fromBufferAttribute( this, i );
  18753. _vector$6.transformDirection( m );
  18754. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18755. }
  18756. return this;
  18757. }
  18758. getComponent( index, component ) {
  18759. let value = this.array[ index * this.data.stride + this.offset + component ];
  18760. if ( this.normalized ) value = denormalize( value, this.array );
  18761. return value;
  18762. }
  18763. setComponent( index, component, value ) {
  18764. if ( this.normalized ) value = normalize( value, this.array );
  18765. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  18766. return this;
  18767. }
  18768. setX( index, x ) {
  18769. if ( this.normalized ) x = normalize( x, this.array );
  18770. this.data.array[ index * this.data.stride + this.offset ] = x;
  18771. return this;
  18772. }
  18773. setY( index, y ) {
  18774. if ( this.normalized ) y = normalize( y, this.array );
  18775. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18776. return this;
  18777. }
  18778. setZ( index, z ) {
  18779. if ( this.normalized ) z = normalize( z, this.array );
  18780. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18781. return this;
  18782. }
  18783. setW( index, w ) {
  18784. if ( this.normalized ) w = normalize( w, this.array );
  18785. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18786. return this;
  18787. }
  18788. getX( index ) {
  18789. let x = this.data.array[ index * this.data.stride + this.offset ];
  18790. if ( this.normalized ) x = denormalize( x, this.array );
  18791. return x;
  18792. }
  18793. getY( index ) {
  18794. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18795. if ( this.normalized ) y = denormalize( y, this.array );
  18796. return y;
  18797. }
  18798. getZ( index ) {
  18799. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18800. if ( this.normalized ) z = denormalize( z, this.array );
  18801. return z;
  18802. }
  18803. getW( index ) {
  18804. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18805. if ( this.normalized ) w = denormalize( w, this.array );
  18806. return w;
  18807. }
  18808. setXY( index, x, y ) {
  18809. index = index * this.data.stride + this.offset;
  18810. if ( this.normalized ) {
  18811. x = normalize( x, this.array );
  18812. y = normalize( y, this.array );
  18813. }
  18814. this.data.array[ index + 0 ] = x;
  18815. this.data.array[ index + 1 ] = y;
  18816. return this;
  18817. }
  18818. setXYZ( index, x, y, z ) {
  18819. index = index * this.data.stride + this.offset;
  18820. if ( this.normalized ) {
  18821. x = normalize( x, this.array );
  18822. y = normalize( y, this.array );
  18823. z = normalize( z, this.array );
  18824. }
  18825. this.data.array[ index + 0 ] = x;
  18826. this.data.array[ index + 1 ] = y;
  18827. this.data.array[ index + 2 ] = z;
  18828. return this;
  18829. }
  18830. setXYZW( index, x, y, z, w ) {
  18831. index = index * this.data.stride + this.offset;
  18832. if ( this.normalized ) {
  18833. x = normalize( x, this.array );
  18834. y = normalize( y, this.array );
  18835. z = normalize( z, this.array );
  18836. w = normalize( w, this.array );
  18837. }
  18838. this.data.array[ index + 0 ] = x;
  18839. this.data.array[ index + 1 ] = y;
  18840. this.data.array[ index + 2 ] = z;
  18841. this.data.array[ index + 3 ] = w;
  18842. return this;
  18843. }
  18844. clone( data ) {
  18845. if ( data === undefined ) {
  18846. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18847. const array = [];
  18848. for ( let i = 0; i < this.count; i ++ ) {
  18849. const index = i * this.data.stride + this.offset;
  18850. for ( let j = 0; j < this.itemSize; j ++ ) {
  18851. array.push( this.data.array[ index + j ] );
  18852. }
  18853. }
  18854. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18855. } else {
  18856. if ( data.interleavedBuffers === undefined ) {
  18857. data.interleavedBuffers = {};
  18858. }
  18859. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18860. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18861. }
  18862. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18863. }
  18864. }
  18865. toJSON( data ) {
  18866. if ( data === undefined ) {
  18867. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18868. const array = [];
  18869. for ( let i = 0; i < this.count; i ++ ) {
  18870. const index = i * this.data.stride + this.offset;
  18871. for ( let j = 0; j < this.itemSize; j ++ ) {
  18872. array.push( this.data.array[ index + j ] );
  18873. }
  18874. }
  18875. // de-interleave data and save it as an ordinary buffer attribute for now
  18876. return {
  18877. itemSize: this.itemSize,
  18878. type: this.array.constructor.name,
  18879. array: array,
  18880. normalized: this.normalized
  18881. };
  18882. } else {
  18883. // save as true interleaved attribute
  18884. if ( data.interleavedBuffers === undefined ) {
  18885. data.interleavedBuffers = {};
  18886. }
  18887. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18888. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18889. }
  18890. return {
  18891. isInterleavedBufferAttribute: true,
  18892. itemSize: this.itemSize,
  18893. data: this.data.uuid,
  18894. offset: this.offset,
  18895. normalized: this.normalized
  18896. };
  18897. }
  18898. }
  18899. }
  18900. class SpriteMaterial extends Material {
  18901. constructor( parameters ) {
  18902. super();
  18903. this.isSpriteMaterial = true;
  18904. this.type = 'SpriteMaterial';
  18905. this.color = new Color( 0xffffff );
  18906. this.map = null;
  18907. this.alphaMap = null;
  18908. this.rotation = 0;
  18909. this.sizeAttenuation = true;
  18910. this.transparent = true;
  18911. this.fog = true;
  18912. this.setValues( parameters );
  18913. }
  18914. copy( source ) {
  18915. super.copy( source );
  18916. this.color.copy( source.color );
  18917. this.map = source.map;
  18918. this.alphaMap = source.alphaMap;
  18919. this.rotation = source.rotation;
  18920. this.sizeAttenuation = source.sizeAttenuation;
  18921. this.fog = source.fog;
  18922. return this;
  18923. }
  18924. }
  18925. let _geometry;
  18926. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18927. const _worldScale = /*@__PURE__*/ new Vector3();
  18928. const _mvPosition = /*@__PURE__*/ new Vector3();
  18929. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18930. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18931. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18932. const _vA = /*@__PURE__*/ new Vector3();
  18933. const _vB = /*@__PURE__*/ new Vector3();
  18934. const _vC = /*@__PURE__*/ new Vector3();
  18935. const _uvA = /*@__PURE__*/ new Vector2();
  18936. const _uvB = /*@__PURE__*/ new Vector2();
  18937. const _uvC = /*@__PURE__*/ new Vector2();
  18938. class Sprite extends Object3D {
  18939. constructor( material = new SpriteMaterial() ) {
  18940. super();
  18941. this.isSprite = true;
  18942. this.type = 'Sprite';
  18943. if ( _geometry === undefined ) {
  18944. _geometry = new BufferGeometry();
  18945. const float32Array = new Float32Array( [
  18946. - 0.5, - 0.5, 0, 0, 0,
  18947. 0.5, - 0.5, 0, 1, 0,
  18948. 0.5, 0.5, 0, 1, 1,
  18949. - 0.5, 0.5, 0, 0, 1
  18950. ] );
  18951. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18952. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18953. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18954. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18955. }
  18956. this.geometry = _geometry;
  18957. this.material = material;
  18958. this.center = new Vector2( 0.5, 0.5 );
  18959. }
  18960. raycast( raycaster, intersects ) {
  18961. if ( raycaster.camera === null ) {
  18962. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18963. }
  18964. _worldScale.setFromMatrixScale( this.matrixWorld );
  18965. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18966. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18967. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18968. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18969. _worldScale.multiplyScalar( - _mvPosition.z );
  18970. }
  18971. const rotation = this.material.rotation;
  18972. let sin, cos;
  18973. if ( rotation !== 0 ) {
  18974. cos = Math.cos( rotation );
  18975. sin = Math.sin( rotation );
  18976. }
  18977. const center = this.center;
  18978. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18979. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18980. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18981. _uvA.set( 0, 0 );
  18982. _uvB.set( 1, 0 );
  18983. _uvC.set( 1, 1 );
  18984. // check first triangle
  18985. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18986. if ( intersect === null ) {
  18987. // check second triangle
  18988. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18989. _uvB.set( 0, 1 );
  18990. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18991. if ( intersect === null ) {
  18992. return;
  18993. }
  18994. }
  18995. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18996. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18997. intersects.push( {
  18998. distance: distance,
  18999. point: _intersectPoint.clone(),
  19000. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  19001. face: null,
  19002. object: this
  19003. } );
  19004. }
  19005. copy( source, recursive ) {
  19006. super.copy( source, recursive );
  19007. if ( source.center !== undefined ) this.center.copy( source.center );
  19008. this.material = source.material;
  19009. return this;
  19010. }
  19011. }
  19012. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  19013. // compute position in camera space
  19014. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  19015. // to check if rotation is not zero
  19016. if ( sin !== undefined ) {
  19017. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  19018. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  19019. } else {
  19020. _rotatedPosition.copy( _alignedPosition );
  19021. }
  19022. vertexPosition.copy( mvPosition );
  19023. vertexPosition.x += _rotatedPosition.x;
  19024. vertexPosition.y += _rotatedPosition.y;
  19025. // transform to world space
  19026. vertexPosition.applyMatrix4( _viewWorldMatrix );
  19027. }
  19028. const _v1$2 = /*@__PURE__*/ new Vector3();
  19029. const _v2$1 = /*@__PURE__*/ new Vector3();
  19030. class LOD extends Object3D {
  19031. constructor() {
  19032. super();
  19033. this._currentLevel = 0;
  19034. this.type = 'LOD';
  19035. Object.defineProperties( this, {
  19036. levels: {
  19037. enumerable: true,
  19038. value: []
  19039. },
  19040. isLOD: {
  19041. value: true,
  19042. }
  19043. } );
  19044. this.autoUpdate = true;
  19045. }
  19046. copy( source ) {
  19047. super.copy( source, false );
  19048. const levels = source.levels;
  19049. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19050. const level = levels[ i ];
  19051. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  19052. }
  19053. this.autoUpdate = source.autoUpdate;
  19054. return this;
  19055. }
  19056. addLevel( object, distance = 0, hysteresis = 0 ) {
  19057. distance = Math.abs( distance );
  19058. const levels = this.levels;
  19059. let l;
  19060. for ( l = 0; l < levels.length; l ++ ) {
  19061. if ( distance < levels[ l ].distance ) {
  19062. break;
  19063. }
  19064. }
  19065. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  19066. this.add( object );
  19067. return this;
  19068. }
  19069. getCurrentLevel() {
  19070. return this._currentLevel;
  19071. }
  19072. getObjectForDistance( distance ) {
  19073. const levels = this.levels;
  19074. if ( levels.length > 0 ) {
  19075. let i, l;
  19076. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19077. let levelDistance = levels[ i ].distance;
  19078. if ( levels[ i ].object.visible ) {
  19079. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19080. }
  19081. if ( distance < levelDistance ) {
  19082. break;
  19083. }
  19084. }
  19085. return levels[ i - 1 ].object;
  19086. }
  19087. return null;
  19088. }
  19089. raycast( raycaster, intersects ) {
  19090. const levels = this.levels;
  19091. if ( levels.length > 0 ) {
  19092. _v1$2.setFromMatrixPosition( this.matrixWorld );
  19093. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  19094. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  19095. }
  19096. }
  19097. update( camera ) {
  19098. const levels = this.levels;
  19099. if ( levels.length > 1 ) {
  19100. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  19101. _v2$1.setFromMatrixPosition( this.matrixWorld );
  19102. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  19103. levels[ 0 ].object.visible = true;
  19104. let i, l;
  19105. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19106. let levelDistance = levels[ i ].distance;
  19107. if ( levels[ i ].object.visible ) {
  19108. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19109. }
  19110. if ( distance >= levelDistance ) {
  19111. levels[ i - 1 ].object.visible = false;
  19112. levels[ i ].object.visible = true;
  19113. } else {
  19114. break;
  19115. }
  19116. }
  19117. this._currentLevel = i - 1;
  19118. for ( ; i < l; i ++ ) {
  19119. levels[ i ].object.visible = false;
  19120. }
  19121. }
  19122. }
  19123. toJSON( meta ) {
  19124. const data = super.toJSON( meta );
  19125. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  19126. data.object.levels = [];
  19127. const levels = this.levels;
  19128. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19129. const level = levels[ i ];
  19130. data.object.levels.push( {
  19131. object: level.object.uuid,
  19132. distance: level.distance,
  19133. hysteresis: level.hysteresis
  19134. } );
  19135. }
  19136. return data;
  19137. }
  19138. }
  19139. const _basePosition = /*@__PURE__*/ new Vector3();
  19140. const _skinIndex = /*@__PURE__*/ new Vector4();
  19141. const _skinWeight = /*@__PURE__*/ new Vector4();
  19142. const _vector3 = /*@__PURE__*/ new Vector3();
  19143. const _matrix4 = /*@__PURE__*/ new Matrix4();
  19144. const _vertex = /*@__PURE__*/ new Vector3();
  19145. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19146. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  19147. const _ray$2 = /*@__PURE__*/ new Ray();
  19148. class SkinnedMesh extends Mesh {
  19149. constructor( geometry, material ) {
  19150. super( geometry, material );
  19151. this.isSkinnedMesh = true;
  19152. this.type = 'SkinnedMesh';
  19153. this.bindMode = AttachedBindMode;
  19154. this.bindMatrix = new Matrix4();
  19155. this.bindMatrixInverse = new Matrix4();
  19156. this.boundingBox = null;
  19157. this.boundingSphere = null;
  19158. }
  19159. computeBoundingBox() {
  19160. const geometry = this.geometry;
  19161. if ( this.boundingBox === null ) {
  19162. this.boundingBox = new Box3();
  19163. }
  19164. this.boundingBox.makeEmpty();
  19165. const positionAttribute = geometry.getAttribute( 'position' );
  19166. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19167. this.getVertexPosition( i, _vertex );
  19168. this.boundingBox.expandByPoint( _vertex );
  19169. }
  19170. }
  19171. computeBoundingSphere() {
  19172. const geometry = this.geometry;
  19173. if ( this.boundingSphere === null ) {
  19174. this.boundingSphere = new Sphere();
  19175. }
  19176. this.boundingSphere.makeEmpty();
  19177. const positionAttribute = geometry.getAttribute( 'position' );
  19178. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19179. this.getVertexPosition( i, _vertex );
  19180. this.boundingSphere.expandByPoint( _vertex );
  19181. }
  19182. }
  19183. copy( source, recursive ) {
  19184. super.copy( source, recursive );
  19185. this.bindMode = source.bindMode;
  19186. this.bindMatrix.copy( source.bindMatrix );
  19187. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  19188. this.skeleton = source.skeleton;
  19189. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19190. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19191. return this;
  19192. }
  19193. raycast( raycaster, intersects ) {
  19194. const material = this.material;
  19195. const matrixWorld = this.matrixWorld;
  19196. if ( material === undefined ) return;
  19197. // test with bounding sphere in world space
  19198. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19199. _sphere$4.copy( this.boundingSphere );
  19200. _sphere$4.applyMatrix4( matrixWorld );
  19201. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19202. // convert ray to local space of skinned mesh
  19203. _inverseMatrix$2.copy( matrixWorld ).invert();
  19204. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  19205. // test with bounding box in local space
  19206. if ( this.boundingBox !== null ) {
  19207. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  19208. }
  19209. // test for intersections with geometry
  19210. this._computeIntersections( raycaster, intersects, _ray$2 );
  19211. }
  19212. getVertexPosition( index, target ) {
  19213. super.getVertexPosition( index, target );
  19214. this.applyBoneTransform( index, target );
  19215. return target;
  19216. }
  19217. bind( skeleton, bindMatrix ) {
  19218. this.skeleton = skeleton;
  19219. if ( bindMatrix === undefined ) {
  19220. this.updateMatrixWorld( true );
  19221. this.skeleton.calculateInverses();
  19222. bindMatrix = this.matrixWorld;
  19223. }
  19224. this.bindMatrix.copy( bindMatrix );
  19225. this.bindMatrixInverse.copy( bindMatrix ).invert();
  19226. }
  19227. pose() {
  19228. this.skeleton.pose();
  19229. }
  19230. normalizeSkinWeights() {
  19231. const vector = new Vector4();
  19232. const skinWeight = this.geometry.attributes.skinWeight;
  19233. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  19234. vector.fromBufferAttribute( skinWeight, i );
  19235. const scale = 1.0 / vector.manhattanLength();
  19236. if ( scale !== Infinity ) {
  19237. vector.multiplyScalar( scale );
  19238. } else {
  19239. vector.set( 1, 0, 0, 0 ); // do something reasonable
  19240. }
  19241. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  19242. }
  19243. }
  19244. updateMatrixWorld( force ) {
  19245. super.updateMatrixWorld( force );
  19246. if ( this.bindMode === AttachedBindMode ) {
  19247. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  19248. } else if ( this.bindMode === DetachedBindMode ) {
  19249. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  19250. } else {
  19251. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  19252. }
  19253. }
  19254. applyBoneTransform( index, vector ) {
  19255. const skeleton = this.skeleton;
  19256. const geometry = this.geometry;
  19257. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  19258. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  19259. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  19260. vector.set( 0, 0, 0 );
  19261. for ( let i = 0; i < 4; i ++ ) {
  19262. const weight = _skinWeight.getComponent( i );
  19263. if ( weight !== 0 ) {
  19264. const boneIndex = _skinIndex.getComponent( i );
  19265. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  19266. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  19267. }
  19268. }
  19269. return vector.applyMatrix4( this.bindMatrixInverse );
  19270. }
  19271. }
  19272. class Bone extends Object3D {
  19273. constructor() {
  19274. super();
  19275. this.isBone = true;
  19276. this.type = 'Bone';
  19277. }
  19278. }
  19279. class DataTexture extends Texture {
  19280. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  19281. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19282. this.isDataTexture = true;
  19283. this.image = { data: data, width: width, height: height };
  19284. this.generateMipmaps = false;
  19285. this.flipY = false;
  19286. this.unpackAlignment = 1;
  19287. }
  19288. }
  19289. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  19290. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  19291. class Skeleton {
  19292. constructor( bones = [], boneInverses = [] ) {
  19293. this.uuid = generateUUID();
  19294. this.bones = bones.slice( 0 );
  19295. this.boneInverses = boneInverses;
  19296. this.boneMatrices = null;
  19297. this.boneTexture = null;
  19298. this.init();
  19299. }
  19300. init() {
  19301. const bones = this.bones;
  19302. const boneInverses = this.boneInverses;
  19303. this.boneMatrices = new Float32Array( bones.length * 16 );
  19304. // calculate inverse bone matrices if necessary
  19305. if ( boneInverses.length === 0 ) {
  19306. this.calculateInverses();
  19307. } else {
  19308. // handle special case
  19309. if ( bones.length !== boneInverses.length ) {
  19310. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19311. this.boneInverses = [];
  19312. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19313. this.boneInverses.push( new Matrix4() );
  19314. }
  19315. }
  19316. }
  19317. }
  19318. calculateInverses() {
  19319. this.boneInverses.length = 0;
  19320. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19321. const inverse = new Matrix4();
  19322. if ( this.bones[ i ] ) {
  19323. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19324. }
  19325. this.boneInverses.push( inverse );
  19326. }
  19327. }
  19328. pose() {
  19329. // recover the bind-time world matrices
  19330. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19331. const bone = this.bones[ i ];
  19332. if ( bone ) {
  19333. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19334. }
  19335. }
  19336. // compute the local matrices, positions, rotations and scales
  19337. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19338. const bone = this.bones[ i ];
  19339. if ( bone ) {
  19340. if ( bone.parent && bone.parent.isBone ) {
  19341. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19342. bone.matrix.multiply( bone.matrixWorld );
  19343. } else {
  19344. bone.matrix.copy( bone.matrixWorld );
  19345. }
  19346. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19347. }
  19348. }
  19349. }
  19350. update() {
  19351. const bones = this.bones;
  19352. const boneInverses = this.boneInverses;
  19353. const boneMatrices = this.boneMatrices;
  19354. const boneTexture = this.boneTexture;
  19355. // flatten bone matrices to array
  19356. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19357. // compute the offset between the current and the original transform
  19358. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  19359. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19360. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19361. }
  19362. if ( boneTexture !== null ) {
  19363. boneTexture.needsUpdate = true;
  19364. }
  19365. }
  19366. clone() {
  19367. return new Skeleton( this.bones, this.boneInverses );
  19368. }
  19369. computeBoneTexture() {
  19370. // layout (1 matrix = 4 pixels)
  19371. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19372. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19373. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19374. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19375. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19376. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19377. size = Math.ceil( size / 4 ) * 4;
  19378. size = Math.max( size, 4 );
  19379. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19380. boneMatrices.set( this.boneMatrices ); // copy current values
  19381. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19382. boneTexture.needsUpdate = true;
  19383. this.boneMatrices = boneMatrices;
  19384. this.boneTexture = boneTexture;
  19385. return this;
  19386. }
  19387. getBoneByName( name ) {
  19388. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19389. const bone = this.bones[ i ];
  19390. if ( bone.name === name ) {
  19391. return bone;
  19392. }
  19393. }
  19394. return undefined;
  19395. }
  19396. dispose( ) {
  19397. if ( this.boneTexture !== null ) {
  19398. this.boneTexture.dispose();
  19399. this.boneTexture = null;
  19400. }
  19401. }
  19402. fromJSON( json, bones ) {
  19403. this.uuid = json.uuid;
  19404. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19405. const uuid = json.bones[ i ];
  19406. let bone = bones[ uuid ];
  19407. if ( bone === undefined ) {
  19408. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  19409. bone = new Bone();
  19410. }
  19411. this.bones.push( bone );
  19412. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19413. }
  19414. this.init();
  19415. return this;
  19416. }
  19417. toJSON() {
  19418. const data = {
  19419. metadata: {
  19420. version: 4.6,
  19421. type: 'Skeleton',
  19422. generator: 'Skeleton.toJSON'
  19423. },
  19424. bones: [],
  19425. boneInverses: []
  19426. };
  19427. data.uuid = this.uuid;
  19428. const bones = this.bones;
  19429. const boneInverses = this.boneInverses;
  19430. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19431. const bone = bones[ i ];
  19432. data.bones.push( bone.uuid );
  19433. const boneInverse = boneInverses[ i ];
  19434. data.boneInverses.push( boneInverse.toArray() );
  19435. }
  19436. return data;
  19437. }
  19438. }
  19439. class InstancedBufferAttribute extends BufferAttribute {
  19440. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19441. super( array, itemSize, normalized );
  19442. this.isInstancedBufferAttribute = true;
  19443. this.meshPerAttribute = meshPerAttribute;
  19444. }
  19445. copy( source ) {
  19446. super.copy( source );
  19447. this.meshPerAttribute = source.meshPerAttribute;
  19448. return this;
  19449. }
  19450. toJSON() {
  19451. const data = super.toJSON();
  19452. data.meshPerAttribute = this.meshPerAttribute;
  19453. data.isInstancedBufferAttribute = true;
  19454. return data;
  19455. }
  19456. }
  19457. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19458. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19459. const _instanceIntersects = [];
  19460. const _box3 = /*@__PURE__*/ new Box3();
  19461. const _identity = /*@__PURE__*/ new Matrix4();
  19462. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19463. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19464. class InstancedMesh extends Mesh {
  19465. constructor( geometry, material, count ) {
  19466. super( geometry, material );
  19467. this.isInstancedMesh = true;
  19468. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19469. this.instanceColor = null;
  19470. this.morphTexture = null;
  19471. this.count = count;
  19472. this.boundingBox = null;
  19473. this.boundingSphere = null;
  19474. for ( let i = 0; i < count; i ++ ) {
  19475. this.setMatrixAt( i, _identity );
  19476. }
  19477. }
  19478. computeBoundingBox() {
  19479. const geometry = this.geometry;
  19480. const count = this.count;
  19481. if ( this.boundingBox === null ) {
  19482. this.boundingBox = new Box3();
  19483. }
  19484. if ( geometry.boundingBox === null ) {
  19485. geometry.computeBoundingBox();
  19486. }
  19487. this.boundingBox.makeEmpty();
  19488. for ( let i = 0; i < count; i ++ ) {
  19489. this.getMatrixAt( i, _instanceLocalMatrix );
  19490. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19491. this.boundingBox.union( _box3 );
  19492. }
  19493. }
  19494. computeBoundingSphere() {
  19495. const geometry = this.geometry;
  19496. const count = this.count;
  19497. if ( this.boundingSphere === null ) {
  19498. this.boundingSphere = new Sphere();
  19499. }
  19500. if ( geometry.boundingSphere === null ) {
  19501. geometry.computeBoundingSphere();
  19502. }
  19503. this.boundingSphere.makeEmpty();
  19504. for ( let i = 0; i < count; i ++ ) {
  19505. this.getMatrixAt( i, _instanceLocalMatrix );
  19506. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19507. this.boundingSphere.union( _sphere$3 );
  19508. }
  19509. }
  19510. copy( source, recursive ) {
  19511. super.copy( source, recursive );
  19512. this.instanceMatrix.copy( source.instanceMatrix );
  19513. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19514. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19515. this.count = source.count;
  19516. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19517. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19518. return this;
  19519. }
  19520. getColorAt( index, color ) {
  19521. color.fromArray( this.instanceColor.array, index * 3 );
  19522. }
  19523. getMatrixAt( index, matrix ) {
  19524. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19525. }
  19526. getMorphAt( index, object ) {
  19527. const objectInfluences = object.morphTargetInfluences;
  19528. const array = this.morphTexture.source.data.data;
  19529. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19530. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19531. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19532. objectInfluences[ i ] = array[ dataIndex + i ];
  19533. }
  19534. }
  19535. raycast( raycaster, intersects ) {
  19536. const matrixWorld = this.matrixWorld;
  19537. const raycastTimes = this.count;
  19538. _mesh$1.geometry = this.geometry;
  19539. _mesh$1.material = this.material;
  19540. if ( _mesh$1.material === undefined ) return;
  19541. // test with bounding sphere first
  19542. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19543. _sphere$3.copy( this.boundingSphere );
  19544. _sphere$3.applyMatrix4( matrixWorld );
  19545. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  19546. // now test each instance
  19547. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19548. // calculate the world matrix for each instance
  19549. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19550. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19551. // the mesh represents this single instance
  19552. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19553. _mesh$1.raycast( raycaster, _instanceIntersects );
  19554. // process the result of raycast
  19555. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19556. const intersect = _instanceIntersects[ i ];
  19557. intersect.instanceId = instanceId;
  19558. intersect.object = this;
  19559. intersects.push( intersect );
  19560. }
  19561. _instanceIntersects.length = 0;
  19562. }
  19563. }
  19564. setColorAt( index, color ) {
  19565. if ( this.instanceColor === null ) {
  19566. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19567. }
  19568. color.toArray( this.instanceColor.array, index * 3 );
  19569. }
  19570. setMatrixAt( index, matrix ) {
  19571. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19572. }
  19573. setMorphAt( index, object ) {
  19574. const objectInfluences = object.morphTargetInfluences;
  19575. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19576. if ( this.morphTexture === null ) {
  19577. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19578. }
  19579. const array = this.morphTexture.source.data.data;
  19580. let morphInfluencesSum = 0;
  19581. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19582. morphInfluencesSum += objectInfluences[ i ];
  19583. }
  19584. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19585. const dataIndex = len * index;
  19586. array[ dataIndex ] = morphBaseInfluence;
  19587. array.set( objectInfluences, dataIndex + 1 );
  19588. }
  19589. updateMorphTargets() {
  19590. }
  19591. dispose() {
  19592. this.dispatchEvent( { type: 'dispose' } );
  19593. if ( this.morphTexture !== null ) {
  19594. this.morphTexture.dispose();
  19595. this.morphTexture = null;
  19596. }
  19597. return this;
  19598. }
  19599. }
  19600. function sortOpaque( a, b ) {
  19601. return a.z - b.z;
  19602. }
  19603. function sortTransparent( a, b ) {
  19604. return b.z - a.z;
  19605. }
  19606. class MultiDrawRenderList {
  19607. constructor() {
  19608. this.index = 0;
  19609. this.pool = [];
  19610. this.list = [];
  19611. }
  19612. push( drawRange, z ) {
  19613. const pool = this.pool;
  19614. const list = this.list;
  19615. if ( this.index >= pool.length ) {
  19616. pool.push( {
  19617. start: - 1,
  19618. count: - 1,
  19619. z: - 1,
  19620. } );
  19621. }
  19622. const item = pool[ this.index ];
  19623. list.push( item );
  19624. this.index ++;
  19625. item.start = drawRange.start;
  19626. item.count = drawRange.count;
  19627. item.z = z;
  19628. }
  19629. reset() {
  19630. this.list.length = 0;
  19631. this.index = 0;
  19632. }
  19633. }
  19634. const ID_ATTR_NAME = 'batchId';
  19635. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19636. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  19637. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  19638. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19639. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19640. const _frustum = /*@__PURE__*/ new Frustum();
  19641. const _box$1 = /*@__PURE__*/ new Box3();
  19642. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19643. const _vector$5 = /*@__PURE__*/ new Vector3();
  19644. const _forward = /*@__PURE__*/ new Vector3();
  19645. const _temp = /*@__PURE__*/ new Vector3();
  19646. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19647. const _mesh = /*@__PURE__*/ new Mesh();
  19648. const _batchIntersects = [];
  19649. // @TODO: SkinnedMesh support?
  19650. // @TODO: geometry.groups support?
  19651. // @TODO: geometry.drawRange support?
  19652. // @TODO: geometry.morphAttributes support?
  19653. // @TODO: Support uniform parameter per geometry
  19654. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  19655. // copies data from attribute "src" into "target" starting at "targetOffset"
  19656. function copyAttributeData( src, target, targetOffset = 0 ) {
  19657. const itemSize = target.itemSize;
  19658. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19659. // use the component getters and setters if the array data cannot
  19660. // be copied directly
  19661. const vertexCount = src.count;
  19662. for ( let i = 0; i < vertexCount; i ++ ) {
  19663. for ( let c = 0; c < itemSize; c ++ ) {
  19664. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19665. }
  19666. }
  19667. } else {
  19668. // faster copy approach using typed array set function
  19669. target.array.set( src.array, targetOffset * itemSize );
  19670. }
  19671. target.needsUpdate = true;
  19672. }
  19673. class BatchedMesh extends Mesh {
  19674. get maxGeometryCount() {
  19675. return this._maxGeometryCount;
  19676. }
  19677. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19678. super( new BufferGeometry(), material );
  19679. this.isBatchedMesh = true;
  19680. this.perObjectFrustumCulled = true;
  19681. this.sortObjects = true;
  19682. this.boundingBox = null;
  19683. this.boundingSphere = null;
  19684. this.customSort = null;
  19685. this._drawRanges = [];
  19686. this._reservedRanges = [];
  19687. this._visibility = [];
  19688. this._active = [];
  19689. this._bounds = [];
  19690. this._maxGeometryCount = maxGeometryCount;
  19691. this._maxVertexCount = maxVertexCount;
  19692. this._maxIndexCount = maxIndexCount;
  19693. this._geometryInitialized = false;
  19694. this._geometryCount = 0;
  19695. this._multiDrawCounts = new Int32Array( maxGeometryCount );
  19696. this._multiDrawStarts = new Int32Array( maxGeometryCount );
  19697. this._multiDrawCount = 0;
  19698. this._multiDrawInstances = null;
  19699. this._visibilityChanged = true;
  19700. // Local matrix per geometry by using data texture
  19701. this._matricesTexture = null;
  19702. this._initMatricesTexture();
  19703. // Local color per geometry by using data texture
  19704. this._colorsTexture = null;
  19705. }
  19706. _initMatricesTexture() {
  19707. // layout (1 matrix = 4 pixels)
  19708. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19709. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19710. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19711. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19712. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19713. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  19714. size = Math.ceil( size / 4 ) * 4;
  19715. size = Math.max( size, 4 );
  19716. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19717. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19718. this._matricesTexture = matricesTexture;
  19719. }
  19720. _initColorsTexture() {
  19721. let size = Math.sqrt( this._maxGeometryCount );
  19722. size = Math.ceil( size );
  19723. // 4 floats per RGBA pixel initialized to white
  19724. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  19725. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  19726. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  19727. this._colorsTexture = colorsTexture;
  19728. }
  19729. _initializeGeometry( reference ) {
  19730. const geometry = this.geometry;
  19731. const maxVertexCount = this._maxVertexCount;
  19732. const maxGeometryCount = this._maxGeometryCount;
  19733. const maxIndexCount = this._maxIndexCount;
  19734. if ( this._geometryInitialized === false ) {
  19735. for ( const attributeName in reference.attributes ) {
  19736. const srcAttribute = reference.getAttribute( attributeName );
  19737. const { array, itemSize, normalized } = srcAttribute;
  19738. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19739. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19740. geometry.setAttribute( attributeName, dstAttribute );
  19741. }
  19742. if ( reference.getIndex() !== null ) {
  19743. const indexArray = maxVertexCount > 65536
  19744. ? new Uint32Array( maxIndexCount )
  19745. : new Uint16Array( maxIndexCount );
  19746. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19747. }
  19748. const idArray = maxGeometryCount > 65536
  19749. ? new Uint32Array( maxVertexCount )
  19750. : new Uint16Array( maxVertexCount );
  19751. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  19752. this._geometryInitialized = true;
  19753. }
  19754. }
  19755. // Make sure the geometry is compatible with the existing combined geometry attributes
  19756. _validateGeometry( geometry ) {
  19757. // check that the geometry doesn't have a version of our reserved id attribute
  19758. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  19759. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  19760. }
  19761. // check to ensure the geometries are using consistent attributes and indices
  19762. const batchGeometry = this.geometry;
  19763. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19764. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  19765. }
  19766. for ( const attributeName in batchGeometry.attributes ) {
  19767. if ( attributeName === ID_ATTR_NAME ) {
  19768. continue;
  19769. }
  19770. if ( ! geometry.hasAttribute( attributeName ) ) {
  19771. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19772. }
  19773. const srcAttribute = geometry.getAttribute( attributeName );
  19774. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19775. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19776. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19777. }
  19778. }
  19779. }
  19780. setCustomSort( func ) {
  19781. this.customSort = func;
  19782. return this;
  19783. }
  19784. computeBoundingBox() {
  19785. if ( this.boundingBox === null ) {
  19786. this.boundingBox = new Box3();
  19787. }
  19788. const geometryCount = this._geometryCount;
  19789. const boundingBox = this.boundingBox;
  19790. const active = this._active;
  19791. boundingBox.makeEmpty();
  19792. for ( let i = 0; i < geometryCount; i ++ ) {
  19793. if ( active[ i ] === false ) continue;
  19794. this.getMatrixAt( i, _matrix$1 );
  19795. this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix$1 );
  19796. boundingBox.union( _box$1 );
  19797. }
  19798. }
  19799. computeBoundingSphere() {
  19800. if ( this.boundingSphere === null ) {
  19801. this.boundingSphere = new Sphere();
  19802. }
  19803. const geometryCount = this._geometryCount;
  19804. const boundingSphere = this.boundingSphere;
  19805. const active = this._active;
  19806. boundingSphere.makeEmpty();
  19807. for ( let i = 0; i < geometryCount; i ++ ) {
  19808. if ( active[ i ] === false ) continue;
  19809. this.getMatrixAt( i, _matrix$1 );
  19810. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  19811. boundingSphere.union( _sphere$2 );
  19812. }
  19813. }
  19814. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  19815. this._initializeGeometry( geometry );
  19816. this._validateGeometry( geometry );
  19817. // ensure we're not over geometry
  19818. if ( this._geometryCount >= this._maxGeometryCount ) {
  19819. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19820. }
  19821. // get the necessary range fo the geometry
  19822. const reservedRange = {
  19823. vertexStart: - 1,
  19824. vertexCount: - 1,
  19825. indexStart: - 1,
  19826. indexCount: - 1,
  19827. };
  19828. let lastRange = null;
  19829. const reservedRanges = this._reservedRanges;
  19830. const drawRanges = this._drawRanges;
  19831. const bounds = this._bounds;
  19832. if ( this._geometryCount !== 0 ) {
  19833. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  19834. }
  19835. if ( vertexCount === - 1 ) {
  19836. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  19837. } else {
  19838. reservedRange.vertexCount = vertexCount;
  19839. }
  19840. if ( lastRange === null ) {
  19841. reservedRange.vertexStart = 0;
  19842. } else {
  19843. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  19844. }
  19845. const index = geometry.getIndex();
  19846. const hasIndex = index !== null;
  19847. if ( hasIndex ) {
  19848. if ( indexCount === - 1 ) {
  19849. reservedRange.indexCount = index.count;
  19850. } else {
  19851. reservedRange.indexCount = indexCount;
  19852. }
  19853. if ( lastRange === null ) {
  19854. reservedRange.indexStart = 0;
  19855. } else {
  19856. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  19857. }
  19858. }
  19859. if (
  19860. reservedRange.indexStart !== - 1 &&
  19861. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  19862. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  19863. ) {
  19864. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19865. }
  19866. const visibility = this._visibility;
  19867. const active = this._active;
  19868. const matricesTexture = this._matricesTexture;
  19869. const matricesArray = this._matricesTexture.image.data;
  19870. const colorsTexture = this._colorsTexture;
  19871. // push new visibility states
  19872. visibility.push( true );
  19873. active.push( true );
  19874. // update id
  19875. const geometryId = this._geometryCount;
  19876. this._geometryCount ++;
  19877. // initialize matrix information
  19878. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  19879. matricesTexture.needsUpdate = true;
  19880. // initialize the color to white
  19881. if ( colorsTexture !== null ) {
  19882. _whiteColor.toArray( colorsTexture.image.data, geometryId * 4 );
  19883. colorsTexture.needsUpdate = true;
  19884. }
  19885. // add the reserved range and draw range objects
  19886. reservedRanges.push( reservedRange );
  19887. drawRanges.push( {
  19888. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  19889. count: - 1
  19890. } );
  19891. bounds.push( {
  19892. boxInitialized: false,
  19893. box: new Box3(),
  19894. sphereInitialized: false,
  19895. sphere: new Sphere()
  19896. } );
  19897. // set the id for the geometry
  19898. const idAttribute = this.geometry.getAttribute( ID_ATTR_NAME );
  19899. for ( let i = 0; i < reservedRange.vertexCount; i ++ ) {
  19900. idAttribute.setX( reservedRange.vertexStart + i, geometryId );
  19901. }
  19902. idAttribute.needsUpdate = true;
  19903. // update the geometry
  19904. this.setGeometryAt( geometryId, geometry );
  19905. return geometryId;
  19906. }
  19907. setGeometryAt( id, geometry ) {
  19908. if ( id >= this._geometryCount ) {
  19909. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19910. }
  19911. this._validateGeometry( geometry );
  19912. const batchGeometry = this.geometry;
  19913. const hasIndex = batchGeometry.getIndex() !== null;
  19914. const dstIndex = batchGeometry.getIndex();
  19915. const srcIndex = geometry.getIndex();
  19916. const reservedRange = this._reservedRanges[ id ];
  19917. if (
  19918. hasIndex &&
  19919. srcIndex.count > reservedRange.indexCount ||
  19920. geometry.attributes.position.count > reservedRange.vertexCount
  19921. ) {
  19922. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  19923. }
  19924. // copy geometry over
  19925. const vertexStart = reservedRange.vertexStart;
  19926. const vertexCount = reservedRange.vertexCount;
  19927. for ( const attributeName in batchGeometry.attributes ) {
  19928. if ( attributeName === ID_ATTR_NAME ) {
  19929. continue;
  19930. }
  19931. // copy attribute data
  19932. const srcAttribute = geometry.getAttribute( attributeName );
  19933. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19934. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19935. // fill the rest in with zeroes
  19936. const itemSize = srcAttribute.itemSize;
  19937. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  19938. const index = vertexStart + i;
  19939. for ( let c = 0; c < itemSize; c ++ ) {
  19940. dstAttribute.setComponent( index, c, 0 );
  19941. }
  19942. }
  19943. dstAttribute.needsUpdate = true;
  19944. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  19945. }
  19946. // copy index
  19947. if ( hasIndex ) {
  19948. const indexStart = reservedRange.indexStart;
  19949. // copy index data over
  19950. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19951. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19952. }
  19953. // fill the rest in with zeroes
  19954. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  19955. dstIndex.setX( indexStart + i, vertexStart );
  19956. }
  19957. dstIndex.needsUpdate = true;
  19958. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  19959. }
  19960. // store the bounding boxes
  19961. const bound = this._bounds[ id ];
  19962. if ( geometry.boundingBox !== null ) {
  19963. bound.box.copy( geometry.boundingBox );
  19964. bound.boxInitialized = true;
  19965. } else {
  19966. bound.boxInitialized = false;
  19967. }
  19968. if ( geometry.boundingSphere !== null ) {
  19969. bound.sphere.copy( geometry.boundingSphere );
  19970. bound.sphereInitialized = true;
  19971. } else {
  19972. bound.sphereInitialized = false;
  19973. }
  19974. // set drawRange count
  19975. const drawRange = this._drawRanges[ id ];
  19976. const posAttr = geometry.getAttribute( 'position' );
  19977. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  19978. this._visibilityChanged = true;
  19979. return id;
  19980. }
  19981. deleteGeometry( geometryId ) {
  19982. // Note: User needs to call optimize() afterward to pack the data.
  19983. const active = this._active;
  19984. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  19985. return this;
  19986. }
  19987. active[ geometryId ] = false;
  19988. this._visibilityChanged = true;
  19989. return this;
  19990. }
  19991. getInstanceCountAt( id ) {
  19992. if ( this._multiDrawInstances === null ) return null;
  19993. return this._multiDrawInstances[ id ];
  19994. }
  19995. setInstanceCountAt( id, instanceCount ) {
  19996. if ( this._multiDrawInstances === null ) {
  19997. this._multiDrawInstances = new Int32Array( this._maxGeometryCount ).fill( 1 );
  19998. }
  19999. this._multiDrawInstances[ id ] = instanceCount;
  20000. return id;
  20001. }
  20002. // get bounding box and compute it if it doesn't exist
  20003. getBoundingBoxAt( id, target ) {
  20004. const active = this._active;
  20005. if ( active[ id ] === false ) {
  20006. return null;
  20007. }
  20008. // compute bounding box
  20009. const bound = this._bounds[ id ];
  20010. const box = bound.box;
  20011. const geometry = this.geometry;
  20012. if ( bound.boxInitialized === false ) {
  20013. box.makeEmpty();
  20014. const index = geometry.index;
  20015. const position = geometry.attributes.position;
  20016. const drawRange = this._drawRanges[ id ];
  20017. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  20018. let iv = i;
  20019. if ( index ) {
  20020. iv = index.getX( iv );
  20021. }
  20022. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20023. }
  20024. bound.boxInitialized = true;
  20025. }
  20026. target.copy( box );
  20027. return target;
  20028. }
  20029. // get bounding sphere and compute it if it doesn't exist
  20030. getBoundingSphereAt( id, target ) {
  20031. const active = this._active;
  20032. if ( active[ id ] === false ) {
  20033. return null;
  20034. }
  20035. // compute bounding sphere
  20036. const bound = this._bounds[ id ];
  20037. const sphere = bound.sphere;
  20038. const geometry = this.geometry;
  20039. if ( bound.sphereInitialized === false ) {
  20040. sphere.makeEmpty();
  20041. this.getBoundingBoxAt( id, _box$1 );
  20042. _box$1.getCenter( sphere.center );
  20043. const index = geometry.index;
  20044. const position = geometry.attributes.position;
  20045. const drawRange = this._drawRanges[ id ];
  20046. let maxRadiusSq = 0;
  20047. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  20048. let iv = i;
  20049. if ( index ) {
  20050. iv = index.getX( iv );
  20051. }
  20052. _vector$5.fromBufferAttribute( position, iv );
  20053. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20054. }
  20055. sphere.radius = Math.sqrt( maxRadiusSq );
  20056. bound.sphereInitialized = true;
  20057. }
  20058. target.copy( sphere );
  20059. return target;
  20060. }
  20061. setMatrixAt( geometryId, matrix ) {
  20062. // @TODO: Map geometryId to index of the arrays because
  20063. // optimize() can make geometryId mismatch the index
  20064. const active = this._active;
  20065. const matricesTexture = this._matricesTexture;
  20066. const matricesArray = this._matricesTexture.image.data;
  20067. const geometryCount = this._geometryCount;
  20068. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20069. return this;
  20070. }
  20071. matrix.toArray( matricesArray, geometryId * 16 );
  20072. matricesTexture.needsUpdate = true;
  20073. return this;
  20074. }
  20075. getMatrixAt( geometryId, matrix ) {
  20076. const active = this._active;
  20077. const matricesArray = this._matricesTexture.image.data;
  20078. const geometryCount = this._geometryCount;
  20079. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20080. return null;
  20081. }
  20082. return matrix.fromArray( matricesArray, geometryId * 16 );
  20083. }
  20084. setColorAt( geometryId, color ) {
  20085. if ( this._colorsTexture === null ) {
  20086. this._initColorsTexture();
  20087. }
  20088. // @TODO: Map geometryId to index of the arrays because
  20089. // optimize() can make geometryId mismatch the index
  20090. const active = this._active;
  20091. const colorsTexture = this._colorsTexture;
  20092. const colorsArray = this._colorsTexture.image.data;
  20093. const geometryCount = this._geometryCount;
  20094. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20095. return this;
  20096. }
  20097. color.toArray( colorsArray, geometryId * 4 );
  20098. colorsTexture.needsUpdate = true;
  20099. return this;
  20100. }
  20101. getColorAt( geometryId, color ) {
  20102. const active = this._active;
  20103. const colorsArray = this._colorsTexture.image.data;
  20104. const geometryCount = this._geometryCount;
  20105. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20106. return null;
  20107. }
  20108. return color.fromArray( colorsArray, geometryId * 4 );
  20109. }
  20110. setVisibleAt( geometryId, value ) {
  20111. const visibility = this._visibility;
  20112. const active = this._active;
  20113. const geometryCount = this._geometryCount;
  20114. // if the geometry is out of range, not active, or visibility state
  20115. // does not change then return early
  20116. if (
  20117. geometryId >= geometryCount ||
  20118. active[ geometryId ] === false ||
  20119. visibility[ geometryId ] === value
  20120. ) {
  20121. return this;
  20122. }
  20123. visibility[ geometryId ] = value;
  20124. this._visibilityChanged = true;
  20125. return this;
  20126. }
  20127. getVisibleAt( geometryId ) {
  20128. const visibility = this._visibility;
  20129. const active = this._active;
  20130. const geometryCount = this._geometryCount;
  20131. // return early if the geometry is out of range or not active
  20132. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20133. return false;
  20134. }
  20135. return visibility[ geometryId ];
  20136. }
  20137. raycast( raycaster, intersects ) {
  20138. const visibility = this._visibility;
  20139. const active = this._active;
  20140. const drawRanges = this._drawRanges;
  20141. const geometryCount = this._geometryCount;
  20142. const matrixWorld = this.matrixWorld;
  20143. const batchGeometry = this.geometry;
  20144. // iterate over each geometry
  20145. _mesh.material = this.material;
  20146. _mesh.geometry.index = batchGeometry.index;
  20147. _mesh.geometry.attributes = batchGeometry.attributes;
  20148. if ( _mesh.geometry.boundingBox === null ) {
  20149. _mesh.geometry.boundingBox = new Box3();
  20150. }
  20151. if ( _mesh.geometry.boundingSphere === null ) {
  20152. _mesh.geometry.boundingSphere = new Sphere();
  20153. }
  20154. for ( let i = 0; i < geometryCount; i ++ ) {
  20155. if ( ! visibility[ i ] || ! active[ i ] ) {
  20156. continue;
  20157. }
  20158. const drawRange = drawRanges[ i ];
  20159. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  20160. // ge the intersects
  20161. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20162. this.getBoundingBoxAt( i, _mesh.geometry.boundingBox );
  20163. this.getBoundingSphereAt( i, _mesh.geometry.boundingSphere );
  20164. _mesh.raycast( raycaster, _batchIntersects );
  20165. // add batch id to the intersects
  20166. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20167. const intersect = _batchIntersects[ j ];
  20168. intersect.object = this;
  20169. intersect.batchId = i;
  20170. intersects.push( intersect );
  20171. }
  20172. _batchIntersects.length = 0;
  20173. }
  20174. _mesh.material = null;
  20175. _mesh.geometry.index = null;
  20176. _mesh.geometry.attributes = {};
  20177. _mesh.geometry.setDrawRange( 0, Infinity );
  20178. }
  20179. copy( source ) {
  20180. super.copy( source );
  20181. this.geometry = source.geometry.clone();
  20182. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20183. this.sortObjects = source.sortObjects;
  20184. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20185. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20186. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  20187. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  20188. this._visibility = source._visibility.slice();
  20189. this._active = source._active.slice();
  20190. this._bounds = source._bounds.map( bound => ( {
  20191. boxInitialized: bound.boxInitialized,
  20192. box: bound.box.clone(),
  20193. sphereInitialized: bound.sphereInitialized,
  20194. sphere: bound.sphere.clone()
  20195. } ) );
  20196. this._maxGeometryCount = source._maxGeometryCount;
  20197. this._maxVertexCount = source._maxVertexCount;
  20198. this._maxIndexCount = source._maxIndexCount;
  20199. this._geometryInitialized = source._geometryInitialized;
  20200. this._geometryCount = source._geometryCount;
  20201. this._multiDrawCounts = source._multiDrawCounts.slice();
  20202. this._multiDrawStarts = source._multiDrawStarts.slice();
  20203. this._matricesTexture = source._matricesTexture.clone();
  20204. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  20205. if ( this._colorsTexture !== null ) {
  20206. this._colorsTexture = source._colorsTexture.clone();
  20207. this._colorsTexture.image.data = this._colorsTexture.image.slice();
  20208. }
  20209. return this;
  20210. }
  20211. dispose() {
  20212. // Assuming the geometry is not shared with other meshes
  20213. this.geometry.dispose();
  20214. this._matricesTexture.dispose();
  20215. this._matricesTexture = null;
  20216. if ( this._colorsTexture !== null ) {
  20217. this._colorsTexture.dispose();
  20218. this._colorsTexture = null;
  20219. }
  20220. return this;
  20221. }
  20222. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20223. // if visibility has not changed and frustum culling and object sorting is not required
  20224. // then skip iterating over all items
  20225. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20226. return;
  20227. }
  20228. // the indexed version of the multi draw function requires specifying the start
  20229. // offset in bytes.
  20230. const index = geometry.getIndex();
  20231. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20232. const active = this._active;
  20233. const visibility = this._visibility;
  20234. const multiDrawStarts = this._multiDrawStarts;
  20235. const multiDrawCounts = this._multiDrawCounts;
  20236. const drawRanges = this._drawRanges;
  20237. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20238. // prepare the frustum in the local frame
  20239. if ( perObjectFrustumCulled ) {
  20240. _projScreenMatrix$2
  20241. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20242. .multiply( this.matrixWorld );
  20243. _frustum.setFromProjectionMatrix(
  20244. _projScreenMatrix$2,
  20245. renderer.coordinateSystem
  20246. );
  20247. }
  20248. let count = 0;
  20249. if ( this.sortObjects ) {
  20250. // get the camera position in the local frame
  20251. _invMatrixWorld.copy( this.matrixWorld ).invert();
  20252. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  20253. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  20254. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  20255. if ( visibility[ i ] && active[ i ] ) {
  20256. // get the bounds in world space
  20257. this.getMatrixAt( i, _matrix$1 );
  20258. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  20259. // determine whether the batched geometry is within the frustum
  20260. let culled = false;
  20261. if ( perObjectFrustumCulled ) {
  20262. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20263. }
  20264. if ( ! culled ) {
  20265. // get the distance from camera used for sorting
  20266. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  20267. _renderList.push( drawRanges[ i ], z );
  20268. }
  20269. }
  20270. }
  20271. // Sort the draw ranges and prep for rendering
  20272. const list = _renderList.list;
  20273. const customSort = this.customSort;
  20274. if ( customSort === null ) {
  20275. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20276. } else {
  20277. customSort.call( this, list, camera );
  20278. }
  20279. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20280. const item = list[ i ];
  20281. multiDrawStarts[ count ] = item.start * bytesPerElement;
  20282. multiDrawCounts[ count ] = item.count;
  20283. count ++;
  20284. }
  20285. _renderList.reset();
  20286. } else {
  20287. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  20288. if ( visibility[ i ] && active[ i ] ) {
  20289. // determine whether the batched geometry is within the frustum
  20290. let culled = false;
  20291. if ( perObjectFrustumCulled ) {
  20292. // get the bounds in world space
  20293. this.getMatrixAt( i, _matrix$1 );
  20294. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  20295. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20296. }
  20297. if ( ! culled ) {
  20298. const range = drawRanges[ i ];
  20299. multiDrawStarts[ count ] = range.start * bytesPerElement;
  20300. multiDrawCounts[ count ] = range.count;
  20301. count ++;
  20302. }
  20303. }
  20304. }
  20305. }
  20306. this._multiDrawCount = count;
  20307. this._visibilityChanged = false;
  20308. }
  20309. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20310. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20311. }
  20312. }
  20313. class LineBasicMaterial extends Material {
  20314. constructor( parameters ) {
  20315. super();
  20316. this.isLineBasicMaterial = true;
  20317. this.type = 'LineBasicMaterial';
  20318. this.color = new Color( 0xffffff );
  20319. this.map = null;
  20320. this.linewidth = 1;
  20321. this.linecap = 'round';
  20322. this.linejoin = 'round';
  20323. this.fog = true;
  20324. this.setValues( parameters );
  20325. }
  20326. copy( source ) {
  20327. super.copy( source );
  20328. this.color.copy( source.color );
  20329. this.map = source.map;
  20330. this.linewidth = source.linewidth;
  20331. this.linecap = source.linecap;
  20332. this.linejoin = source.linejoin;
  20333. this.fog = source.fog;
  20334. return this;
  20335. }
  20336. }
  20337. const _vStart = /*@__PURE__*/ new Vector3();
  20338. const _vEnd = /*@__PURE__*/ new Vector3();
  20339. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20340. const _ray$1 = /*@__PURE__*/ new Ray();
  20341. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20342. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  20343. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  20344. class Line extends Object3D {
  20345. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20346. super();
  20347. this.isLine = true;
  20348. this.type = 'Line';
  20349. this.geometry = geometry;
  20350. this.material = material;
  20351. this.updateMorphTargets();
  20352. }
  20353. copy( source, recursive ) {
  20354. super.copy( source, recursive );
  20355. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20356. this.geometry = source.geometry;
  20357. return this;
  20358. }
  20359. computeLineDistances() {
  20360. const geometry = this.geometry;
  20361. // we assume non-indexed geometry
  20362. if ( geometry.index === null ) {
  20363. const positionAttribute = geometry.attributes.position;
  20364. const lineDistances = [ 0 ];
  20365. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20366. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  20367. _vEnd.fromBufferAttribute( positionAttribute, i );
  20368. lineDistances[ i ] = lineDistances[ i - 1 ];
  20369. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  20370. }
  20371. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20372. } else {
  20373. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20374. }
  20375. return this;
  20376. }
  20377. raycast( raycaster, intersects ) {
  20378. const geometry = this.geometry;
  20379. const matrixWorld = this.matrixWorld;
  20380. const threshold = raycaster.params.Line.threshold;
  20381. const drawRange = geometry.drawRange;
  20382. // Checking boundingSphere distance to ray
  20383. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20384. _sphere$1.copy( geometry.boundingSphere );
  20385. _sphere$1.applyMatrix4( matrixWorld );
  20386. _sphere$1.radius += threshold;
  20387. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20388. //
  20389. _inverseMatrix$1.copy( matrixWorld ).invert();
  20390. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20391. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20392. const localThresholdSq = localThreshold * localThreshold;
  20393. const step = this.isLineSegments ? 2 : 1;
  20394. const index = geometry.index;
  20395. const attributes = geometry.attributes;
  20396. const positionAttribute = attributes.position;
  20397. if ( index !== null ) {
  20398. const start = Math.max( 0, drawRange.start );
  20399. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20400. for ( let i = start, l = end - 1; i < l; i += step ) {
  20401. const a = index.getX( i );
  20402. const b = index.getX( i + 1 );
  20403. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  20404. if ( intersect ) {
  20405. intersects.push( intersect );
  20406. }
  20407. }
  20408. if ( this.isLineLoop ) {
  20409. const a = index.getX( end - 1 );
  20410. const b = index.getX( start );
  20411. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  20412. if ( intersect ) {
  20413. intersects.push( intersect );
  20414. }
  20415. }
  20416. } else {
  20417. const start = Math.max( 0, drawRange.start );
  20418. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20419. for ( let i = start, l = end - 1; i < l; i += step ) {
  20420. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  20421. if ( intersect ) {
  20422. intersects.push( intersect );
  20423. }
  20424. }
  20425. if ( this.isLineLoop ) {
  20426. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  20427. if ( intersect ) {
  20428. intersects.push( intersect );
  20429. }
  20430. }
  20431. }
  20432. }
  20433. updateMorphTargets() {
  20434. const geometry = this.geometry;
  20435. const morphAttributes = geometry.morphAttributes;
  20436. const keys = Object.keys( morphAttributes );
  20437. if ( keys.length > 0 ) {
  20438. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20439. if ( morphAttribute !== undefined ) {
  20440. this.morphTargetInfluences = [];
  20441. this.morphTargetDictionary = {};
  20442. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20443. const name = morphAttribute[ m ].name || String( m );
  20444. this.morphTargetInfluences.push( 0 );
  20445. this.morphTargetDictionary[ name ] = m;
  20446. }
  20447. }
  20448. }
  20449. }
  20450. }
  20451. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  20452. const positionAttribute = object.geometry.attributes.position;
  20453. _vStart.fromBufferAttribute( positionAttribute, a );
  20454. _vEnd.fromBufferAttribute( positionAttribute, b );
  20455. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  20456. if ( distSq > thresholdSq ) return;
  20457. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  20458. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  20459. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20460. return {
  20461. distance: distance,
  20462. // What do we want? intersection point on the ray or on the segment??
  20463. // point: raycaster.ray.at( distance ),
  20464. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  20465. index: a,
  20466. face: null,
  20467. faceIndex: null,
  20468. object: object
  20469. };
  20470. }
  20471. const _start = /*@__PURE__*/ new Vector3();
  20472. const _end = /*@__PURE__*/ new Vector3();
  20473. class LineSegments extends Line {
  20474. constructor( geometry, material ) {
  20475. super( geometry, material );
  20476. this.isLineSegments = true;
  20477. this.type = 'LineSegments';
  20478. }
  20479. computeLineDistances() {
  20480. const geometry = this.geometry;
  20481. // we assume non-indexed geometry
  20482. if ( geometry.index === null ) {
  20483. const positionAttribute = geometry.attributes.position;
  20484. const lineDistances = [];
  20485. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20486. _start.fromBufferAttribute( positionAttribute, i );
  20487. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20488. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20489. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20490. }
  20491. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20492. } else {
  20493. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20494. }
  20495. return this;
  20496. }
  20497. }
  20498. class LineLoop extends Line {
  20499. constructor( geometry, material ) {
  20500. super( geometry, material );
  20501. this.isLineLoop = true;
  20502. this.type = 'LineLoop';
  20503. }
  20504. }
  20505. class PointsMaterial extends Material {
  20506. constructor( parameters ) {
  20507. super();
  20508. this.isPointsMaterial = true;
  20509. this.type = 'PointsMaterial';
  20510. this.color = new Color( 0xffffff );
  20511. this.map = null;
  20512. this.alphaMap = null;
  20513. this.size = 1;
  20514. this.sizeAttenuation = true;
  20515. this.fog = true;
  20516. this.setValues( parameters );
  20517. }
  20518. copy( source ) {
  20519. super.copy( source );
  20520. this.color.copy( source.color );
  20521. this.map = source.map;
  20522. this.alphaMap = source.alphaMap;
  20523. this.size = source.size;
  20524. this.sizeAttenuation = source.sizeAttenuation;
  20525. this.fog = source.fog;
  20526. return this;
  20527. }
  20528. }
  20529. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20530. const _ray = /*@__PURE__*/ new Ray();
  20531. const _sphere = /*@__PURE__*/ new Sphere();
  20532. const _position$2 = /*@__PURE__*/ new Vector3();
  20533. class Points extends Object3D {
  20534. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20535. super();
  20536. this.isPoints = true;
  20537. this.type = 'Points';
  20538. this.geometry = geometry;
  20539. this.material = material;
  20540. this.updateMorphTargets();
  20541. }
  20542. copy( source, recursive ) {
  20543. super.copy( source, recursive );
  20544. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20545. this.geometry = source.geometry;
  20546. return this;
  20547. }
  20548. raycast( raycaster, intersects ) {
  20549. const geometry = this.geometry;
  20550. const matrixWorld = this.matrixWorld;
  20551. const threshold = raycaster.params.Points.threshold;
  20552. const drawRange = geometry.drawRange;
  20553. // Checking boundingSphere distance to ray
  20554. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20555. _sphere.copy( geometry.boundingSphere );
  20556. _sphere.applyMatrix4( matrixWorld );
  20557. _sphere.radius += threshold;
  20558. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20559. //
  20560. _inverseMatrix.copy( matrixWorld ).invert();
  20561. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20562. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20563. const localThresholdSq = localThreshold * localThreshold;
  20564. const index = geometry.index;
  20565. const attributes = geometry.attributes;
  20566. const positionAttribute = attributes.position;
  20567. if ( index !== null ) {
  20568. const start = Math.max( 0, drawRange.start );
  20569. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20570. for ( let i = start, il = end; i < il; i ++ ) {
  20571. const a = index.getX( i );
  20572. _position$2.fromBufferAttribute( positionAttribute, a );
  20573. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20574. }
  20575. } else {
  20576. const start = Math.max( 0, drawRange.start );
  20577. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20578. for ( let i = start, l = end; i < l; i ++ ) {
  20579. _position$2.fromBufferAttribute( positionAttribute, i );
  20580. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20581. }
  20582. }
  20583. }
  20584. updateMorphTargets() {
  20585. const geometry = this.geometry;
  20586. const morphAttributes = geometry.morphAttributes;
  20587. const keys = Object.keys( morphAttributes );
  20588. if ( keys.length > 0 ) {
  20589. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20590. if ( morphAttribute !== undefined ) {
  20591. this.morphTargetInfluences = [];
  20592. this.morphTargetDictionary = {};
  20593. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20594. const name = morphAttribute[ m ].name || String( m );
  20595. this.morphTargetInfluences.push( 0 );
  20596. this.morphTargetDictionary[ name ] = m;
  20597. }
  20598. }
  20599. }
  20600. }
  20601. }
  20602. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20603. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20604. if ( rayPointDistanceSq < localThresholdSq ) {
  20605. const intersectPoint = new Vector3();
  20606. _ray.closestPointToPoint( point, intersectPoint );
  20607. intersectPoint.applyMatrix4( matrixWorld );
  20608. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20609. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20610. intersects.push( {
  20611. distance: distance,
  20612. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20613. point: intersectPoint,
  20614. index: index,
  20615. face: null,
  20616. object: object
  20617. } );
  20618. }
  20619. }
  20620. class VideoTexture extends Texture {
  20621. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20622. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20623. this.isVideoTexture = true;
  20624. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20625. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20626. this.generateMipmaps = false;
  20627. const scope = this;
  20628. function updateVideo() {
  20629. scope.needsUpdate = true;
  20630. video.requestVideoFrameCallback( updateVideo );
  20631. }
  20632. if ( 'requestVideoFrameCallback' in video ) {
  20633. video.requestVideoFrameCallback( updateVideo );
  20634. }
  20635. }
  20636. clone() {
  20637. return new this.constructor( this.image ).copy( this );
  20638. }
  20639. update() {
  20640. const video = this.image;
  20641. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20642. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20643. this.needsUpdate = true;
  20644. }
  20645. }
  20646. }
  20647. class FramebufferTexture extends Texture {
  20648. constructor( width, height ) {
  20649. super( { width, height } );
  20650. this.isFramebufferTexture = true;
  20651. this.magFilter = NearestFilter;
  20652. this.minFilter = NearestFilter;
  20653. this.generateMipmaps = false;
  20654. this.needsUpdate = true;
  20655. }
  20656. }
  20657. class CompressedTexture extends Texture {
  20658. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20659. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20660. this.isCompressedTexture = true;
  20661. this.image = { width: width, height: height };
  20662. this.mipmaps = mipmaps;
  20663. // no flipping for cube textures
  20664. // (also flipping doesn't work for compressed textures )
  20665. this.flipY = false;
  20666. // can't generate mipmaps for compressed textures
  20667. // mips must be embedded in DDS files
  20668. this.generateMipmaps = false;
  20669. }
  20670. }
  20671. class CompressedArrayTexture extends CompressedTexture {
  20672. constructor( mipmaps, width, height, depth, format, type ) {
  20673. super( mipmaps, width, height, format, type );
  20674. this.isCompressedArrayTexture = true;
  20675. this.image.depth = depth;
  20676. this.wrapR = ClampToEdgeWrapping;
  20677. this.layerUpdates = new Set();
  20678. }
  20679. addLayerUpdates( layerIndex ) {
  20680. this.layerUpdates.add( layerIndex );
  20681. }
  20682. clearLayerUpdates() {
  20683. this.layerUpdates.clear();
  20684. }
  20685. }
  20686. class CompressedCubeTexture extends CompressedTexture {
  20687. constructor( images, format, type ) {
  20688. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  20689. this.isCompressedCubeTexture = true;
  20690. this.isCubeTexture = true;
  20691. this.image = images;
  20692. }
  20693. }
  20694. class CanvasTexture extends Texture {
  20695. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20696. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20697. this.isCanvasTexture = true;
  20698. this.needsUpdate = true;
  20699. }
  20700. }
  20701. /**
  20702. * Extensible curve object.
  20703. *
  20704. * Some common of curve methods:
  20705. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20706. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20707. * .getPoints(), .getSpacedPoints()
  20708. * .getLength()
  20709. * .updateArcLengths()
  20710. *
  20711. * This following curves inherit from THREE.Curve:
  20712. *
  20713. * -- 2D curves --
  20714. * THREE.ArcCurve
  20715. * THREE.CubicBezierCurve
  20716. * THREE.EllipseCurve
  20717. * THREE.LineCurve
  20718. * THREE.QuadraticBezierCurve
  20719. * THREE.SplineCurve
  20720. *
  20721. * -- 3D curves --
  20722. * THREE.CatmullRomCurve3
  20723. * THREE.CubicBezierCurve3
  20724. * THREE.LineCurve3
  20725. * THREE.QuadraticBezierCurve3
  20726. *
  20727. * A series of curves can be represented as a THREE.CurvePath.
  20728. *
  20729. **/
  20730. class Curve {
  20731. constructor() {
  20732. this.type = 'Curve';
  20733. this.arcLengthDivisions = 200;
  20734. }
  20735. // Virtual base class method to overwrite and implement in subclasses
  20736. // - t [0 .. 1]
  20737. getPoint( /* t, optionalTarget */ ) {
  20738. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20739. return null;
  20740. }
  20741. // Get point at relative position in curve according to arc length
  20742. // - u [0 .. 1]
  20743. getPointAt( u, optionalTarget ) {
  20744. const t = this.getUtoTmapping( u );
  20745. return this.getPoint( t, optionalTarget );
  20746. }
  20747. // Get sequence of points using getPoint( t )
  20748. getPoints( divisions = 5 ) {
  20749. const points = [];
  20750. for ( let d = 0; d <= divisions; d ++ ) {
  20751. points.push( this.getPoint( d / divisions ) );
  20752. }
  20753. return points;
  20754. }
  20755. // Get sequence of points using getPointAt( u )
  20756. getSpacedPoints( divisions = 5 ) {
  20757. const points = [];
  20758. for ( let d = 0; d <= divisions; d ++ ) {
  20759. points.push( this.getPointAt( d / divisions ) );
  20760. }
  20761. return points;
  20762. }
  20763. // Get total curve arc length
  20764. getLength() {
  20765. const lengths = this.getLengths();
  20766. return lengths[ lengths.length - 1 ];
  20767. }
  20768. // Get list of cumulative segment lengths
  20769. getLengths( divisions = this.arcLengthDivisions ) {
  20770. if ( this.cacheArcLengths &&
  20771. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20772. ! this.needsUpdate ) {
  20773. return this.cacheArcLengths;
  20774. }
  20775. this.needsUpdate = false;
  20776. const cache = [];
  20777. let current, last = this.getPoint( 0 );
  20778. let sum = 0;
  20779. cache.push( 0 );
  20780. for ( let p = 1; p <= divisions; p ++ ) {
  20781. current = this.getPoint( p / divisions );
  20782. sum += current.distanceTo( last );
  20783. cache.push( sum );
  20784. last = current;
  20785. }
  20786. this.cacheArcLengths = cache;
  20787. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20788. }
  20789. updateArcLengths() {
  20790. this.needsUpdate = true;
  20791. this.getLengths();
  20792. }
  20793. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20794. getUtoTmapping( u, distance ) {
  20795. const arcLengths = this.getLengths();
  20796. let i = 0;
  20797. const il = arcLengths.length;
  20798. let targetArcLength; // The targeted u distance value to get
  20799. if ( distance ) {
  20800. targetArcLength = distance;
  20801. } else {
  20802. targetArcLength = u * arcLengths[ il - 1 ];
  20803. }
  20804. // binary search for the index with largest value smaller than target u distance
  20805. let low = 0, high = il - 1, comparison;
  20806. while ( low <= high ) {
  20807. 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
  20808. comparison = arcLengths[ i ] - targetArcLength;
  20809. if ( comparison < 0 ) {
  20810. low = i + 1;
  20811. } else if ( comparison > 0 ) {
  20812. high = i - 1;
  20813. } else {
  20814. high = i;
  20815. break;
  20816. // DONE
  20817. }
  20818. }
  20819. i = high;
  20820. if ( arcLengths[ i ] === targetArcLength ) {
  20821. return i / ( il - 1 );
  20822. }
  20823. // we could get finer grain at lengths, or use simple interpolation between two points
  20824. const lengthBefore = arcLengths[ i ];
  20825. const lengthAfter = arcLengths[ i + 1 ];
  20826. const segmentLength = lengthAfter - lengthBefore;
  20827. // determine where we are between the 'before' and 'after' points
  20828. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20829. // add that fractional amount to t
  20830. const t = ( i + segmentFraction ) / ( il - 1 );
  20831. return t;
  20832. }
  20833. // Returns a unit vector tangent at t
  20834. // In case any sub curve does not implement its tangent derivation,
  20835. // 2 points a small delta apart will be used to find its gradient
  20836. // which seems to give a reasonable approximation
  20837. getTangent( t, optionalTarget ) {
  20838. const delta = 0.0001;
  20839. let t1 = t - delta;
  20840. let t2 = t + delta;
  20841. // Capping in case of danger
  20842. if ( t1 < 0 ) t1 = 0;
  20843. if ( t2 > 1 ) t2 = 1;
  20844. const pt1 = this.getPoint( t1 );
  20845. const pt2 = this.getPoint( t2 );
  20846. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  20847. tangent.copy( pt2 ).sub( pt1 ).normalize();
  20848. return tangent;
  20849. }
  20850. getTangentAt( u, optionalTarget ) {
  20851. const t = this.getUtoTmapping( u );
  20852. return this.getTangent( t, optionalTarget );
  20853. }
  20854. computeFrenetFrames( segments, closed ) {
  20855. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20856. const normal = new Vector3();
  20857. const tangents = [];
  20858. const normals = [];
  20859. const binormals = [];
  20860. const vec = new Vector3();
  20861. const mat = new Matrix4();
  20862. // compute the tangent vectors for each segment on the curve
  20863. for ( let i = 0; i <= segments; i ++ ) {
  20864. const u = i / segments;
  20865. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  20866. }
  20867. // select an initial normal vector perpendicular to the first tangent vector,
  20868. // and in the direction of the minimum tangent xyz component
  20869. normals[ 0 ] = new Vector3();
  20870. binormals[ 0 ] = new Vector3();
  20871. let min = Number.MAX_VALUE;
  20872. const tx = Math.abs( tangents[ 0 ].x );
  20873. const ty = Math.abs( tangents[ 0 ].y );
  20874. const tz = Math.abs( tangents[ 0 ].z );
  20875. if ( tx <= min ) {
  20876. min = tx;
  20877. normal.set( 1, 0, 0 );
  20878. }
  20879. if ( ty <= min ) {
  20880. min = ty;
  20881. normal.set( 0, 1, 0 );
  20882. }
  20883. if ( tz <= min ) {
  20884. normal.set( 0, 0, 1 );
  20885. }
  20886. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20887. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20888. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20889. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20890. for ( let i = 1; i <= segments; i ++ ) {
  20891. normals[ i ] = normals[ i - 1 ].clone();
  20892. binormals[ i ] = binormals[ i - 1 ].clone();
  20893. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20894. if ( vec.length() > Number.EPSILON ) {
  20895. vec.normalize();
  20896. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20897. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20898. }
  20899. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20900. }
  20901. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20902. if ( closed === true ) {
  20903. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20904. theta /= segments;
  20905. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20906. theta = - theta;
  20907. }
  20908. for ( let i = 1; i <= segments; i ++ ) {
  20909. // twist a little...
  20910. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20911. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20912. }
  20913. }
  20914. return {
  20915. tangents: tangents,
  20916. normals: normals,
  20917. binormals: binormals
  20918. };
  20919. }
  20920. clone() {
  20921. return new this.constructor().copy( this );
  20922. }
  20923. copy( source ) {
  20924. this.arcLengthDivisions = source.arcLengthDivisions;
  20925. return this;
  20926. }
  20927. toJSON() {
  20928. const data = {
  20929. metadata: {
  20930. version: 4.6,
  20931. type: 'Curve',
  20932. generator: 'Curve.toJSON'
  20933. }
  20934. };
  20935. data.arcLengthDivisions = this.arcLengthDivisions;
  20936. data.type = this.type;
  20937. return data;
  20938. }
  20939. fromJSON( json ) {
  20940. this.arcLengthDivisions = json.arcLengthDivisions;
  20941. return this;
  20942. }
  20943. }
  20944. class EllipseCurve extends Curve {
  20945. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  20946. super();
  20947. this.isEllipseCurve = true;
  20948. this.type = 'EllipseCurve';
  20949. this.aX = aX;
  20950. this.aY = aY;
  20951. this.xRadius = xRadius;
  20952. this.yRadius = yRadius;
  20953. this.aStartAngle = aStartAngle;
  20954. this.aEndAngle = aEndAngle;
  20955. this.aClockwise = aClockwise;
  20956. this.aRotation = aRotation;
  20957. }
  20958. getPoint( t, optionalTarget = new Vector2() ) {
  20959. const point = optionalTarget;
  20960. const twoPi = Math.PI * 2;
  20961. let deltaAngle = this.aEndAngle - this.aStartAngle;
  20962. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20963. // ensures that deltaAngle is 0 .. 2 PI
  20964. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20965. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20966. if ( deltaAngle < Number.EPSILON ) {
  20967. if ( samePoints ) {
  20968. deltaAngle = 0;
  20969. } else {
  20970. deltaAngle = twoPi;
  20971. }
  20972. }
  20973. if ( this.aClockwise === true && ! samePoints ) {
  20974. if ( deltaAngle === twoPi ) {
  20975. deltaAngle = - twoPi;
  20976. } else {
  20977. deltaAngle = deltaAngle - twoPi;
  20978. }
  20979. }
  20980. const angle = this.aStartAngle + t * deltaAngle;
  20981. let x = this.aX + this.xRadius * Math.cos( angle );
  20982. let y = this.aY + this.yRadius * Math.sin( angle );
  20983. if ( this.aRotation !== 0 ) {
  20984. const cos = Math.cos( this.aRotation );
  20985. const sin = Math.sin( this.aRotation );
  20986. const tx = x - this.aX;
  20987. const ty = y - this.aY;
  20988. // Rotate the point about the center of the ellipse.
  20989. x = tx * cos - ty * sin + this.aX;
  20990. y = tx * sin + ty * cos + this.aY;
  20991. }
  20992. return point.set( x, y );
  20993. }
  20994. copy( source ) {
  20995. super.copy( source );
  20996. this.aX = source.aX;
  20997. this.aY = source.aY;
  20998. this.xRadius = source.xRadius;
  20999. this.yRadius = source.yRadius;
  21000. this.aStartAngle = source.aStartAngle;
  21001. this.aEndAngle = source.aEndAngle;
  21002. this.aClockwise = source.aClockwise;
  21003. this.aRotation = source.aRotation;
  21004. return this;
  21005. }
  21006. toJSON() {
  21007. const data = super.toJSON();
  21008. data.aX = this.aX;
  21009. data.aY = this.aY;
  21010. data.xRadius = this.xRadius;
  21011. data.yRadius = this.yRadius;
  21012. data.aStartAngle = this.aStartAngle;
  21013. data.aEndAngle = this.aEndAngle;
  21014. data.aClockwise = this.aClockwise;
  21015. data.aRotation = this.aRotation;
  21016. return data;
  21017. }
  21018. fromJSON( json ) {
  21019. super.fromJSON( json );
  21020. this.aX = json.aX;
  21021. this.aY = json.aY;
  21022. this.xRadius = json.xRadius;
  21023. this.yRadius = json.yRadius;
  21024. this.aStartAngle = json.aStartAngle;
  21025. this.aEndAngle = json.aEndAngle;
  21026. this.aClockwise = json.aClockwise;
  21027. this.aRotation = json.aRotation;
  21028. return this;
  21029. }
  21030. }
  21031. class ArcCurve extends EllipseCurve {
  21032. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21033. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21034. this.isArcCurve = true;
  21035. this.type = 'ArcCurve';
  21036. }
  21037. }
  21038. /**
  21039. * Centripetal CatmullRom Curve - which is useful for avoiding
  21040. * cusps and self-intersections in non-uniform catmull rom curves.
  21041. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21042. *
  21043. * curve.type accepts centripetal(default), chordal and catmullrom
  21044. * curve.tension is used for catmullrom which defaults to 0.5
  21045. */
  21046. /*
  21047. Based on an optimized c++ solution in
  21048. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21049. - http://ideone.com/NoEbVM
  21050. This CubicPoly class could be used for reusing some variables and calculations,
  21051. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21052. which can be placed in CurveUtils.
  21053. */
  21054. function CubicPoly() {
  21055. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  21056. /*
  21057. * Compute coefficients for a cubic polynomial
  21058. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21059. * such that
  21060. * p(0) = x0, p(1) = x1
  21061. * and
  21062. * p'(0) = t0, p'(1) = t1.
  21063. */
  21064. function init( x0, x1, t0, t1 ) {
  21065. c0 = x0;
  21066. c1 = t0;
  21067. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21068. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21069. }
  21070. return {
  21071. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  21072. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21073. },
  21074. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21075. // compute tangents when parameterized in [t1,t2]
  21076. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21077. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21078. // rescale tangents for parametrization in [0,1]
  21079. t1 *= dt1;
  21080. t2 *= dt1;
  21081. init( x1, x2, t1, t2 );
  21082. },
  21083. calc: function ( t ) {
  21084. const t2 = t * t;
  21085. const t3 = t2 * t;
  21086. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21087. }
  21088. };
  21089. }
  21090. //
  21091. const tmp = /*@__PURE__*/ new Vector3();
  21092. const px = /*@__PURE__*/ new CubicPoly();
  21093. const py = /*@__PURE__*/ new CubicPoly();
  21094. const pz = /*@__PURE__*/ new CubicPoly();
  21095. class CatmullRomCurve3 extends Curve {
  21096. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  21097. super();
  21098. this.isCatmullRomCurve3 = true;
  21099. this.type = 'CatmullRomCurve3';
  21100. this.points = points;
  21101. this.closed = closed;
  21102. this.curveType = curveType;
  21103. this.tension = tension;
  21104. }
  21105. getPoint( t, optionalTarget = new Vector3() ) {
  21106. const point = optionalTarget;
  21107. const points = this.points;
  21108. const l = points.length;
  21109. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21110. let intPoint = Math.floor( p );
  21111. let weight = p - intPoint;
  21112. if ( this.closed ) {
  21113. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  21114. } else if ( weight === 0 && intPoint === l - 1 ) {
  21115. intPoint = l - 2;
  21116. weight = 1;
  21117. }
  21118. let p0, p3; // 4 points (p1 & p2 defined below)
  21119. if ( this.closed || intPoint > 0 ) {
  21120. p0 = points[ ( intPoint - 1 ) % l ];
  21121. } else {
  21122. // extrapolate first point
  21123. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21124. p0 = tmp;
  21125. }
  21126. const p1 = points[ intPoint % l ];
  21127. const p2 = points[ ( intPoint + 1 ) % l ];
  21128. if ( this.closed || intPoint + 2 < l ) {
  21129. p3 = points[ ( intPoint + 2 ) % l ];
  21130. } else {
  21131. // extrapolate last point
  21132. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21133. p3 = tmp;
  21134. }
  21135. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  21136. // init Centripetal / Chordal Catmull-Rom
  21137. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21138. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21139. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21140. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21141. // safety check for repeated points
  21142. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21143. if ( dt0 < 1e-4 ) dt0 = dt1;
  21144. if ( dt2 < 1e-4 ) dt2 = dt1;
  21145. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21146. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21147. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21148. } else if ( this.curveType === 'catmullrom' ) {
  21149. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  21150. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  21151. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  21152. }
  21153. point.set(
  21154. px.calc( weight ),
  21155. py.calc( weight ),
  21156. pz.calc( weight )
  21157. );
  21158. return point;
  21159. }
  21160. copy( source ) {
  21161. super.copy( source );
  21162. this.points = [];
  21163. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21164. const point = source.points[ i ];
  21165. this.points.push( point.clone() );
  21166. }
  21167. this.closed = source.closed;
  21168. this.curveType = source.curveType;
  21169. this.tension = source.tension;
  21170. return this;
  21171. }
  21172. toJSON() {
  21173. const data = super.toJSON();
  21174. data.points = [];
  21175. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21176. const point = this.points[ i ];
  21177. data.points.push( point.toArray() );
  21178. }
  21179. data.closed = this.closed;
  21180. data.curveType = this.curveType;
  21181. data.tension = this.tension;
  21182. return data;
  21183. }
  21184. fromJSON( json ) {
  21185. super.fromJSON( json );
  21186. this.points = [];
  21187. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21188. const point = json.points[ i ];
  21189. this.points.push( new Vector3().fromArray( point ) );
  21190. }
  21191. this.closed = json.closed;
  21192. this.curveType = json.curveType;
  21193. this.tension = json.tension;
  21194. return this;
  21195. }
  21196. }
  21197. /**
  21198. * Bezier Curves formulas obtained from
  21199. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  21200. */
  21201. function CatmullRom( t, p0, p1, p2, p3 ) {
  21202. const v0 = ( p2 - p0 ) * 0.5;
  21203. const v1 = ( p3 - p1 ) * 0.5;
  21204. const t2 = t * t;
  21205. const t3 = t * t2;
  21206. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21207. }
  21208. //
  21209. function QuadraticBezierP0( t, p ) {
  21210. const k = 1 - t;
  21211. return k * k * p;
  21212. }
  21213. function QuadraticBezierP1( t, p ) {
  21214. return 2 * ( 1 - t ) * t * p;
  21215. }
  21216. function QuadraticBezierP2( t, p ) {
  21217. return t * t * p;
  21218. }
  21219. function QuadraticBezier( t, p0, p1, p2 ) {
  21220. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  21221. QuadraticBezierP2( t, p2 );
  21222. }
  21223. //
  21224. function CubicBezierP0( t, p ) {
  21225. const k = 1 - t;
  21226. return k * k * k * p;
  21227. }
  21228. function CubicBezierP1( t, p ) {
  21229. const k = 1 - t;
  21230. return 3 * k * k * t * p;
  21231. }
  21232. function CubicBezierP2( t, p ) {
  21233. return 3 * ( 1 - t ) * t * t * p;
  21234. }
  21235. function CubicBezierP3( t, p ) {
  21236. return t * t * t * p;
  21237. }
  21238. function CubicBezier( t, p0, p1, p2, p3 ) {
  21239. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  21240. CubicBezierP3( t, p3 );
  21241. }
  21242. class CubicBezierCurve extends Curve {
  21243. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  21244. super();
  21245. this.isCubicBezierCurve = true;
  21246. this.type = 'CubicBezierCurve';
  21247. this.v0 = v0;
  21248. this.v1 = v1;
  21249. this.v2 = v2;
  21250. this.v3 = v3;
  21251. }
  21252. getPoint( t, optionalTarget = new Vector2() ) {
  21253. const point = optionalTarget;
  21254. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21255. point.set(
  21256. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21257. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21258. );
  21259. return point;
  21260. }
  21261. copy( source ) {
  21262. super.copy( source );
  21263. this.v0.copy( source.v0 );
  21264. this.v1.copy( source.v1 );
  21265. this.v2.copy( source.v2 );
  21266. this.v3.copy( source.v3 );
  21267. return this;
  21268. }
  21269. toJSON() {
  21270. const data = super.toJSON();
  21271. data.v0 = this.v0.toArray();
  21272. data.v1 = this.v1.toArray();
  21273. data.v2 = this.v2.toArray();
  21274. data.v3 = this.v3.toArray();
  21275. return data;
  21276. }
  21277. fromJSON( json ) {
  21278. super.fromJSON( json );
  21279. this.v0.fromArray( json.v0 );
  21280. this.v1.fromArray( json.v1 );
  21281. this.v2.fromArray( json.v2 );
  21282. this.v3.fromArray( json.v3 );
  21283. return this;
  21284. }
  21285. }
  21286. class CubicBezierCurve3 extends Curve {
  21287. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  21288. super();
  21289. this.isCubicBezierCurve3 = true;
  21290. this.type = 'CubicBezierCurve3';
  21291. this.v0 = v0;
  21292. this.v1 = v1;
  21293. this.v2 = v2;
  21294. this.v3 = v3;
  21295. }
  21296. getPoint( t, optionalTarget = new Vector3() ) {
  21297. const point = optionalTarget;
  21298. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21299. point.set(
  21300. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21301. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  21302. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  21303. );
  21304. return point;
  21305. }
  21306. copy( source ) {
  21307. super.copy( source );
  21308. this.v0.copy( source.v0 );
  21309. this.v1.copy( source.v1 );
  21310. this.v2.copy( source.v2 );
  21311. this.v3.copy( source.v3 );
  21312. return this;
  21313. }
  21314. toJSON() {
  21315. const data = super.toJSON();
  21316. data.v0 = this.v0.toArray();
  21317. data.v1 = this.v1.toArray();
  21318. data.v2 = this.v2.toArray();
  21319. data.v3 = this.v3.toArray();
  21320. return data;
  21321. }
  21322. fromJSON( json ) {
  21323. super.fromJSON( json );
  21324. this.v0.fromArray( json.v0 );
  21325. this.v1.fromArray( json.v1 );
  21326. this.v2.fromArray( json.v2 );
  21327. this.v3.fromArray( json.v3 );
  21328. return this;
  21329. }
  21330. }
  21331. class LineCurve extends Curve {
  21332. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  21333. super();
  21334. this.isLineCurve = true;
  21335. this.type = 'LineCurve';
  21336. this.v1 = v1;
  21337. this.v2 = v2;
  21338. }
  21339. getPoint( t, optionalTarget = new Vector2() ) {
  21340. const point = optionalTarget;
  21341. if ( t === 1 ) {
  21342. point.copy( this.v2 );
  21343. } else {
  21344. point.copy( this.v2 ).sub( this.v1 );
  21345. point.multiplyScalar( t ).add( this.v1 );
  21346. }
  21347. return point;
  21348. }
  21349. // Line curve is linear, so we can overwrite default getPointAt
  21350. getPointAt( u, optionalTarget ) {
  21351. return this.getPoint( u, optionalTarget );
  21352. }
  21353. getTangent( t, optionalTarget = new Vector2() ) {
  21354. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21355. }
  21356. getTangentAt( u, optionalTarget ) {
  21357. return this.getTangent( u, optionalTarget );
  21358. }
  21359. copy( source ) {
  21360. super.copy( source );
  21361. this.v1.copy( source.v1 );
  21362. this.v2.copy( source.v2 );
  21363. return this;
  21364. }
  21365. toJSON() {
  21366. const data = super.toJSON();
  21367. data.v1 = this.v1.toArray();
  21368. data.v2 = this.v2.toArray();
  21369. return data;
  21370. }
  21371. fromJSON( json ) {
  21372. super.fromJSON( json );
  21373. this.v1.fromArray( json.v1 );
  21374. this.v2.fromArray( json.v2 );
  21375. return this;
  21376. }
  21377. }
  21378. class LineCurve3 extends Curve {
  21379. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21380. super();
  21381. this.isLineCurve3 = true;
  21382. this.type = 'LineCurve3';
  21383. this.v1 = v1;
  21384. this.v2 = v2;
  21385. }
  21386. getPoint( t, optionalTarget = new Vector3() ) {
  21387. const point = optionalTarget;
  21388. if ( t === 1 ) {
  21389. point.copy( this.v2 );
  21390. } else {
  21391. point.copy( this.v2 ).sub( this.v1 );
  21392. point.multiplyScalar( t ).add( this.v1 );
  21393. }
  21394. return point;
  21395. }
  21396. // Line curve is linear, so we can overwrite default getPointAt
  21397. getPointAt( u, optionalTarget ) {
  21398. return this.getPoint( u, optionalTarget );
  21399. }
  21400. getTangent( t, optionalTarget = new Vector3() ) {
  21401. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21402. }
  21403. getTangentAt( u, optionalTarget ) {
  21404. return this.getTangent( u, optionalTarget );
  21405. }
  21406. copy( source ) {
  21407. super.copy( source );
  21408. this.v1.copy( source.v1 );
  21409. this.v2.copy( source.v2 );
  21410. return this;
  21411. }
  21412. toJSON() {
  21413. const data = super.toJSON();
  21414. data.v1 = this.v1.toArray();
  21415. data.v2 = this.v2.toArray();
  21416. return data;
  21417. }
  21418. fromJSON( json ) {
  21419. super.fromJSON( json );
  21420. this.v1.fromArray( json.v1 );
  21421. this.v2.fromArray( json.v2 );
  21422. return this;
  21423. }
  21424. }
  21425. class QuadraticBezierCurve extends Curve {
  21426. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21427. super();
  21428. this.isQuadraticBezierCurve = true;
  21429. this.type = 'QuadraticBezierCurve';
  21430. this.v0 = v0;
  21431. this.v1 = v1;
  21432. this.v2 = v2;
  21433. }
  21434. getPoint( t, optionalTarget = new Vector2() ) {
  21435. const point = optionalTarget;
  21436. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21437. point.set(
  21438. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21439. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21440. );
  21441. return point;
  21442. }
  21443. copy( source ) {
  21444. super.copy( source );
  21445. this.v0.copy( source.v0 );
  21446. this.v1.copy( source.v1 );
  21447. this.v2.copy( source.v2 );
  21448. return this;
  21449. }
  21450. toJSON() {
  21451. const data = super.toJSON();
  21452. data.v0 = this.v0.toArray();
  21453. data.v1 = this.v1.toArray();
  21454. data.v2 = this.v2.toArray();
  21455. return data;
  21456. }
  21457. fromJSON( json ) {
  21458. super.fromJSON( json );
  21459. this.v0.fromArray( json.v0 );
  21460. this.v1.fromArray( json.v1 );
  21461. this.v2.fromArray( json.v2 );
  21462. return this;
  21463. }
  21464. }
  21465. class QuadraticBezierCurve3 extends Curve {
  21466. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21467. super();
  21468. this.isQuadraticBezierCurve3 = true;
  21469. this.type = 'QuadraticBezierCurve3';
  21470. this.v0 = v0;
  21471. this.v1 = v1;
  21472. this.v2 = v2;
  21473. }
  21474. getPoint( t, optionalTarget = new Vector3() ) {
  21475. const point = optionalTarget;
  21476. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21477. point.set(
  21478. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21479. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21480. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21481. );
  21482. return point;
  21483. }
  21484. copy( source ) {
  21485. super.copy( source );
  21486. this.v0.copy( source.v0 );
  21487. this.v1.copy( source.v1 );
  21488. this.v2.copy( source.v2 );
  21489. return this;
  21490. }
  21491. toJSON() {
  21492. const data = super.toJSON();
  21493. data.v0 = this.v0.toArray();
  21494. data.v1 = this.v1.toArray();
  21495. data.v2 = this.v2.toArray();
  21496. return data;
  21497. }
  21498. fromJSON( json ) {
  21499. super.fromJSON( json );
  21500. this.v0.fromArray( json.v0 );
  21501. this.v1.fromArray( json.v1 );
  21502. this.v2.fromArray( json.v2 );
  21503. return this;
  21504. }
  21505. }
  21506. class SplineCurve extends Curve {
  21507. constructor( points = [] ) {
  21508. super();
  21509. this.isSplineCurve = true;
  21510. this.type = 'SplineCurve';
  21511. this.points = points;
  21512. }
  21513. getPoint( t, optionalTarget = new Vector2() ) {
  21514. const point = optionalTarget;
  21515. const points = this.points;
  21516. const p = ( points.length - 1 ) * t;
  21517. const intPoint = Math.floor( p );
  21518. const weight = p - intPoint;
  21519. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21520. const p1 = points[ intPoint ];
  21521. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21522. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21523. point.set(
  21524. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21525. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21526. );
  21527. return point;
  21528. }
  21529. copy( source ) {
  21530. super.copy( source );
  21531. this.points = [];
  21532. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21533. const point = source.points[ i ];
  21534. this.points.push( point.clone() );
  21535. }
  21536. return this;
  21537. }
  21538. toJSON() {
  21539. const data = super.toJSON();
  21540. data.points = [];
  21541. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21542. const point = this.points[ i ];
  21543. data.points.push( point.toArray() );
  21544. }
  21545. return data;
  21546. }
  21547. fromJSON( json ) {
  21548. super.fromJSON( json );
  21549. this.points = [];
  21550. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21551. const point = json.points[ i ];
  21552. this.points.push( new Vector2().fromArray( point ) );
  21553. }
  21554. return this;
  21555. }
  21556. }
  21557. var Curves = /*#__PURE__*/Object.freeze({
  21558. __proto__: null,
  21559. ArcCurve: ArcCurve,
  21560. CatmullRomCurve3: CatmullRomCurve3,
  21561. CubicBezierCurve: CubicBezierCurve,
  21562. CubicBezierCurve3: CubicBezierCurve3,
  21563. EllipseCurve: EllipseCurve,
  21564. LineCurve: LineCurve,
  21565. LineCurve3: LineCurve3,
  21566. QuadraticBezierCurve: QuadraticBezierCurve,
  21567. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21568. SplineCurve: SplineCurve
  21569. });
  21570. /**************************************************************
  21571. * Curved Path - a curve path is simply a array of connected
  21572. * curves, but retains the api of a curve
  21573. **************************************************************/
  21574. class CurvePath extends Curve {
  21575. constructor() {
  21576. super();
  21577. this.type = 'CurvePath';
  21578. this.curves = [];
  21579. this.autoClose = false; // Automatically closes the path
  21580. }
  21581. add( curve ) {
  21582. this.curves.push( curve );
  21583. }
  21584. closePath() {
  21585. // Add a line curve if start and end of lines are not connected
  21586. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21587. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21588. if ( ! startPoint.equals( endPoint ) ) {
  21589. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  21590. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  21591. }
  21592. return this;
  21593. }
  21594. // To get accurate point with reference to
  21595. // entire path distance at time t,
  21596. // following has to be done:
  21597. // 1. Length of each sub path have to be known
  21598. // 2. Locate and identify type of curve
  21599. // 3. Get t for the curve
  21600. // 4. Return curve.getPointAt(t')
  21601. getPoint( t, optionalTarget ) {
  21602. const d = t * this.getLength();
  21603. const curveLengths = this.getCurveLengths();
  21604. let i = 0;
  21605. // To think about boundaries points.
  21606. while ( i < curveLengths.length ) {
  21607. if ( curveLengths[ i ] >= d ) {
  21608. const diff = curveLengths[ i ] - d;
  21609. const curve = this.curves[ i ];
  21610. const segmentLength = curve.getLength();
  21611. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21612. return curve.getPointAt( u, optionalTarget );
  21613. }
  21614. i ++;
  21615. }
  21616. return null;
  21617. // loop where sum != 0, sum > d , sum+1 <d
  21618. }
  21619. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21620. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21621. // getPoint() depends on getLength
  21622. getLength() {
  21623. const lens = this.getCurveLengths();
  21624. return lens[ lens.length - 1 ];
  21625. }
  21626. // cacheLengths must be recalculated.
  21627. updateArcLengths() {
  21628. this.needsUpdate = true;
  21629. this.cacheLengths = null;
  21630. this.getCurveLengths();
  21631. }
  21632. // Compute lengths and cache them
  21633. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21634. getCurveLengths() {
  21635. // We use cache values if curves and cache array are same length
  21636. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21637. return this.cacheLengths;
  21638. }
  21639. // Get length of sub-curve
  21640. // Push sums into cached array
  21641. const lengths = [];
  21642. let sums = 0;
  21643. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21644. sums += this.curves[ i ].getLength();
  21645. lengths.push( sums );
  21646. }
  21647. this.cacheLengths = lengths;
  21648. return lengths;
  21649. }
  21650. getSpacedPoints( divisions = 40 ) {
  21651. const points = [];
  21652. for ( let i = 0; i <= divisions; i ++ ) {
  21653. points.push( this.getPoint( i / divisions ) );
  21654. }
  21655. if ( this.autoClose ) {
  21656. points.push( points[ 0 ] );
  21657. }
  21658. return points;
  21659. }
  21660. getPoints( divisions = 12 ) {
  21661. const points = [];
  21662. let last;
  21663. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21664. const curve = curves[ i ];
  21665. const resolution = curve.isEllipseCurve ? divisions * 2
  21666. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  21667. : curve.isSplineCurve ? divisions * curve.points.length
  21668. : divisions;
  21669. const pts = curve.getPoints( resolution );
  21670. for ( let j = 0; j < pts.length; j ++ ) {
  21671. const point = pts[ j ];
  21672. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21673. points.push( point );
  21674. last = point;
  21675. }
  21676. }
  21677. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21678. points.push( points[ 0 ] );
  21679. }
  21680. return points;
  21681. }
  21682. copy( source ) {
  21683. super.copy( source );
  21684. this.curves = [];
  21685. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21686. const curve = source.curves[ i ];
  21687. this.curves.push( curve.clone() );
  21688. }
  21689. this.autoClose = source.autoClose;
  21690. return this;
  21691. }
  21692. toJSON() {
  21693. const data = super.toJSON();
  21694. data.autoClose = this.autoClose;
  21695. data.curves = [];
  21696. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21697. const curve = this.curves[ i ];
  21698. data.curves.push( curve.toJSON() );
  21699. }
  21700. return data;
  21701. }
  21702. fromJSON( json ) {
  21703. super.fromJSON( json );
  21704. this.autoClose = json.autoClose;
  21705. this.curves = [];
  21706. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21707. const curve = json.curves[ i ];
  21708. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21709. }
  21710. return this;
  21711. }
  21712. }
  21713. class Path extends CurvePath {
  21714. constructor( points ) {
  21715. super();
  21716. this.type = 'Path';
  21717. this.currentPoint = new Vector2();
  21718. if ( points ) {
  21719. this.setFromPoints( points );
  21720. }
  21721. }
  21722. setFromPoints( points ) {
  21723. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21724. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21725. this.lineTo( points[ i ].x, points[ i ].y );
  21726. }
  21727. return this;
  21728. }
  21729. moveTo( x, y ) {
  21730. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21731. return this;
  21732. }
  21733. lineTo( x, y ) {
  21734. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21735. this.curves.push( curve );
  21736. this.currentPoint.set( x, y );
  21737. return this;
  21738. }
  21739. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21740. const curve = new QuadraticBezierCurve(
  21741. this.currentPoint.clone(),
  21742. new Vector2( aCPx, aCPy ),
  21743. new Vector2( aX, aY )
  21744. );
  21745. this.curves.push( curve );
  21746. this.currentPoint.set( aX, aY );
  21747. return this;
  21748. }
  21749. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21750. const curve = new CubicBezierCurve(
  21751. this.currentPoint.clone(),
  21752. new Vector2( aCP1x, aCP1y ),
  21753. new Vector2( aCP2x, aCP2y ),
  21754. new Vector2( aX, aY )
  21755. );
  21756. this.curves.push( curve );
  21757. this.currentPoint.set( aX, aY );
  21758. return this;
  21759. }
  21760. splineThru( pts /*Array of Vector*/ ) {
  21761. const npts = [ this.currentPoint.clone() ].concat( pts );
  21762. const curve = new SplineCurve( npts );
  21763. this.curves.push( curve );
  21764. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21765. return this;
  21766. }
  21767. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21768. const x0 = this.currentPoint.x;
  21769. const y0 = this.currentPoint.y;
  21770. this.absarc( aX + x0, aY + y0, aRadius,
  21771. aStartAngle, aEndAngle, aClockwise );
  21772. return this;
  21773. }
  21774. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21775. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21776. return this;
  21777. }
  21778. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21779. const x0 = this.currentPoint.x;
  21780. const y0 = this.currentPoint.y;
  21781. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21782. return this;
  21783. }
  21784. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21785. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21786. if ( this.curves.length > 0 ) {
  21787. // if a previous curve is present, attempt to join
  21788. const firstPoint = curve.getPoint( 0 );
  21789. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21790. this.lineTo( firstPoint.x, firstPoint.y );
  21791. }
  21792. }
  21793. this.curves.push( curve );
  21794. const lastPoint = curve.getPoint( 1 );
  21795. this.currentPoint.copy( lastPoint );
  21796. return this;
  21797. }
  21798. copy( source ) {
  21799. super.copy( source );
  21800. this.currentPoint.copy( source.currentPoint );
  21801. return this;
  21802. }
  21803. toJSON() {
  21804. const data = super.toJSON();
  21805. data.currentPoint = this.currentPoint.toArray();
  21806. return data;
  21807. }
  21808. fromJSON( json ) {
  21809. super.fromJSON( json );
  21810. this.currentPoint.fromArray( json.currentPoint );
  21811. return this;
  21812. }
  21813. }
  21814. class LatheGeometry extends BufferGeometry {
  21815. 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 ) {
  21816. super();
  21817. this.type = 'LatheGeometry';
  21818. this.parameters = {
  21819. points: points,
  21820. segments: segments,
  21821. phiStart: phiStart,
  21822. phiLength: phiLength
  21823. };
  21824. segments = Math.floor( segments );
  21825. // clamp phiLength so it's in range of [ 0, 2PI ]
  21826. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21827. // buffers
  21828. const indices = [];
  21829. const vertices = [];
  21830. const uvs = [];
  21831. const initNormals = [];
  21832. const normals = [];
  21833. // helper variables
  21834. const inverseSegments = 1.0 / segments;
  21835. const vertex = new Vector3();
  21836. const uv = new Vector2();
  21837. const normal = new Vector3();
  21838. const curNormal = new Vector3();
  21839. const prevNormal = new Vector3();
  21840. let dx = 0;
  21841. let dy = 0;
  21842. // pre-compute normals for initial "meridian"
  21843. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21844. switch ( j ) {
  21845. case 0: // special handling for 1st vertex on path
  21846. dx = points[ j + 1 ].x - points[ j ].x;
  21847. dy = points[ j + 1 ].y - points[ j ].y;
  21848. normal.x = dy * 1.0;
  21849. normal.y = - dx;
  21850. normal.z = dy * 0.0;
  21851. prevNormal.copy( normal );
  21852. normal.normalize();
  21853. initNormals.push( normal.x, normal.y, normal.z );
  21854. break;
  21855. case ( points.length - 1 ): // special handling for last Vertex on path
  21856. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  21857. break;
  21858. default: // default handling for all vertices in between
  21859. dx = points[ j + 1 ].x - points[ j ].x;
  21860. dy = points[ j + 1 ].y - points[ j ].y;
  21861. normal.x = dy * 1.0;
  21862. normal.y = - dx;
  21863. normal.z = dy * 0.0;
  21864. curNormal.copy( normal );
  21865. normal.x += prevNormal.x;
  21866. normal.y += prevNormal.y;
  21867. normal.z += prevNormal.z;
  21868. normal.normalize();
  21869. initNormals.push( normal.x, normal.y, normal.z );
  21870. prevNormal.copy( curNormal );
  21871. }
  21872. }
  21873. // generate vertices, uvs and normals
  21874. for ( let i = 0; i <= segments; i ++ ) {
  21875. const phi = phiStart + i * inverseSegments * phiLength;
  21876. const sin = Math.sin( phi );
  21877. const cos = Math.cos( phi );
  21878. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21879. // vertex
  21880. vertex.x = points[ j ].x * sin;
  21881. vertex.y = points[ j ].y;
  21882. vertex.z = points[ j ].x * cos;
  21883. vertices.push( vertex.x, vertex.y, vertex.z );
  21884. // uv
  21885. uv.x = i / segments;
  21886. uv.y = j / ( points.length - 1 );
  21887. uvs.push( uv.x, uv.y );
  21888. // normal
  21889. const x = initNormals[ 3 * j + 0 ] * sin;
  21890. const y = initNormals[ 3 * j + 1 ];
  21891. const z = initNormals[ 3 * j + 0 ] * cos;
  21892. normals.push( x, y, z );
  21893. }
  21894. }
  21895. // indices
  21896. for ( let i = 0; i < segments; i ++ ) {
  21897. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  21898. const base = j + i * points.length;
  21899. const a = base;
  21900. const b = base + points.length;
  21901. const c = base + points.length + 1;
  21902. const d = base + 1;
  21903. // faces
  21904. indices.push( a, b, d );
  21905. indices.push( c, d, b );
  21906. }
  21907. }
  21908. // build geometry
  21909. this.setIndex( indices );
  21910. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21911. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21912. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21913. }
  21914. copy( source ) {
  21915. super.copy( source );
  21916. this.parameters = Object.assign( {}, source.parameters );
  21917. return this;
  21918. }
  21919. static fromJSON( data ) {
  21920. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  21921. }
  21922. }
  21923. class CapsuleGeometry extends LatheGeometry {
  21924. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  21925. const path = new Path();
  21926. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  21927. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  21928. super( path.getPoints( capSegments ), radialSegments );
  21929. this.type = 'CapsuleGeometry';
  21930. this.parameters = {
  21931. radius: radius,
  21932. length: length,
  21933. capSegments: capSegments,
  21934. radialSegments: radialSegments,
  21935. };
  21936. }
  21937. static fromJSON( data ) {
  21938. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  21939. }
  21940. }
  21941. class CircleGeometry extends BufferGeometry {
  21942. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21943. super();
  21944. this.type = 'CircleGeometry';
  21945. this.parameters = {
  21946. radius: radius,
  21947. segments: segments,
  21948. thetaStart: thetaStart,
  21949. thetaLength: thetaLength
  21950. };
  21951. segments = Math.max( 3, segments );
  21952. // buffers
  21953. const indices = [];
  21954. const vertices = [];
  21955. const normals = [];
  21956. const uvs = [];
  21957. // helper variables
  21958. const vertex = new Vector3();
  21959. const uv = new Vector2();
  21960. // center point
  21961. vertices.push( 0, 0, 0 );
  21962. normals.push( 0, 0, 1 );
  21963. uvs.push( 0.5, 0.5 );
  21964. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21965. const segment = thetaStart + s / segments * thetaLength;
  21966. // vertex
  21967. vertex.x = radius * Math.cos( segment );
  21968. vertex.y = radius * Math.sin( segment );
  21969. vertices.push( vertex.x, vertex.y, vertex.z );
  21970. // normal
  21971. normals.push( 0, 0, 1 );
  21972. // uvs
  21973. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21974. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21975. uvs.push( uv.x, uv.y );
  21976. }
  21977. // indices
  21978. for ( let i = 1; i <= segments; i ++ ) {
  21979. indices.push( i, i + 1, 0 );
  21980. }
  21981. // build geometry
  21982. this.setIndex( indices );
  21983. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21984. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21985. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21986. }
  21987. copy( source ) {
  21988. super.copy( source );
  21989. this.parameters = Object.assign( {}, source.parameters );
  21990. return this;
  21991. }
  21992. static fromJSON( data ) {
  21993. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21994. }
  21995. }
  21996. class CylinderGeometry extends BufferGeometry {
  21997. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21998. super();
  21999. this.type = 'CylinderGeometry';
  22000. this.parameters = {
  22001. radiusTop: radiusTop,
  22002. radiusBottom: radiusBottom,
  22003. height: height,
  22004. radialSegments: radialSegments,
  22005. heightSegments: heightSegments,
  22006. openEnded: openEnded,
  22007. thetaStart: thetaStart,
  22008. thetaLength: thetaLength
  22009. };
  22010. const scope = this;
  22011. radialSegments = Math.floor( radialSegments );
  22012. heightSegments = Math.floor( heightSegments );
  22013. // buffers
  22014. const indices = [];
  22015. const vertices = [];
  22016. const normals = [];
  22017. const uvs = [];
  22018. // helper variables
  22019. let index = 0;
  22020. const indexArray = [];
  22021. const halfHeight = height / 2;
  22022. let groupStart = 0;
  22023. // generate geometry
  22024. generateTorso();
  22025. if ( openEnded === false ) {
  22026. if ( radiusTop > 0 ) generateCap( true );
  22027. if ( radiusBottom > 0 ) generateCap( false );
  22028. }
  22029. // build geometry
  22030. this.setIndex( indices );
  22031. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22032. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22033. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22034. function generateTorso() {
  22035. const normal = new Vector3();
  22036. const vertex = new Vector3();
  22037. let groupCount = 0;
  22038. // this will be used to calculate the normal
  22039. const slope = ( radiusBottom - radiusTop ) / height;
  22040. // generate vertices, normals and uvs
  22041. for ( let y = 0; y <= heightSegments; y ++ ) {
  22042. const indexRow = [];
  22043. const v = y / heightSegments;
  22044. // calculate the radius of the current row
  22045. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22046. for ( let x = 0; x <= radialSegments; x ++ ) {
  22047. const u = x / radialSegments;
  22048. const theta = u * thetaLength + thetaStart;
  22049. const sinTheta = Math.sin( theta );
  22050. const cosTheta = Math.cos( theta );
  22051. // vertex
  22052. vertex.x = radius * sinTheta;
  22053. vertex.y = - v * height + halfHeight;
  22054. vertex.z = radius * cosTheta;
  22055. vertices.push( vertex.x, vertex.y, vertex.z );
  22056. // normal
  22057. normal.set( sinTheta, slope, cosTheta ).normalize();
  22058. normals.push( normal.x, normal.y, normal.z );
  22059. // uv
  22060. uvs.push( u, 1 - v );
  22061. // save index of vertex in respective row
  22062. indexRow.push( index ++ );
  22063. }
  22064. // now save vertices of the row in our index array
  22065. indexArray.push( indexRow );
  22066. }
  22067. // generate indices
  22068. for ( let x = 0; x < radialSegments; x ++ ) {
  22069. for ( let y = 0; y < heightSegments; y ++ ) {
  22070. // we use the index array to access the correct indices
  22071. const a = indexArray[ y ][ x ];
  22072. const b = indexArray[ y + 1 ][ x ];
  22073. const c = indexArray[ y + 1 ][ x + 1 ];
  22074. const d = indexArray[ y ][ x + 1 ];
  22075. // faces
  22076. indices.push( a, b, d );
  22077. indices.push( b, c, d );
  22078. // update group counter
  22079. groupCount += 6;
  22080. }
  22081. }
  22082. // add a group to the geometry. this will ensure multi material support
  22083. scope.addGroup( groupStart, groupCount, 0 );
  22084. // calculate new start value for groups
  22085. groupStart += groupCount;
  22086. }
  22087. function generateCap( top ) {
  22088. // save the index of the first center vertex
  22089. const centerIndexStart = index;
  22090. const uv = new Vector2();
  22091. const vertex = new Vector3();
  22092. let groupCount = 0;
  22093. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22094. const sign = ( top === true ) ? 1 : - 1;
  22095. // first we generate the center vertex data of the cap.
  22096. // because the geometry needs one set of uvs per face,
  22097. // we must generate a center vertex per face/segment
  22098. for ( let x = 1; x <= radialSegments; x ++ ) {
  22099. // vertex
  22100. vertices.push( 0, halfHeight * sign, 0 );
  22101. // normal
  22102. normals.push( 0, sign, 0 );
  22103. // uv
  22104. uvs.push( 0.5, 0.5 );
  22105. // increase index
  22106. index ++;
  22107. }
  22108. // save the index of the last center vertex
  22109. const centerIndexEnd = index;
  22110. // now we generate the surrounding vertices, normals and uvs
  22111. for ( let x = 0; x <= radialSegments; x ++ ) {
  22112. const u = x / radialSegments;
  22113. const theta = u * thetaLength + thetaStart;
  22114. const cosTheta = Math.cos( theta );
  22115. const sinTheta = Math.sin( theta );
  22116. // vertex
  22117. vertex.x = radius * sinTheta;
  22118. vertex.y = halfHeight * sign;
  22119. vertex.z = radius * cosTheta;
  22120. vertices.push( vertex.x, vertex.y, vertex.z );
  22121. // normal
  22122. normals.push( 0, sign, 0 );
  22123. // uv
  22124. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22125. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22126. uvs.push( uv.x, uv.y );
  22127. // increase index
  22128. index ++;
  22129. }
  22130. // generate indices
  22131. for ( let x = 0; x < radialSegments; x ++ ) {
  22132. const c = centerIndexStart + x;
  22133. const i = centerIndexEnd + x;
  22134. if ( top === true ) {
  22135. // face top
  22136. indices.push( i, i + 1, c );
  22137. } else {
  22138. // face bottom
  22139. indices.push( i + 1, i, c );
  22140. }
  22141. groupCount += 3;
  22142. }
  22143. // add a group to the geometry. this will ensure multi material support
  22144. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22145. // calculate new start value for groups
  22146. groupStart += groupCount;
  22147. }
  22148. }
  22149. copy( source ) {
  22150. super.copy( source );
  22151. this.parameters = Object.assign( {}, source.parameters );
  22152. return this;
  22153. }
  22154. static fromJSON( data ) {
  22155. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22156. }
  22157. }
  22158. class ConeGeometry extends CylinderGeometry {
  22159. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22160. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22161. this.type = 'ConeGeometry';
  22162. this.parameters = {
  22163. radius: radius,
  22164. height: height,
  22165. radialSegments: radialSegments,
  22166. heightSegments: heightSegments,
  22167. openEnded: openEnded,
  22168. thetaStart: thetaStart,
  22169. thetaLength: thetaLength
  22170. };
  22171. }
  22172. static fromJSON( data ) {
  22173. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22174. }
  22175. }
  22176. class PolyhedronGeometry extends BufferGeometry {
  22177. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22178. super();
  22179. this.type = 'PolyhedronGeometry';
  22180. this.parameters = {
  22181. vertices: vertices,
  22182. indices: indices,
  22183. radius: radius,
  22184. detail: detail
  22185. };
  22186. // default buffer data
  22187. const vertexBuffer = [];
  22188. const uvBuffer = [];
  22189. // the subdivision creates the vertex buffer data
  22190. subdivide( detail );
  22191. // all vertices should lie on a conceptual sphere with a given radius
  22192. applyRadius( radius );
  22193. // finally, create the uv data
  22194. generateUVs();
  22195. // build non-indexed geometry
  22196. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22197. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22198. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22199. if ( detail === 0 ) {
  22200. this.computeVertexNormals(); // flat normals
  22201. } else {
  22202. this.normalizeNormals(); // smooth normals
  22203. }
  22204. // helper functions
  22205. function subdivide( detail ) {
  22206. const a = new Vector3();
  22207. const b = new Vector3();
  22208. const c = new Vector3();
  22209. // iterate over all faces and apply a subdivision with the given detail value
  22210. for ( let i = 0; i < indices.length; i += 3 ) {
  22211. // get the vertices of the face
  22212. getVertexByIndex( indices[ i + 0 ], a );
  22213. getVertexByIndex( indices[ i + 1 ], b );
  22214. getVertexByIndex( indices[ i + 2 ], c );
  22215. // perform subdivision
  22216. subdivideFace( a, b, c, detail );
  22217. }
  22218. }
  22219. function subdivideFace( a, b, c, detail ) {
  22220. const cols = detail + 1;
  22221. // we use this multidimensional array as a data structure for creating the subdivision
  22222. const v = [];
  22223. // construct all of the vertices for this subdivision
  22224. for ( let i = 0; i <= cols; i ++ ) {
  22225. v[ i ] = [];
  22226. const aj = a.clone().lerp( c, i / cols );
  22227. const bj = b.clone().lerp( c, i / cols );
  22228. const rows = cols - i;
  22229. for ( let j = 0; j <= rows; j ++ ) {
  22230. if ( j === 0 && i === cols ) {
  22231. v[ i ][ j ] = aj;
  22232. } else {
  22233. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22234. }
  22235. }
  22236. }
  22237. // construct all of the faces
  22238. for ( let i = 0; i < cols; i ++ ) {
  22239. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22240. const k = Math.floor( j / 2 );
  22241. if ( j % 2 === 0 ) {
  22242. pushVertex( v[ i ][ k + 1 ] );
  22243. pushVertex( v[ i + 1 ][ k ] );
  22244. pushVertex( v[ i ][ k ] );
  22245. } else {
  22246. pushVertex( v[ i ][ k + 1 ] );
  22247. pushVertex( v[ i + 1 ][ k + 1 ] );
  22248. pushVertex( v[ i + 1 ][ k ] );
  22249. }
  22250. }
  22251. }
  22252. }
  22253. function applyRadius( radius ) {
  22254. const vertex = new Vector3();
  22255. // iterate over the entire buffer and apply the radius to each vertex
  22256. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22257. vertex.x = vertexBuffer[ i + 0 ];
  22258. vertex.y = vertexBuffer[ i + 1 ];
  22259. vertex.z = vertexBuffer[ i + 2 ];
  22260. vertex.normalize().multiplyScalar( radius );
  22261. vertexBuffer[ i + 0 ] = vertex.x;
  22262. vertexBuffer[ i + 1 ] = vertex.y;
  22263. vertexBuffer[ i + 2 ] = vertex.z;
  22264. }
  22265. }
  22266. function generateUVs() {
  22267. const vertex = new Vector3();
  22268. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22269. vertex.x = vertexBuffer[ i + 0 ];
  22270. vertex.y = vertexBuffer[ i + 1 ];
  22271. vertex.z = vertexBuffer[ i + 2 ];
  22272. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22273. const v = inclination( vertex ) / Math.PI + 0.5;
  22274. uvBuffer.push( u, 1 - v );
  22275. }
  22276. correctUVs();
  22277. correctSeam();
  22278. }
  22279. function correctSeam() {
  22280. // handle case when face straddles the seam, see #3269
  22281. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22282. // uv data of a single face
  22283. const x0 = uvBuffer[ i + 0 ];
  22284. const x1 = uvBuffer[ i + 2 ];
  22285. const x2 = uvBuffer[ i + 4 ];
  22286. const max = Math.max( x0, x1, x2 );
  22287. const min = Math.min( x0, x1, x2 );
  22288. // 0.9 is somewhat arbitrary
  22289. if ( max > 0.9 && min < 0.1 ) {
  22290. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22291. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22292. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22293. }
  22294. }
  22295. }
  22296. function pushVertex( vertex ) {
  22297. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22298. }
  22299. function getVertexByIndex( index, vertex ) {
  22300. const stride = index * 3;
  22301. vertex.x = vertices[ stride + 0 ];
  22302. vertex.y = vertices[ stride + 1 ];
  22303. vertex.z = vertices[ stride + 2 ];
  22304. }
  22305. function correctUVs() {
  22306. const a = new Vector3();
  22307. const b = new Vector3();
  22308. const c = new Vector3();
  22309. const centroid = new Vector3();
  22310. const uvA = new Vector2();
  22311. const uvB = new Vector2();
  22312. const uvC = new Vector2();
  22313. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22314. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22315. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22316. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22317. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22318. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22319. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22320. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22321. const azi = azimuth( centroid );
  22322. correctUV( uvA, j + 0, a, azi );
  22323. correctUV( uvB, j + 2, b, azi );
  22324. correctUV( uvC, j + 4, c, azi );
  22325. }
  22326. }
  22327. function correctUV( uv, stride, vector, azimuth ) {
  22328. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22329. uvBuffer[ stride ] = uv.x - 1;
  22330. }
  22331. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22332. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22333. }
  22334. }
  22335. // Angle around the Y axis, counter-clockwise when looking from above.
  22336. function azimuth( vector ) {
  22337. return Math.atan2( vector.z, - vector.x );
  22338. }
  22339. // Angle above the XZ plane.
  22340. function inclination( vector ) {
  22341. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22342. }
  22343. }
  22344. copy( source ) {
  22345. super.copy( source );
  22346. this.parameters = Object.assign( {}, source.parameters );
  22347. return this;
  22348. }
  22349. static fromJSON( data ) {
  22350. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22351. }
  22352. }
  22353. class DodecahedronGeometry extends PolyhedronGeometry {
  22354. constructor( radius = 1, detail = 0 ) {
  22355. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22356. const r = 1 / t;
  22357. const vertices = [
  22358. // (±1, ±1, ±1)
  22359. - 1, - 1, - 1, - 1, - 1, 1,
  22360. - 1, 1, - 1, - 1, 1, 1,
  22361. 1, - 1, - 1, 1, - 1, 1,
  22362. 1, 1, - 1, 1, 1, 1,
  22363. // (0, ±1/φ, ±φ)
  22364. 0, - r, - t, 0, - r, t,
  22365. 0, r, - t, 0, r, t,
  22366. // (±1/φ, ±φ, 0)
  22367. - r, - t, 0, - r, t, 0,
  22368. r, - t, 0, r, t, 0,
  22369. // (±φ, 0, ±1/φ)
  22370. - t, 0, - r, t, 0, - r,
  22371. - t, 0, r, t, 0, r
  22372. ];
  22373. const indices = [
  22374. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22375. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22376. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22377. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22378. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22379. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22380. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22381. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22382. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22383. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22384. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22385. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22386. ];
  22387. super( vertices, indices, radius, detail );
  22388. this.type = 'DodecahedronGeometry';
  22389. this.parameters = {
  22390. radius: radius,
  22391. detail: detail
  22392. };
  22393. }
  22394. static fromJSON( data ) {
  22395. return new DodecahedronGeometry( data.radius, data.detail );
  22396. }
  22397. }
  22398. const _v0 = /*@__PURE__*/ new Vector3();
  22399. const _v1$1 = /*@__PURE__*/ new Vector3();
  22400. const _normal = /*@__PURE__*/ new Vector3();
  22401. const _triangle = /*@__PURE__*/ new Triangle();
  22402. class EdgesGeometry extends BufferGeometry {
  22403. constructor( geometry = null, thresholdAngle = 1 ) {
  22404. super();
  22405. this.type = 'EdgesGeometry';
  22406. this.parameters = {
  22407. geometry: geometry,
  22408. thresholdAngle: thresholdAngle
  22409. };
  22410. if ( geometry !== null ) {
  22411. const precisionPoints = 4;
  22412. const precision = Math.pow( 10, precisionPoints );
  22413. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22414. const indexAttr = geometry.getIndex();
  22415. const positionAttr = geometry.getAttribute( 'position' );
  22416. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22417. const indexArr = [ 0, 0, 0 ];
  22418. const vertKeys = [ 'a', 'b', 'c' ];
  22419. const hashes = new Array( 3 );
  22420. const edgeData = {};
  22421. const vertices = [];
  22422. for ( let i = 0; i < indexCount; i += 3 ) {
  22423. if ( indexAttr ) {
  22424. indexArr[ 0 ] = indexAttr.getX( i );
  22425. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22426. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22427. } else {
  22428. indexArr[ 0 ] = i;
  22429. indexArr[ 1 ] = i + 1;
  22430. indexArr[ 2 ] = i + 2;
  22431. }
  22432. const { a, b, c } = _triangle;
  22433. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22434. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22435. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22436. _triangle.getNormal( _normal );
  22437. // create hashes for the edge from the vertices
  22438. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22439. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22440. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22441. // skip degenerate triangles
  22442. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22443. continue;
  22444. }
  22445. // iterate over every edge
  22446. for ( let j = 0; j < 3; j ++ ) {
  22447. // get the first and next vertex making up the edge
  22448. const jNext = ( j + 1 ) % 3;
  22449. const vecHash0 = hashes[ j ];
  22450. const vecHash1 = hashes[ jNext ];
  22451. const v0 = _triangle[ vertKeys[ j ] ];
  22452. const v1 = _triangle[ vertKeys[ jNext ] ];
  22453. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22454. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22455. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22456. // if we found a sibling edge add it into the vertex array if
  22457. // it meets the angle threshold and delete the edge from the map.
  22458. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22459. vertices.push( v0.x, v0.y, v0.z );
  22460. vertices.push( v1.x, v1.y, v1.z );
  22461. }
  22462. edgeData[ reverseHash ] = null;
  22463. } else if ( ! ( hash in edgeData ) ) {
  22464. // if we've already got an edge here then skip adding a new one
  22465. edgeData[ hash ] = {
  22466. index0: indexArr[ j ],
  22467. index1: indexArr[ jNext ],
  22468. normal: _normal.clone(),
  22469. };
  22470. }
  22471. }
  22472. }
  22473. // iterate over all remaining, unmatched edges and add them to the vertex array
  22474. for ( const key in edgeData ) {
  22475. if ( edgeData[ key ] ) {
  22476. const { index0, index1 } = edgeData[ key ];
  22477. _v0.fromBufferAttribute( positionAttr, index0 );
  22478. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22479. vertices.push( _v0.x, _v0.y, _v0.z );
  22480. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22481. }
  22482. }
  22483. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22484. }
  22485. }
  22486. copy( source ) {
  22487. super.copy( source );
  22488. this.parameters = Object.assign( {}, source.parameters );
  22489. return this;
  22490. }
  22491. }
  22492. class Shape extends Path {
  22493. constructor( points ) {
  22494. super( points );
  22495. this.uuid = generateUUID();
  22496. this.type = 'Shape';
  22497. this.holes = [];
  22498. }
  22499. getPointsHoles( divisions ) {
  22500. const holesPts = [];
  22501. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22502. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22503. }
  22504. return holesPts;
  22505. }
  22506. // get points of shape and holes (keypoints based on segments parameter)
  22507. extractPoints( divisions ) {
  22508. return {
  22509. shape: this.getPoints( divisions ),
  22510. holes: this.getPointsHoles( divisions )
  22511. };
  22512. }
  22513. copy( source ) {
  22514. super.copy( source );
  22515. this.holes = [];
  22516. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22517. const hole = source.holes[ i ];
  22518. this.holes.push( hole.clone() );
  22519. }
  22520. return this;
  22521. }
  22522. toJSON() {
  22523. const data = super.toJSON();
  22524. data.uuid = this.uuid;
  22525. data.holes = [];
  22526. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22527. const hole = this.holes[ i ];
  22528. data.holes.push( hole.toJSON() );
  22529. }
  22530. return data;
  22531. }
  22532. fromJSON( json ) {
  22533. super.fromJSON( json );
  22534. this.uuid = json.uuid;
  22535. this.holes = [];
  22536. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22537. const hole = json.holes[ i ];
  22538. this.holes.push( new Path().fromJSON( hole ) );
  22539. }
  22540. return this;
  22541. }
  22542. }
  22543. /**
  22544. * Port from https://github.com/mapbox/earcut (v2.2.4)
  22545. */
  22546. const Earcut = {
  22547. triangulate: function ( data, holeIndices, dim = 2 ) {
  22548. const hasHoles = holeIndices && holeIndices.length;
  22549. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  22550. let outerNode = linkedList( data, 0, outerLen, dim, true );
  22551. const triangles = [];
  22552. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  22553. let minX, minY, maxX, maxY, x, y, invSize;
  22554. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  22555. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22556. if ( data.length > 80 * dim ) {
  22557. minX = maxX = data[ 0 ];
  22558. minY = maxY = data[ 1 ];
  22559. for ( let i = dim; i < outerLen; i += dim ) {
  22560. x = data[ i ];
  22561. y = data[ i + 1 ];
  22562. if ( x < minX ) minX = x;
  22563. if ( y < minY ) minY = y;
  22564. if ( x > maxX ) maxX = x;
  22565. if ( y > maxY ) maxY = y;
  22566. }
  22567. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22568. invSize = Math.max( maxX - minX, maxY - minY );
  22569. invSize = invSize !== 0 ? 32767 / invSize : 0;
  22570. }
  22571. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  22572. return triangles;
  22573. }
  22574. };
  22575. // create a circular doubly linked list from polygon points in the specified winding order
  22576. function linkedList( data, start, end, dim, clockwise ) {
  22577. let i, last;
  22578. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22579. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22580. } else {
  22581. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22582. }
  22583. if ( last && equals( last, last.next ) ) {
  22584. removeNode( last );
  22585. last = last.next;
  22586. }
  22587. return last;
  22588. }
  22589. // eliminate colinear or duplicate points
  22590. function filterPoints( start, end ) {
  22591. if ( ! start ) return start;
  22592. if ( ! end ) end = start;
  22593. let p = start,
  22594. again;
  22595. do {
  22596. again = false;
  22597. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22598. removeNode( p );
  22599. p = end = p.prev;
  22600. if ( p === p.next ) break;
  22601. again = true;
  22602. } else {
  22603. p = p.next;
  22604. }
  22605. } while ( again || p !== end );
  22606. return end;
  22607. }
  22608. // main ear slicing loop which triangulates a polygon (given as a linked list)
  22609. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  22610. if ( ! ear ) return;
  22611. // interlink polygon nodes in z-order
  22612. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  22613. let stop = ear,
  22614. prev, next;
  22615. // iterate through ears, slicing them one by one
  22616. while ( ear.prev !== ear.next ) {
  22617. prev = ear.prev;
  22618. next = ear.next;
  22619. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  22620. // cut off the triangle
  22621. triangles.push( prev.i / dim | 0 );
  22622. triangles.push( ear.i / dim | 0 );
  22623. triangles.push( next.i / dim | 0 );
  22624. removeNode( ear );
  22625. // skipping the next vertex leads to less sliver triangles
  22626. ear = next.next;
  22627. stop = next.next;
  22628. continue;
  22629. }
  22630. ear = next;
  22631. // if we looped through the whole remaining polygon and can't find any more ears
  22632. if ( ear === stop ) {
  22633. // try filtering points and slicing again
  22634. if ( ! pass ) {
  22635. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  22636. // if this didn't work, try curing all small self-intersections locally
  22637. } else if ( pass === 1 ) {
  22638. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  22639. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  22640. // as a last resort, try splitting the remaining polygon into two
  22641. } else if ( pass === 2 ) {
  22642. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  22643. }
  22644. break;
  22645. }
  22646. }
  22647. }
  22648. // check whether a polygon node forms a valid ear with adjacent nodes
  22649. function isEar( ear ) {
  22650. const a = ear.prev,
  22651. b = ear,
  22652. c = ear.next;
  22653. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22654. // now make sure we don't have other points inside the potential ear
  22655. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22656. // triangle bbox; min & max are calculated like this for speed
  22657. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22658. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22659. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22660. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22661. let p = c.next;
  22662. while ( p !== a ) {
  22663. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  22664. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  22665. area( p.prev, p, p.next ) >= 0 ) return false;
  22666. p = p.next;
  22667. }
  22668. return true;
  22669. }
  22670. function isEarHashed( ear, minX, minY, invSize ) {
  22671. const a = ear.prev,
  22672. b = ear,
  22673. c = ear.next;
  22674. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22675. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22676. // triangle bbox; min & max are calculated like this for speed
  22677. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22678. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22679. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22680. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22681. // z-order range for the current triangle bbox;
  22682. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  22683. maxZ = zOrder( x1, y1, minX, minY, invSize );
  22684. let p = ear.prevZ,
  22685. n = ear.nextZ;
  22686. // look for points inside the triangle in both directions
  22687. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  22688. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22689. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22690. p = p.prevZ;
  22691. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22692. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22693. n = n.nextZ;
  22694. }
  22695. // look for remaining points in decreasing z-order
  22696. while ( p && p.z >= minZ ) {
  22697. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22698. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22699. p = p.prevZ;
  22700. }
  22701. // look for remaining points in increasing z-order
  22702. while ( n && n.z <= maxZ ) {
  22703. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22704. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22705. n = n.nextZ;
  22706. }
  22707. return true;
  22708. }
  22709. // go through all polygon nodes and cure small local self-intersections
  22710. function cureLocalIntersections( start, triangles, dim ) {
  22711. let p = start;
  22712. do {
  22713. const a = p.prev,
  22714. b = p.next.next;
  22715. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  22716. triangles.push( a.i / dim | 0 );
  22717. triangles.push( p.i / dim | 0 );
  22718. triangles.push( b.i / dim | 0 );
  22719. // remove two nodes involved
  22720. removeNode( p );
  22721. removeNode( p.next );
  22722. p = start = b;
  22723. }
  22724. p = p.next;
  22725. } while ( p !== start );
  22726. return filterPoints( p );
  22727. }
  22728. // try splitting polygon into two and triangulate them independently
  22729. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  22730. // look for a valid diagonal that divides the polygon into two
  22731. let a = start;
  22732. do {
  22733. let b = a.next.next;
  22734. while ( b !== a.prev ) {
  22735. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  22736. // split the polygon in two by the diagonal
  22737. let c = splitPolygon( a, b );
  22738. // filter colinear points around the cuts
  22739. a = filterPoints( a, a.next );
  22740. c = filterPoints( c, c.next );
  22741. // run earcut on each half
  22742. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  22743. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  22744. return;
  22745. }
  22746. b = b.next;
  22747. }
  22748. a = a.next;
  22749. } while ( a !== start );
  22750. }
  22751. // link every hole into the outer loop, producing a single-ring polygon without holes
  22752. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  22753. const queue = [];
  22754. let i, len, start, end, list;
  22755. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  22756. start = holeIndices[ i ] * dim;
  22757. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  22758. list = linkedList( data, start, end, dim, false );
  22759. if ( list === list.next ) list.steiner = true;
  22760. queue.push( getLeftmost( list ) );
  22761. }
  22762. queue.sort( compareX );
  22763. // process holes from left to right
  22764. for ( i = 0; i < queue.length; i ++ ) {
  22765. outerNode = eliminateHole( queue[ i ], outerNode );
  22766. }
  22767. return outerNode;
  22768. }
  22769. function compareX( a, b ) {
  22770. return a.x - b.x;
  22771. }
  22772. // find a bridge between vertices that connects hole with an outer ring and link it
  22773. function eliminateHole( hole, outerNode ) {
  22774. const bridge = findHoleBridge( hole, outerNode );
  22775. if ( ! bridge ) {
  22776. return outerNode;
  22777. }
  22778. const bridgeReverse = splitPolygon( bridge, hole );
  22779. // filter collinear points around the cuts
  22780. filterPoints( bridgeReverse, bridgeReverse.next );
  22781. return filterPoints( bridge, bridge.next );
  22782. }
  22783. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  22784. function findHoleBridge( hole, outerNode ) {
  22785. let p = outerNode,
  22786. qx = - Infinity,
  22787. m;
  22788. const hx = hole.x, hy = hole.y;
  22789. // find a segment intersected by a ray from the hole's leftmost point to the left;
  22790. // segment's endpoint with lesser x will be potential connection point
  22791. do {
  22792. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  22793. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  22794. if ( x <= hx && x > qx ) {
  22795. qx = x;
  22796. m = p.x < p.next.x ? p : p.next;
  22797. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  22798. }
  22799. }
  22800. p = p.next;
  22801. } while ( p !== outerNode );
  22802. if ( ! m ) return null;
  22803. // look for points inside the triangle of hole point, segment intersection and endpoint;
  22804. // if there are no points found, we have a valid connection;
  22805. // otherwise choose the point of the minimum angle with the ray as connection point
  22806. const stop = m,
  22807. mx = m.x,
  22808. my = m.y;
  22809. let tanMin = Infinity, tan;
  22810. p = m;
  22811. do {
  22812. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  22813. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  22814. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  22815. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  22816. m = p;
  22817. tanMin = tan;
  22818. }
  22819. }
  22820. p = p.next;
  22821. } while ( p !== stop );
  22822. return m;
  22823. }
  22824. // whether sector in vertex m contains sector in vertex p in the same coordinates
  22825. function sectorContainsSector( m, p ) {
  22826. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  22827. }
  22828. // interlink polygon nodes in z-order
  22829. function indexCurve( start, minX, minY, invSize ) {
  22830. let p = start;
  22831. do {
  22832. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  22833. p.prevZ = p.prev;
  22834. p.nextZ = p.next;
  22835. p = p.next;
  22836. } while ( p !== start );
  22837. p.prevZ.nextZ = null;
  22838. p.prevZ = null;
  22839. sortLinked( p );
  22840. }
  22841. // Simon Tatham's linked list merge sort algorithm
  22842. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  22843. function sortLinked( list ) {
  22844. let i, p, q, e, tail, numMerges, pSize, qSize,
  22845. inSize = 1;
  22846. do {
  22847. p = list;
  22848. list = null;
  22849. tail = null;
  22850. numMerges = 0;
  22851. while ( p ) {
  22852. numMerges ++;
  22853. q = p;
  22854. pSize = 0;
  22855. for ( i = 0; i < inSize; i ++ ) {
  22856. pSize ++;
  22857. q = q.nextZ;
  22858. if ( ! q ) break;
  22859. }
  22860. qSize = inSize;
  22861. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  22862. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  22863. e = p;
  22864. p = p.nextZ;
  22865. pSize --;
  22866. } else {
  22867. e = q;
  22868. q = q.nextZ;
  22869. qSize --;
  22870. }
  22871. if ( tail ) tail.nextZ = e;
  22872. else list = e;
  22873. e.prevZ = tail;
  22874. tail = e;
  22875. }
  22876. p = q;
  22877. }
  22878. tail.nextZ = null;
  22879. inSize *= 2;
  22880. } while ( numMerges > 1 );
  22881. return list;
  22882. }
  22883. // z-order of a point given coords and inverse of the longer side of data bbox
  22884. function zOrder( x, y, minX, minY, invSize ) {
  22885. // coords are transformed into non-negative 15-bit integer range
  22886. x = ( x - minX ) * invSize | 0;
  22887. y = ( y - minY ) * invSize | 0;
  22888. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  22889. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  22890. x = ( x | ( x << 2 ) ) & 0x33333333;
  22891. x = ( x | ( x << 1 ) ) & 0x55555555;
  22892. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  22893. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  22894. y = ( y | ( y << 2 ) ) & 0x33333333;
  22895. y = ( y | ( y << 1 ) ) & 0x55555555;
  22896. return x | ( y << 1 );
  22897. }
  22898. // find the leftmost node of a polygon ring
  22899. function getLeftmost( start ) {
  22900. let p = start,
  22901. leftmost = start;
  22902. do {
  22903. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  22904. p = p.next;
  22905. } while ( p !== start );
  22906. return leftmost;
  22907. }
  22908. // check if a point lies within a convex triangle
  22909. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  22910. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  22911. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  22912. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  22913. }
  22914. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  22915. function isValidDiagonal( a, b ) {
  22916. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  22917. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  22918. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  22919. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  22920. }
  22921. // signed area of a triangle
  22922. function area( p, q, r ) {
  22923. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  22924. }
  22925. // check if two points are equal
  22926. function equals( p1, p2 ) {
  22927. return p1.x === p2.x && p1.y === p2.y;
  22928. }
  22929. // check if two segments intersect
  22930. function intersects( p1, q1, p2, q2 ) {
  22931. const o1 = sign( area( p1, q1, p2 ) );
  22932. const o2 = sign( area( p1, q1, q2 ) );
  22933. const o3 = sign( area( p2, q2, p1 ) );
  22934. const o4 = sign( area( p2, q2, q1 ) );
  22935. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  22936. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  22937. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  22938. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  22939. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  22940. return false;
  22941. }
  22942. // for collinear points p, q, r, check if point q lies on segment pr
  22943. function onSegment( p, q, r ) {
  22944. 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 );
  22945. }
  22946. function sign( num ) {
  22947. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  22948. }
  22949. // check if a polygon diagonal intersects any polygon segments
  22950. function intersectsPolygon( a, b ) {
  22951. let p = a;
  22952. do {
  22953. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  22954. intersects( p, p.next, a, b ) ) return true;
  22955. p = p.next;
  22956. } while ( p !== a );
  22957. return false;
  22958. }
  22959. // check if a polygon diagonal is locally inside the polygon
  22960. function locallyInside( a, b ) {
  22961. return area( a.prev, a, a.next ) < 0 ?
  22962. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  22963. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  22964. }
  22965. // check if the middle point of a polygon diagonal is inside the polygon
  22966. function middleInside( a, b ) {
  22967. let p = a,
  22968. inside = false;
  22969. const px = ( a.x + b.x ) / 2,
  22970. py = ( a.y + b.y ) / 2;
  22971. do {
  22972. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  22973. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  22974. inside = ! inside;
  22975. p = p.next;
  22976. } while ( p !== a );
  22977. return inside;
  22978. }
  22979. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  22980. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  22981. function splitPolygon( a, b ) {
  22982. const a2 = new Node( a.i, a.x, a.y ),
  22983. b2 = new Node( b.i, b.x, b.y ),
  22984. an = a.next,
  22985. bp = b.prev;
  22986. a.next = b;
  22987. b.prev = a;
  22988. a2.next = an;
  22989. an.prev = a2;
  22990. b2.next = a2;
  22991. a2.prev = b2;
  22992. bp.next = b2;
  22993. b2.prev = bp;
  22994. return b2;
  22995. }
  22996. // create a node and optionally link it with previous one (in a circular doubly linked list)
  22997. function insertNode( i, x, y, last ) {
  22998. const p = new Node( i, x, y );
  22999. if ( ! last ) {
  23000. p.prev = p;
  23001. p.next = p;
  23002. } else {
  23003. p.next = last.next;
  23004. p.prev = last;
  23005. last.next.prev = p;
  23006. last.next = p;
  23007. }
  23008. return p;
  23009. }
  23010. function removeNode( p ) {
  23011. p.next.prev = p.prev;
  23012. p.prev.next = p.next;
  23013. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  23014. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  23015. }
  23016. function Node( i, x, y ) {
  23017. // vertex index in coordinates array
  23018. this.i = i;
  23019. // vertex coordinates
  23020. this.x = x;
  23021. this.y = y;
  23022. // previous and next vertex nodes in a polygon ring
  23023. this.prev = null;
  23024. this.next = null;
  23025. // z-order curve value
  23026. this.z = 0;
  23027. // previous and next nodes in z-order
  23028. this.prevZ = null;
  23029. this.nextZ = null;
  23030. // indicates whether this is a steiner point
  23031. this.steiner = false;
  23032. }
  23033. function signedArea( data, start, end, dim ) {
  23034. let sum = 0;
  23035. for ( let i = start, j = end - dim; i < end; i += dim ) {
  23036. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  23037. j = i;
  23038. }
  23039. return sum;
  23040. }
  23041. class ShapeUtils {
  23042. // calculate area of the contour polygon
  23043. static area( contour ) {
  23044. const n = contour.length;
  23045. let a = 0.0;
  23046. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  23047. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  23048. }
  23049. return a * 0.5;
  23050. }
  23051. static isClockWise( pts ) {
  23052. return ShapeUtils.area( pts ) < 0;
  23053. }
  23054. static triangulateShape( contour, holes ) {
  23055. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  23056. const holeIndices = []; // array of hole indices
  23057. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  23058. removeDupEndPts( contour );
  23059. addContour( vertices, contour );
  23060. //
  23061. let holeIndex = contour.length;
  23062. holes.forEach( removeDupEndPts );
  23063. for ( let i = 0; i < holes.length; i ++ ) {
  23064. holeIndices.push( holeIndex );
  23065. holeIndex += holes[ i ].length;
  23066. addContour( vertices, holes[ i ] );
  23067. }
  23068. //
  23069. const triangles = Earcut.triangulate( vertices, holeIndices );
  23070. //
  23071. for ( let i = 0; i < triangles.length; i += 3 ) {
  23072. faces.push( triangles.slice( i, i + 3 ) );
  23073. }
  23074. return faces;
  23075. }
  23076. }
  23077. function removeDupEndPts( points ) {
  23078. const l = points.length;
  23079. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  23080. points.pop();
  23081. }
  23082. }
  23083. function addContour( vertices, contour ) {
  23084. for ( let i = 0; i < contour.length; i ++ ) {
  23085. vertices.push( contour[ i ].x );
  23086. vertices.push( contour[ i ].y );
  23087. }
  23088. }
  23089. /**
  23090. * Creates extruded geometry from a path shape.
  23091. *
  23092. * parameters = {
  23093. *
  23094. * curveSegments: <int>, // number of points on the curves
  23095. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  23096. * depth: <float>, // Depth to extrude the shape
  23097. *
  23098. * bevelEnabled: <bool>, // turn on bevel
  23099. * bevelThickness: <float>, // how deep into the original shape bevel goes
  23100. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  23101. * bevelOffset: <float>, // how far from shape outline does bevel start
  23102. * bevelSegments: <int>, // number of bevel layers
  23103. *
  23104. * extrudePath: <THREE.Curve> // curve to extrude shape along
  23105. *
  23106. * UVGenerator: <Object> // object that provides UV generator functions
  23107. *
  23108. * }
  23109. */
  23110. class ExtrudeGeometry extends BufferGeometry {
  23111. 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 = {} ) {
  23112. super();
  23113. this.type = 'ExtrudeGeometry';
  23114. this.parameters = {
  23115. shapes: shapes,
  23116. options: options
  23117. };
  23118. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  23119. const scope = this;
  23120. const verticesArray = [];
  23121. const uvArray = [];
  23122. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23123. const shape = shapes[ i ];
  23124. addShape( shape );
  23125. }
  23126. // build geometry
  23127. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  23128. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  23129. this.computeVertexNormals();
  23130. // functions
  23131. function addShape( shape ) {
  23132. const placeholder = [];
  23133. // options
  23134. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  23135. const steps = options.steps !== undefined ? options.steps : 1;
  23136. const depth = options.depth !== undefined ? options.depth : 1;
  23137. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  23138. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  23139. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  23140. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  23141. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  23142. const extrudePath = options.extrudePath;
  23143. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  23144. //
  23145. let extrudePts, extrudeByPath = false;
  23146. let splineTube, binormal, normal, position2;
  23147. if ( extrudePath ) {
  23148. extrudePts = extrudePath.getSpacedPoints( steps );
  23149. extrudeByPath = true;
  23150. bevelEnabled = false; // bevels not supported for path extrusion
  23151. // SETUP TNB variables
  23152. // TODO1 - have a .isClosed in spline?
  23153. splineTube = extrudePath.computeFrenetFrames( steps, false );
  23154. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  23155. binormal = new Vector3();
  23156. normal = new Vector3();
  23157. position2 = new Vector3();
  23158. }
  23159. // Safeguards if bevels are not enabled
  23160. if ( ! bevelEnabled ) {
  23161. bevelSegments = 0;
  23162. bevelThickness = 0;
  23163. bevelSize = 0;
  23164. bevelOffset = 0;
  23165. }
  23166. // Variables initialization
  23167. const shapePoints = shape.extractPoints( curveSegments );
  23168. let vertices = shapePoints.shape;
  23169. const holes = shapePoints.holes;
  23170. const reverse = ! ShapeUtils.isClockWise( vertices );
  23171. if ( reverse ) {
  23172. vertices = vertices.reverse();
  23173. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  23174. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23175. const ahole = holes[ h ];
  23176. if ( ShapeUtils.isClockWise( ahole ) ) {
  23177. holes[ h ] = ahole.reverse();
  23178. }
  23179. }
  23180. }
  23181. const faces = ShapeUtils.triangulateShape( vertices, holes );
  23182. /* Vertices */
  23183. const contour = vertices; // vertices has all points but contour has only points of circumference
  23184. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23185. const ahole = holes[ h ];
  23186. vertices = vertices.concat( ahole );
  23187. }
  23188. function scalePt2( pt, vec, size ) {
  23189. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  23190. return pt.clone().addScaledVector( vec, size );
  23191. }
  23192. const vlen = vertices.length, flen = faces.length;
  23193. // Find directions for point movement
  23194. function getBevelVec( inPt, inPrev, inNext ) {
  23195. // computes for inPt the corresponding point inPt' on a new contour
  23196. // shifted by 1 unit (length of normalized vector) to the left
  23197. // if we walk along contour clockwise, this new contour is outside the old one
  23198. //
  23199. // inPt' is the intersection of the two lines parallel to the two
  23200. // adjacent edges of inPt at a distance of 1 unit on the left side.
  23201. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  23202. // good reading for geometry algorithms (here: line-line intersection)
  23203. // http://geomalgorithms.com/a05-_intersect-1.html
  23204. const v_prev_x = inPt.x - inPrev.x,
  23205. v_prev_y = inPt.y - inPrev.y;
  23206. const v_next_x = inNext.x - inPt.x,
  23207. v_next_y = inNext.y - inPt.y;
  23208. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  23209. // check for collinear edges
  23210. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23211. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  23212. // not collinear
  23213. // length of vectors for normalizing
  23214. const v_prev_len = Math.sqrt( v_prev_lensq );
  23215. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  23216. // shift adjacent points by unit vectors to the left
  23217. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  23218. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  23219. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  23220. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  23221. // scaling factor for v_prev to intersection point
  23222. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  23223. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  23224. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23225. // vector from inPt to intersection point
  23226. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  23227. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  23228. // Don't normalize!, otherwise sharp corners become ugly
  23229. // but prevent crazy spikes
  23230. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  23231. if ( v_trans_lensq <= 2 ) {
  23232. return new Vector2( v_trans_x, v_trans_y );
  23233. } else {
  23234. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  23235. }
  23236. } else {
  23237. // handle special case of collinear edges
  23238. let direction_eq = false; // assumes: opposite
  23239. if ( v_prev_x > Number.EPSILON ) {
  23240. if ( v_next_x > Number.EPSILON ) {
  23241. direction_eq = true;
  23242. }
  23243. } else {
  23244. if ( v_prev_x < - Number.EPSILON ) {
  23245. if ( v_next_x < - Number.EPSILON ) {
  23246. direction_eq = true;
  23247. }
  23248. } else {
  23249. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  23250. direction_eq = true;
  23251. }
  23252. }
  23253. }
  23254. if ( direction_eq ) {
  23255. // console.log("Warning: lines are a straight sequence");
  23256. v_trans_x = - v_prev_y;
  23257. v_trans_y = v_prev_x;
  23258. shrink_by = Math.sqrt( v_prev_lensq );
  23259. } else {
  23260. // console.log("Warning: lines are a straight spike");
  23261. v_trans_x = v_prev_x;
  23262. v_trans_y = v_prev_y;
  23263. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  23264. }
  23265. }
  23266. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  23267. }
  23268. const contourMovements = [];
  23269. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23270. if ( j === il ) j = 0;
  23271. if ( k === il ) k = 0;
  23272. // (j)---(i)---(k)
  23273. // console.log('i,j,k', i, j , k)
  23274. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  23275. }
  23276. const holesMovements = [];
  23277. let oneHoleMovements, verticesMovements = contourMovements.concat();
  23278. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23279. const ahole = holes[ h ];
  23280. oneHoleMovements = [];
  23281. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23282. if ( j === il ) j = 0;
  23283. if ( k === il ) k = 0;
  23284. // (j)---(i)---(k)
  23285. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  23286. }
  23287. holesMovements.push( oneHoleMovements );
  23288. verticesMovements = verticesMovements.concat( oneHoleMovements );
  23289. }
  23290. // Loop bevelSegments, 1 for the front, 1 for the back
  23291. for ( let b = 0; b < bevelSegments; b ++ ) {
  23292. //for ( b = bevelSegments; b > 0; b -- ) {
  23293. const t = b / bevelSegments;
  23294. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23295. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23296. // contract shape
  23297. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23298. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23299. v( vert.x, vert.y, - z );
  23300. }
  23301. // expand holes
  23302. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23303. const ahole = holes[ h ];
  23304. oneHoleMovements = holesMovements[ h ];
  23305. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23306. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23307. v( vert.x, vert.y, - z );
  23308. }
  23309. }
  23310. }
  23311. const bs = bevelSize + bevelOffset;
  23312. // Back facing vertices
  23313. for ( let i = 0; i < vlen; i ++ ) {
  23314. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23315. if ( ! extrudeByPath ) {
  23316. v( vert.x, vert.y, 0 );
  23317. } else {
  23318. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  23319. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  23320. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  23321. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  23322. v( position2.x, position2.y, position2.z );
  23323. }
  23324. }
  23325. // Add stepped vertices...
  23326. // Including front facing vertices
  23327. for ( let s = 1; s <= steps; s ++ ) {
  23328. for ( let i = 0; i < vlen; i ++ ) {
  23329. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23330. if ( ! extrudeByPath ) {
  23331. v( vert.x, vert.y, depth / steps * s );
  23332. } else {
  23333. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  23334. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  23335. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  23336. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  23337. v( position2.x, position2.y, position2.z );
  23338. }
  23339. }
  23340. }
  23341. // Add bevel segments planes
  23342. //for ( b = 1; b <= bevelSegments; b ++ ) {
  23343. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  23344. const t = b / bevelSegments;
  23345. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23346. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23347. // contract shape
  23348. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23349. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23350. v( vert.x, vert.y, depth + z );
  23351. }
  23352. // expand holes
  23353. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23354. const ahole = holes[ h ];
  23355. oneHoleMovements = holesMovements[ h ];
  23356. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23357. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23358. if ( ! extrudeByPath ) {
  23359. v( vert.x, vert.y, depth + z );
  23360. } else {
  23361. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  23362. }
  23363. }
  23364. }
  23365. }
  23366. /* Faces */
  23367. // Top and bottom faces
  23368. buildLidFaces();
  23369. // Sides faces
  23370. buildSideFaces();
  23371. ///// Internal functions
  23372. function buildLidFaces() {
  23373. const start = verticesArray.length / 3;
  23374. if ( bevelEnabled ) {
  23375. let layer = 0; // steps + 1
  23376. let offset = vlen * layer;
  23377. // Bottom faces
  23378. for ( let i = 0; i < flen; i ++ ) {
  23379. const face = faces[ i ];
  23380. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  23381. }
  23382. layer = steps + bevelSegments * 2;
  23383. offset = vlen * layer;
  23384. // Top faces
  23385. for ( let i = 0; i < flen; i ++ ) {
  23386. const face = faces[ i ];
  23387. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23388. }
  23389. } else {
  23390. // Bottom faces
  23391. for ( let i = 0; i < flen; i ++ ) {
  23392. const face = faces[ i ];
  23393. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23394. }
  23395. // Top faces
  23396. for ( let i = 0; i < flen; i ++ ) {
  23397. const face = faces[ i ];
  23398. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23399. }
  23400. }
  23401. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23402. }
  23403. // Create faces for the z-sides of the shape
  23404. function buildSideFaces() {
  23405. const start = verticesArray.length / 3;
  23406. let layeroffset = 0;
  23407. sidewalls( contour, layeroffset );
  23408. layeroffset += contour.length;
  23409. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23410. const ahole = holes[ h ];
  23411. sidewalls( ahole, layeroffset );
  23412. //, true
  23413. layeroffset += ahole.length;
  23414. }
  23415. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23416. }
  23417. function sidewalls( contour, layeroffset ) {
  23418. let i = contour.length;
  23419. while ( -- i >= 0 ) {
  23420. const j = i;
  23421. let k = i - 1;
  23422. if ( k < 0 ) k = contour.length - 1;
  23423. //console.log('b', i,j, i-1, k,vertices.length);
  23424. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  23425. const slen1 = vlen * s;
  23426. const slen2 = vlen * ( s + 1 );
  23427. const a = layeroffset + j + slen1,
  23428. b = layeroffset + k + slen1,
  23429. c = layeroffset + k + slen2,
  23430. d = layeroffset + j + slen2;
  23431. f4( a, b, c, d );
  23432. }
  23433. }
  23434. }
  23435. function v( x, y, z ) {
  23436. placeholder.push( x );
  23437. placeholder.push( y );
  23438. placeholder.push( z );
  23439. }
  23440. function f3( a, b, c ) {
  23441. addVertex( a );
  23442. addVertex( b );
  23443. addVertex( c );
  23444. const nextIndex = verticesArray.length / 3;
  23445. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23446. addUV( uvs[ 0 ] );
  23447. addUV( uvs[ 1 ] );
  23448. addUV( uvs[ 2 ] );
  23449. }
  23450. function f4( a, b, c, d ) {
  23451. addVertex( a );
  23452. addVertex( b );
  23453. addVertex( d );
  23454. addVertex( b );
  23455. addVertex( c );
  23456. addVertex( d );
  23457. const nextIndex = verticesArray.length / 3;
  23458. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23459. addUV( uvs[ 0 ] );
  23460. addUV( uvs[ 1 ] );
  23461. addUV( uvs[ 3 ] );
  23462. addUV( uvs[ 1 ] );
  23463. addUV( uvs[ 2 ] );
  23464. addUV( uvs[ 3 ] );
  23465. }
  23466. function addVertex( index ) {
  23467. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23468. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23469. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23470. }
  23471. function addUV( vector2 ) {
  23472. uvArray.push( vector2.x );
  23473. uvArray.push( vector2.y );
  23474. }
  23475. }
  23476. }
  23477. copy( source ) {
  23478. super.copy( source );
  23479. this.parameters = Object.assign( {}, source.parameters );
  23480. return this;
  23481. }
  23482. toJSON() {
  23483. const data = super.toJSON();
  23484. const shapes = this.parameters.shapes;
  23485. const options = this.parameters.options;
  23486. return toJSON$1( shapes, options, data );
  23487. }
  23488. static fromJSON( data, shapes ) {
  23489. const geometryShapes = [];
  23490. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23491. const shape = shapes[ data.shapes[ j ] ];
  23492. geometryShapes.push( shape );
  23493. }
  23494. const extrudePath = data.options.extrudePath;
  23495. if ( extrudePath !== undefined ) {
  23496. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23497. }
  23498. return new ExtrudeGeometry( geometryShapes, data.options );
  23499. }
  23500. }
  23501. const WorldUVGenerator = {
  23502. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23503. const a_x = vertices[ indexA * 3 ];
  23504. const a_y = vertices[ indexA * 3 + 1 ];
  23505. const b_x = vertices[ indexB * 3 ];
  23506. const b_y = vertices[ indexB * 3 + 1 ];
  23507. const c_x = vertices[ indexC * 3 ];
  23508. const c_y = vertices[ indexC * 3 + 1 ];
  23509. return [
  23510. new Vector2( a_x, a_y ),
  23511. new Vector2( b_x, b_y ),
  23512. new Vector2( c_x, c_y )
  23513. ];
  23514. },
  23515. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23516. const a_x = vertices[ indexA * 3 ];
  23517. const a_y = vertices[ indexA * 3 + 1 ];
  23518. const a_z = vertices[ indexA * 3 + 2 ];
  23519. const b_x = vertices[ indexB * 3 ];
  23520. const b_y = vertices[ indexB * 3 + 1 ];
  23521. const b_z = vertices[ indexB * 3 + 2 ];
  23522. const c_x = vertices[ indexC * 3 ];
  23523. const c_y = vertices[ indexC * 3 + 1 ];
  23524. const c_z = vertices[ indexC * 3 + 2 ];
  23525. const d_x = vertices[ indexD * 3 ];
  23526. const d_y = vertices[ indexD * 3 + 1 ];
  23527. const d_z = vertices[ indexD * 3 + 2 ];
  23528. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  23529. return [
  23530. new Vector2( a_x, 1 - a_z ),
  23531. new Vector2( b_x, 1 - b_z ),
  23532. new Vector2( c_x, 1 - c_z ),
  23533. new Vector2( d_x, 1 - d_z )
  23534. ];
  23535. } else {
  23536. return [
  23537. new Vector2( a_y, 1 - a_z ),
  23538. new Vector2( b_y, 1 - b_z ),
  23539. new Vector2( c_y, 1 - c_z ),
  23540. new Vector2( d_y, 1 - d_z )
  23541. ];
  23542. }
  23543. }
  23544. };
  23545. function toJSON$1( shapes, options, data ) {
  23546. data.shapes = [];
  23547. if ( Array.isArray( shapes ) ) {
  23548. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23549. const shape = shapes[ i ];
  23550. data.shapes.push( shape.uuid );
  23551. }
  23552. } else {
  23553. data.shapes.push( shapes.uuid );
  23554. }
  23555. data.options = Object.assign( {}, options );
  23556. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  23557. return data;
  23558. }
  23559. class IcosahedronGeometry extends PolyhedronGeometry {
  23560. constructor( radius = 1, detail = 0 ) {
  23561. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23562. const vertices = [
  23563. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23564. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23565. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23566. ];
  23567. const indices = [
  23568. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23569. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23570. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23571. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23572. ];
  23573. super( vertices, indices, radius, detail );
  23574. this.type = 'IcosahedronGeometry';
  23575. this.parameters = {
  23576. radius: radius,
  23577. detail: detail
  23578. };
  23579. }
  23580. static fromJSON( data ) {
  23581. return new IcosahedronGeometry( data.radius, data.detail );
  23582. }
  23583. }
  23584. class OctahedronGeometry extends PolyhedronGeometry {
  23585. constructor( radius = 1, detail = 0 ) {
  23586. const vertices = [
  23587. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23588. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23589. ];
  23590. const indices = [
  23591. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23592. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23593. 1, 3, 4, 1, 4, 2
  23594. ];
  23595. super( vertices, indices, radius, detail );
  23596. this.type = 'OctahedronGeometry';
  23597. this.parameters = {
  23598. radius: radius,
  23599. detail: detail
  23600. };
  23601. }
  23602. static fromJSON( data ) {
  23603. return new OctahedronGeometry( data.radius, data.detail );
  23604. }
  23605. }
  23606. class RingGeometry extends BufferGeometry {
  23607. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23608. super();
  23609. this.type = 'RingGeometry';
  23610. this.parameters = {
  23611. innerRadius: innerRadius,
  23612. outerRadius: outerRadius,
  23613. thetaSegments: thetaSegments,
  23614. phiSegments: phiSegments,
  23615. thetaStart: thetaStart,
  23616. thetaLength: thetaLength
  23617. };
  23618. thetaSegments = Math.max( 3, thetaSegments );
  23619. phiSegments = Math.max( 1, phiSegments );
  23620. // buffers
  23621. const indices = [];
  23622. const vertices = [];
  23623. const normals = [];
  23624. const uvs = [];
  23625. // some helper variables
  23626. let radius = innerRadius;
  23627. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23628. const vertex = new Vector3();
  23629. const uv = new Vector2();
  23630. // generate vertices, normals and uvs
  23631. for ( let j = 0; j <= phiSegments; j ++ ) {
  23632. for ( let i = 0; i <= thetaSegments; i ++ ) {
  23633. // values are generate from the inside of the ring to the outside
  23634. const segment = thetaStart + i / thetaSegments * thetaLength;
  23635. // vertex
  23636. vertex.x = radius * Math.cos( segment );
  23637. vertex.y = radius * Math.sin( segment );
  23638. vertices.push( vertex.x, vertex.y, vertex.z );
  23639. // normal
  23640. normals.push( 0, 0, 1 );
  23641. // uv
  23642. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23643. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23644. uvs.push( uv.x, uv.y );
  23645. }
  23646. // increase the radius for next row of vertices
  23647. radius += radiusStep;
  23648. }
  23649. // indices
  23650. for ( let j = 0; j < phiSegments; j ++ ) {
  23651. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  23652. for ( let i = 0; i < thetaSegments; i ++ ) {
  23653. const segment = i + thetaSegmentLevel;
  23654. const a = segment;
  23655. const b = segment + thetaSegments + 1;
  23656. const c = segment + thetaSegments + 2;
  23657. const d = segment + 1;
  23658. // faces
  23659. indices.push( a, b, d );
  23660. indices.push( b, c, d );
  23661. }
  23662. }
  23663. // build geometry
  23664. this.setIndex( indices );
  23665. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23666. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23667. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23668. }
  23669. copy( source ) {
  23670. super.copy( source );
  23671. this.parameters = Object.assign( {}, source.parameters );
  23672. return this;
  23673. }
  23674. static fromJSON( data ) {
  23675. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  23676. }
  23677. }
  23678. class ShapeGeometry extends BufferGeometry {
  23679. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  23680. super();
  23681. this.type = 'ShapeGeometry';
  23682. this.parameters = {
  23683. shapes: shapes,
  23684. curveSegments: curveSegments
  23685. };
  23686. // buffers
  23687. const indices = [];
  23688. const vertices = [];
  23689. const normals = [];
  23690. const uvs = [];
  23691. // helper variables
  23692. let groupStart = 0;
  23693. let groupCount = 0;
  23694. // allow single and array values for "shapes" parameter
  23695. if ( Array.isArray( shapes ) === false ) {
  23696. addShape( shapes );
  23697. } else {
  23698. for ( let i = 0; i < shapes.length; i ++ ) {
  23699. addShape( shapes[ i ] );
  23700. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23701. groupStart += groupCount;
  23702. groupCount = 0;
  23703. }
  23704. }
  23705. // build geometry
  23706. this.setIndex( indices );
  23707. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23708. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23709. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23710. // helper functions
  23711. function addShape( shape ) {
  23712. const indexOffset = vertices.length / 3;
  23713. const points = shape.extractPoints( curveSegments );
  23714. let shapeVertices = points.shape;
  23715. const shapeHoles = points.holes;
  23716. // check direction of vertices
  23717. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23718. shapeVertices = shapeVertices.reverse();
  23719. }
  23720. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23721. const shapeHole = shapeHoles[ i ];
  23722. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23723. shapeHoles[ i ] = shapeHole.reverse();
  23724. }
  23725. }
  23726. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23727. // join vertices of inner and outer paths to a single array
  23728. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23729. const shapeHole = shapeHoles[ i ];
  23730. shapeVertices = shapeVertices.concat( shapeHole );
  23731. }
  23732. // vertices, normals, uvs
  23733. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23734. const vertex = shapeVertices[ i ];
  23735. vertices.push( vertex.x, vertex.y, 0 );
  23736. normals.push( 0, 0, 1 );
  23737. uvs.push( vertex.x, vertex.y ); // world uvs
  23738. }
  23739. // indices
  23740. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  23741. const face = faces[ i ];
  23742. const a = face[ 0 ] + indexOffset;
  23743. const b = face[ 1 ] + indexOffset;
  23744. const c = face[ 2 ] + indexOffset;
  23745. indices.push( a, b, c );
  23746. groupCount += 3;
  23747. }
  23748. }
  23749. }
  23750. copy( source ) {
  23751. super.copy( source );
  23752. this.parameters = Object.assign( {}, source.parameters );
  23753. return this;
  23754. }
  23755. toJSON() {
  23756. const data = super.toJSON();
  23757. const shapes = this.parameters.shapes;
  23758. return toJSON( shapes, data );
  23759. }
  23760. static fromJSON( data, shapes ) {
  23761. const geometryShapes = [];
  23762. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23763. const shape = shapes[ data.shapes[ j ] ];
  23764. geometryShapes.push( shape );
  23765. }
  23766. return new ShapeGeometry( geometryShapes, data.curveSegments );
  23767. }
  23768. }
  23769. function toJSON( shapes, data ) {
  23770. data.shapes = [];
  23771. if ( Array.isArray( shapes ) ) {
  23772. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23773. const shape = shapes[ i ];
  23774. data.shapes.push( shape.uuid );
  23775. }
  23776. } else {
  23777. data.shapes.push( shapes.uuid );
  23778. }
  23779. return data;
  23780. }
  23781. class SphereGeometry extends BufferGeometry {
  23782. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  23783. super();
  23784. this.type = 'SphereGeometry';
  23785. this.parameters = {
  23786. radius: radius,
  23787. widthSegments: widthSegments,
  23788. heightSegments: heightSegments,
  23789. phiStart: phiStart,
  23790. phiLength: phiLength,
  23791. thetaStart: thetaStart,
  23792. thetaLength: thetaLength
  23793. };
  23794. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  23795. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  23796. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  23797. let index = 0;
  23798. const grid = [];
  23799. const vertex = new Vector3();
  23800. const normal = new Vector3();
  23801. // buffers
  23802. const indices = [];
  23803. const vertices = [];
  23804. const normals = [];
  23805. const uvs = [];
  23806. // generate vertices, normals and uvs
  23807. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  23808. const verticesRow = [];
  23809. const v = iy / heightSegments;
  23810. // special case for the poles
  23811. let uOffset = 0;
  23812. if ( iy === 0 && thetaStart === 0 ) {
  23813. uOffset = 0.5 / widthSegments;
  23814. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  23815. uOffset = - 0.5 / widthSegments;
  23816. }
  23817. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  23818. const u = ix / widthSegments;
  23819. // vertex
  23820. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23821. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  23822. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23823. vertices.push( vertex.x, vertex.y, vertex.z );
  23824. // normal
  23825. normal.copy( vertex ).normalize();
  23826. normals.push( normal.x, normal.y, normal.z );
  23827. // uv
  23828. uvs.push( u + uOffset, 1 - v );
  23829. verticesRow.push( index ++ );
  23830. }
  23831. grid.push( verticesRow );
  23832. }
  23833. // indices
  23834. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  23835. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  23836. const a = grid[ iy ][ ix + 1 ];
  23837. const b = grid[ iy ][ ix ];
  23838. const c = grid[ iy + 1 ][ ix ];
  23839. const d = grid[ iy + 1 ][ ix + 1 ];
  23840. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  23841. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  23842. }
  23843. }
  23844. // build geometry
  23845. this.setIndex( indices );
  23846. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23847. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23848. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23849. }
  23850. copy( source ) {
  23851. super.copy( source );
  23852. this.parameters = Object.assign( {}, source.parameters );
  23853. return this;
  23854. }
  23855. static fromJSON( data ) {
  23856. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  23857. }
  23858. }
  23859. class TetrahedronGeometry extends PolyhedronGeometry {
  23860. constructor( radius = 1, detail = 0 ) {
  23861. const vertices = [
  23862. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23863. ];
  23864. const indices = [
  23865. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23866. ];
  23867. super( vertices, indices, radius, detail );
  23868. this.type = 'TetrahedronGeometry';
  23869. this.parameters = {
  23870. radius: radius,
  23871. detail: detail
  23872. };
  23873. }
  23874. static fromJSON( data ) {
  23875. return new TetrahedronGeometry( data.radius, data.detail );
  23876. }
  23877. }
  23878. class TorusGeometry extends BufferGeometry {
  23879. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  23880. super();
  23881. this.type = 'TorusGeometry';
  23882. this.parameters = {
  23883. radius: radius,
  23884. tube: tube,
  23885. radialSegments: radialSegments,
  23886. tubularSegments: tubularSegments,
  23887. arc: arc
  23888. };
  23889. radialSegments = Math.floor( radialSegments );
  23890. tubularSegments = Math.floor( tubularSegments );
  23891. // buffers
  23892. const indices = [];
  23893. const vertices = [];
  23894. const normals = [];
  23895. const uvs = [];
  23896. // helper variables
  23897. const center = new Vector3();
  23898. const vertex = new Vector3();
  23899. const normal = new Vector3();
  23900. // generate vertices, normals and uvs
  23901. for ( let j = 0; j <= radialSegments; j ++ ) {
  23902. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23903. const u = i / tubularSegments * arc;
  23904. const v = j / radialSegments * Math.PI * 2;
  23905. // vertex
  23906. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23907. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23908. vertex.z = tube * Math.sin( v );
  23909. vertices.push( vertex.x, vertex.y, vertex.z );
  23910. // normal
  23911. center.x = radius * Math.cos( u );
  23912. center.y = radius * Math.sin( u );
  23913. normal.subVectors( vertex, center ).normalize();
  23914. normals.push( normal.x, normal.y, normal.z );
  23915. // uv
  23916. uvs.push( i / tubularSegments );
  23917. uvs.push( j / radialSegments );
  23918. }
  23919. }
  23920. // generate indices
  23921. for ( let j = 1; j <= radialSegments; j ++ ) {
  23922. for ( let i = 1; i <= tubularSegments; i ++ ) {
  23923. // indices
  23924. const a = ( tubularSegments + 1 ) * j + i - 1;
  23925. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23926. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23927. const d = ( tubularSegments + 1 ) * j + i;
  23928. // faces
  23929. indices.push( a, b, d );
  23930. indices.push( b, c, d );
  23931. }
  23932. }
  23933. // build geometry
  23934. this.setIndex( indices );
  23935. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23936. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23937. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23938. }
  23939. copy( source ) {
  23940. super.copy( source );
  23941. this.parameters = Object.assign( {}, source.parameters );
  23942. return this;
  23943. }
  23944. static fromJSON( data ) {
  23945. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  23946. }
  23947. }
  23948. class TorusKnotGeometry extends BufferGeometry {
  23949. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  23950. super();
  23951. this.type = 'TorusKnotGeometry';
  23952. this.parameters = {
  23953. radius: radius,
  23954. tube: tube,
  23955. tubularSegments: tubularSegments,
  23956. radialSegments: radialSegments,
  23957. p: p,
  23958. q: q
  23959. };
  23960. tubularSegments = Math.floor( tubularSegments );
  23961. radialSegments = Math.floor( radialSegments );
  23962. // buffers
  23963. const indices = [];
  23964. const vertices = [];
  23965. const normals = [];
  23966. const uvs = [];
  23967. // helper variables
  23968. const vertex = new Vector3();
  23969. const normal = new Vector3();
  23970. const P1 = new Vector3();
  23971. const P2 = new Vector3();
  23972. const B = new Vector3();
  23973. const T = new Vector3();
  23974. const N = new Vector3();
  23975. // generate vertices, normals and uvs
  23976. for ( let i = 0; i <= tubularSegments; ++ i ) {
  23977. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  23978. const u = i / tubularSegments * p * Math.PI * 2;
  23979. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23980. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23981. calculatePositionOnCurve( u, p, q, radius, P1 );
  23982. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23983. // calculate orthonormal basis
  23984. T.subVectors( P2, P1 );
  23985. N.addVectors( P2, P1 );
  23986. B.crossVectors( T, N );
  23987. N.crossVectors( B, T );
  23988. // normalize B, N. T can be ignored, we don't use it
  23989. B.normalize();
  23990. N.normalize();
  23991. for ( let j = 0; j <= radialSegments; ++ j ) {
  23992. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23993. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23994. const v = j / radialSegments * Math.PI * 2;
  23995. const cx = - tube * Math.cos( v );
  23996. const cy = tube * Math.sin( v );
  23997. // now calculate the final vertex position.
  23998. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  23999. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  24000. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  24001. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  24002. vertices.push( vertex.x, vertex.y, vertex.z );
  24003. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  24004. normal.subVectors( vertex, P1 ).normalize();
  24005. normals.push( normal.x, normal.y, normal.z );
  24006. // uv
  24007. uvs.push( i / tubularSegments );
  24008. uvs.push( j / radialSegments );
  24009. }
  24010. }
  24011. // generate indices
  24012. for ( let j = 1; j <= tubularSegments; j ++ ) {
  24013. for ( let i = 1; i <= radialSegments; i ++ ) {
  24014. // indices
  24015. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  24016. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  24017. const c = ( radialSegments + 1 ) * j + i;
  24018. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  24019. // faces
  24020. indices.push( a, b, d );
  24021. indices.push( b, c, d );
  24022. }
  24023. }
  24024. // build geometry
  24025. this.setIndex( indices );
  24026. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24027. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24028. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24029. // this function calculates the current position on the torus curve
  24030. function calculatePositionOnCurve( u, p, q, radius, position ) {
  24031. const cu = Math.cos( u );
  24032. const su = Math.sin( u );
  24033. const quOverP = q / p * u;
  24034. const cs = Math.cos( quOverP );
  24035. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  24036. position.y = radius * ( 2 + cs ) * su * 0.5;
  24037. position.z = radius * Math.sin( quOverP ) * 0.5;
  24038. }
  24039. }
  24040. copy( source ) {
  24041. super.copy( source );
  24042. this.parameters = Object.assign( {}, source.parameters );
  24043. return this;
  24044. }
  24045. static fromJSON( data ) {
  24046. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  24047. }
  24048. }
  24049. class TubeGeometry extends BufferGeometry {
  24050. 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 ) {
  24051. super();
  24052. this.type = 'TubeGeometry';
  24053. this.parameters = {
  24054. path: path,
  24055. tubularSegments: tubularSegments,
  24056. radius: radius,
  24057. radialSegments: radialSegments,
  24058. closed: closed
  24059. };
  24060. const frames = path.computeFrenetFrames( tubularSegments, closed );
  24061. // expose internals
  24062. this.tangents = frames.tangents;
  24063. this.normals = frames.normals;
  24064. this.binormals = frames.binormals;
  24065. // helper variables
  24066. const vertex = new Vector3();
  24067. const normal = new Vector3();
  24068. const uv = new Vector2();
  24069. let P = new Vector3();
  24070. // buffer
  24071. const vertices = [];
  24072. const normals = [];
  24073. const uvs = [];
  24074. const indices = [];
  24075. // create buffer data
  24076. generateBufferData();
  24077. // build geometry
  24078. this.setIndex( indices );
  24079. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24080. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  24081. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  24082. // functions
  24083. function generateBufferData() {
  24084. for ( let i = 0; i < tubularSegments; i ++ ) {
  24085. generateSegment( i );
  24086. }
  24087. // if the geometry is not closed, generate the last row of vertices and normals
  24088. // at the regular position on the given path
  24089. //
  24090. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  24091. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  24092. // uvs are generated in a separate function.
  24093. // this makes it easy compute correct values for closed geometries
  24094. generateUVs();
  24095. // finally create faces
  24096. generateIndices();
  24097. }
  24098. function generateSegment( i ) {
  24099. // we use getPointAt to sample evenly distributed points from the given path
  24100. P = path.getPointAt( i / tubularSegments, P );
  24101. // retrieve corresponding normal and binormal
  24102. const N = frames.normals[ i ];
  24103. const B = frames.binormals[ i ];
  24104. // generate normals and vertices for the current segment
  24105. for ( let j = 0; j <= radialSegments; j ++ ) {
  24106. const v = j / radialSegments * Math.PI * 2;
  24107. const sin = Math.sin( v );
  24108. const cos = - Math.cos( v );
  24109. // normal
  24110. normal.x = ( cos * N.x + sin * B.x );
  24111. normal.y = ( cos * N.y + sin * B.y );
  24112. normal.z = ( cos * N.z + sin * B.z );
  24113. normal.normalize();
  24114. normals.push( normal.x, normal.y, normal.z );
  24115. // vertex
  24116. vertex.x = P.x + radius * normal.x;
  24117. vertex.y = P.y + radius * normal.y;
  24118. vertex.z = P.z + radius * normal.z;
  24119. vertices.push( vertex.x, vertex.y, vertex.z );
  24120. }
  24121. }
  24122. function generateIndices() {
  24123. for ( let j = 1; j <= tubularSegments; j ++ ) {
  24124. for ( let i = 1; i <= radialSegments; i ++ ) {
  24125. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  24126. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  24127. const c = ( radialSegments + 1 ) * j + i;
  24128. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  24129. // faces
  24130. indices.push( a, b, d );
  24131. indices.push( b, c, d );
  24132. }
  24133. }
  24134. }
  24135. function generateUVs() {
  24136. for ( let i = 0; i <= tubularSegments; i ++ ) {
  24137. for ( let j = 0; j <= radialSegments; j ++ ) {
  24138. uv.x = i / tubularSegments;
  24139. uv.y = j / radialSegments;
  24140. uvs.push( uv.x, uv.y );
  24141. }
  24142. }
  24143. }
  24144. }
  24145. copy( source ) {
  24146. super.copy( source );
  24147. this.parameters = Object.assign( {}, source.parameters );
  24148. return this;
  24149. }
  24150. toJSON() {
  24151. const data = super.toJSON();
  24152. data.path = this.parameters.path.toJSON();
  24153. return data;
  24154. }
  24155. static fromJSON( data ) {
  24156. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24157. // User defined curves or instances of CurvePath will not be deserialized.
  24158. return new TubeGeometry(
  24159. new Curves[ data.path.type ]().fromJSON( data.path ),
  24160. data.tubularSegments,
  24161. data.radius,
  24162. data.radialSegments,
  24163. data.closed
  24164. );
  24165. }
  24166. }
  24167. class WireframeGeometry extends BufferGeometry {
  24168. constructor( geometry = null ) {
  24169. super();
  24170. this.type = 'WireframeGeometry';
  24171. this.parameters = {
  24172. geometry: geometry
  24173. };
  24174. if ( geometry !== null ) {
  24175. // buffer
  24176. const vertices = [];
  24177. const edges = new Set();
  24178. // helper variables
  24179. const start = new Vector3();
  24180. const end = new Vector3();
  24181. if ( geometry.index !== null ) {
  24182. // indexed BufferGeometry
  24183. const position = geometry.attributes.position;
  24184. const indices = geometry.index;
  24185. let groups = geometry.groups;
  24186. if ( groups.length === 0 ) {
  24187. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  24188. }
  24189. // create a data structure that contains all edges without duplicates
  24190. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  24191. const group = groups[ o ];
  24192. const groupStart = group.start;
  24193. const groupCount = group.count;
  24194. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  24195. for ( let j = 0; j < 3; j ++ ) {
  24196. const index1 = indices.getX( i + j );
  24197. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  24198. start.fromBufferAttribute( position, index1 );
  24199. end.fromBufferAttribute( position, index2 );
  24200. if ( isUniqueEdge( start, end, edges ) === true ) {
  24201. vertices.push( start.x, start.y, start.z );
  24202. vertices.push( end.x, end.y, end.z );
  24203. }
  24204. }
  24205. }
  24206. }
  24207. } else {
  24208. // non-indexed BufferGeometry
  24209. const position = geometry.attributes.position;
  24210. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  24211. for ( let j = 0; j < 3; j ++ ) {
  24212. // three edges per triangle, an edge is represented as (index1, index2)
  24213. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  24214. const index1 = 3 * i + j;
  24215. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  24216. start.fromBufferAttribute( position, index1 );
  24217. end.fromBufferAttribute( position, index2 );
  24218. if ( isUniqueEdge( start, end, edges ) === true ) {
  24219. vertices.push( start.x, start.y, start.z );
  24220. vertices.push( end.x, end.y, end.z );
  24221. }
  24222. }
  24223. }
  24224. }
  24225. // build geometry
  24226. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24227. }
  24228. }
  24229. copy( source ) {
  24230. super.copy( source );
  24231. this.parameters = Object.assign( {}, source.parameters );
  24232. return this;
  24233. }
  24234. }
  24235. function isUniqueEdge( start, end, edges ) {
  24236. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  24237. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  24238. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  24239. return false;
  24240. } else {
  24241. edges.add( hash1 );
  24242. edges.add( hash2 );
  24243. return true;
  24244. }
  24245. }
  24246. var Geometries = /*#__PURE__*/Object.freeze({
  24247. __proto__: null,
  24248. BoxGeometry: BoxGeometry,
  24249. CapsuleGeometry: CapsuleGeometry,
  24250. CircleGeometry: CircleGeometry,
  24251. ConeGeometry: ConeGeometry,
  24252. CylinderGeometry: CylinderGeometry,
  24253. DodecahedronGeometry: DodecahedronGeometry,
  24254. EdgesGeometry: EdgesGeometry,
  24255. ExtrudeGeometry: ExtrudeGeometry,
  24256. IcosahedronGeometry: IcosahedronGeometry,
  24257. LatheGeometry: LatheGeometry,
  24258. OctahedronGeometry: OctahedronGeometry,
  24259. PlaneGeometry: PlaneGeometry,
  24260. PolyhedronGeometry: PolyhedronGeometry,
  24261. RingGeometry: RingGeometry,
  24262. ShapeGeometry: ShapeGeometry,
  24263. SphereGeometry: SphereGeometry,
  24264. TetrahedronGeometry: TetrahedronGeometry,
  24265. TorusGeometry: TorusGeometry,
  24266. TorusKnotGeometry: TorusKnotGeometry,
  24267. TubeGeometry: TubeGeometry,
  24268. WireframeGeometry: WireframeGeometry
  24269. });
  24270. class ShadowMaterial extends Material {
  24271. constructor( parameters ) {
  24272. super();
  24273. this.isShadowMaterial = true;
  24274. this.type = 'ShadowMaterial';
  24275. this.color = new Color( 0x000000 );
  24276. this.transparent = true;
  24277. this.fog = true;
  24278. this.setValues( parameters );
  24279. }
  24280. copy( source ) {
  24281. super.copy( source );
  24282. this.color.copy( source.color );
  24283. this.fog = source.fog;
  24284. return this;
  24285. }
  24286. }
  24287. class RawShaderMaterial extends ShaderMaterial {
  24288. constructor( parameters ) {
  24289. super( parameters );
  24290. this.isRawShaderMaterial = true;
  24291. this.type = 'RawShaderMaterial';
  24292. }
  24293. }
  24294. class MeshStandardMaterial extends Material {
  24295. constructor( parameters ) {
  24296. super();
  24297. this.isMeshStandardMaterial = true;
  24298. this.defines = { 'STANDARD': '' };
  24299. this.type = 'MeshStandardMaterial';
  24300. this.color = new Color( 0xffffff ); // diffuse
  24301. this.roughness = 1.0;
  24302. this.metalness = 0.0;
  24303. this.map = null;
  24304. this.lightMap = null;
  24305. this.lightMapIntensity = 1.0;
  24306. this.aoMap = null;
  24307. this.aoMapIntensity = 1.0;
  24308. this.emissive = new Color( 0x000000 );
  24309. this.emissiveIntensity = 1.0;
  24310. this.emissiveMap = null;
  24311. this.bumpMap = null;
  24312. this.bumpScale = 1;
  24313. this.normalMap = null;
  24314. this.normalMapType = TangentSpaceNormalMap;
  24315. this.normalScale = new Vector2( 1, 1 );
  24316. this.displacementMap = null;
  24317. this.displacementScale = 1;
  24318. this.displacementBias = 0;
  24319. this.roughnessMap = null;
  24320. this.metalnessMap = null;
  24321. this.alphaMap = null;
  24322. this.envMap = null;
  24323. this.envMapRotation = new Euler();
  24324. this.envMapIntensity = 1.0;
  24325. this.wireframe = false;
  24326. this.wireframeLinewidth = 1;
  24327. this.wireframeLinecap = 'round';
  24328. this.wireframeLinejoin = 'round';
  24329. this.flatShading = false;
  24330. this.fog = true;
  24331. this.setValues( parameters );
  24332. }
  24333. copy( source ) {
  24334. super.copy( source );
  24335. this.defines = { 'STANDARD': '' };
  24336. this.color.copy( source.color );
  24337. this.roughness = source.roughness;
  24338. this.metalness = source.metalness;
  24339. this.map = source.map;
  24340. this.lightMap = source.lightMap;
  24341. this.lightMapIntensity = source.lightMapIntensity;
  24342. this.aoMap = source.aoMap;
  24343. this.aoMapIntensity = source.aoMapIntensity;
  24344. this.emissive.copy( source.emissive );
  24345. this.emissiveMap = source.emissiveMap;
  24346. this.emissiveIntensity = source.emissiveIntensity;
  24347. this.bumpMap = source.bumpMap;
  24348. this.bumpScale = source.bumpScale;
  24349. this.normalMap = source.normalMap;
  24350. this.normalMapType = source.normalMapType;
  24351. this.normalScale.copy( source.normalScale );
  24352. this.displacementMap = source.displacementMap;
  24353. this.displacementScale = source.displacementScale;
  24354. this.displacementBias = source.displacementBias;
  24355. this.roughnessMap = source.roughnessMap;
  24356. this.metalnessMap = source.metalnessMap;
  24357. this.alphaMap = source.alphaMap;
  24358. this.envMap = source.envMap;
  24359. this.envMapRotation.copy( source.envMapRotation );
  24360. this.envMapIntensity = source.envMapIntensity;
  24361. this.wireframe = source.wireframe;
  24362. this.wireframeLinewidth = source.wireframeLinewidth;
  24363. this.wireframeLinecap = source.wireframeLinecap;
  24364. this.wireframeLinejoin = source.wireframeLinejoin;
  24365. this.flatShading = source.flatShading;
  24366. this.fog = source.fog;
  24367. return this;
  24368. }
  24369. }
  24370. class MeshPhysicalMaterial extends MeshStandardMaterial {
  24371. constructor( parameters ) {
  24372. super();
  24373. this.isMeshPhysicalMaterial = true;
  24374. this.defines = {
  24375. 'STANDARD': '',
  24376. 'PHYSICAL': ''
  24377. };
  24378. this.type = 'MeshPhysicalMaterial';
  24379. this.anisotropyRotation = 0;
  24380. this.anisotropyMap = null;
  24381. this.clearcoatMap = null;
  24382. this.clearcoatRoughness = 0.0;
  24383. this.clearcoatRoughnessMap = null;
  24384. this.clearcoatNormalScale = new Vector2( 1, 1 );
  24385. this.clearcoatNormalMap = null;
  24386. this.ior = 1.5;
  24387. Object.defineProperty( this, 'reflectivity', {
  24388. get: function () {
  24389. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  24390. },
  24391. set: function ( reflectivity ) {
  24392. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  24393. }
  24394. } );
  24395. this.iridescenceMap = null;
  24396. this.iridescenceIOR = 1.3;
  24397. this.iridescenceThicknessRange = [ 100, 400 ];
  24398. this.iridescenceThicknessMap = null;
  24399. this.sheenColor = new Color( 0x000000 );
  24400. this.sheenColorMap = null;
  24401. this.sheenRoughness = 1.0;
  24402. this.sheenRoughnessMap = null;
  24403. this.transmissionMap = null;
  24404. this.thickness = 0;
  24405. this.thicknessMap = null;
  24406. this.attenuationDistance = Infinity;
  24407. this.attenuationColor = new Color( 1, 1, 1 );
  24408. this.specularIntensity = 1.0;
  24409. this.specularIntensityMap = null;
  24410. this.specularColor = new Color( 1, 1, 1 );
  24411. this.specularColorMap = null;
  24412. this._anisotropy = 0;
  24413. this._clearcoat = 0;
  24414. this._dispersion = 0;
  24415. this._iridescence = 0;
  24416. this._sheen = 0.0;
  24417. this._transmission = 0;
  24418. this.setValues( parameters );
  24419. }
  24420. get anisotropy() {
  24421. return this._anisotropy;
  24422. }
  24423. set anisotropy( value ) {
  24424. if ( this._anisotropy > 0 !== value > 0 ) {
  24425. this.version ++;
  24426. }
  24427. this._anisotropy = value;
  24428. }
  24429. get clearcoat() {
  24430. return this._clearcoat;
  24431. }
  24432. set clearcoat( value ) {
  24433. if ( this._clearcoat > 0 !== value > 0 ) {
  24434. this.version ++;
  24435. }
  24436. this._clearcoat = value;
  24437. }
  24438. get iridescence() {
  24439. return this._iridescence;
  24440. }
  24441. set iridescence( value ) {
  24442. if ( this._iridescence > 0 !== value > 0 ) {
  24443. this.version ++;
  24444. }
  24445. this._iridescence = value;
  24446. }
  24447. get dispersion() {
  24448. return this._dispersion;
  24449. }
  24450. set dispersion( value ) {
  24451. if ( this._dispersion > 0 !== value > 0 ) {
  24452. this.version ++;
  24453. }
  24454. this._dispersion = value;
  24455. }
  24456. get sheen() {
  24457. return this._sheen;
  24458. }
  24459. set sheen( value ) {
  24460. if ( this._sheen > 0 !== value > 0 ) {
  24461. this.version ++;
  24462. }
  24463. this._sheen = value;
  24464. }
  24465. get transmission() {
  24466. return this._transmission;
  24467. }
  24468. set transmission( value ) {
  24469. if ( this._transmission > 0 !== value > 0 ) {
  24470. this.version ++;
  24471. }
  24472. this._transmission = value;
  24473. }
  24474. copy( source ) {
  24475. super.copy( source );
  24476. this.defines = {
  24477. 'STANDARD': '',
  24478. 'PHYSICAL': ''
  24479. };
  24480. this.anisotropy = source.anisotropy;
  24481. this.anisotropyRotation = source.anisotropyRotation;
  24482. this.anisotropyMap = source.anisotropyMap;
  24483. this.clearcoat = source.clearcoat;
  24484. this.clearcoatMap = source.clearcoatMap;
  24485. this.clearcoatRoughness = source.clearcoatRoughness;
  24486. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  24487. this.clearcoatNormalMap = source.clearcoatNormalMap;
  24488. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  24489. this.dispersion = source.dispersion;
  24490. this.ior = source.ior;
  24491. this.iridescence = source.iridescence;
  24492. this.iridescenceMap = source.iridescenceMap;
  24493. this.iridescenceIOR = source.iridescenceIOR;
  24494. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  24495. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  24496. this.sheen = source.sheen;
  24497. this.sheenColor.copy( source.sheenColor );
  24498. this.sheenColorMap = source.sheenColorMap;
  24499. this.sheenRoughness = source.sheenRoughness;
  24500. this.sheenRoughnessMap = source.sheenRoughnessMap;
  24501. this.transmission = source.transmission;
  24502. this.transmissionMap = source.transmissionMap;
  24503. this.thickness = source.thickness;
  24504. this.thicknessMap = source.thicknessMap;
  24505. this.attenuationDistance = source.attenuationDistance;
  24506. this.attenuationColor.copy( source.attenuationColor );
  24507. this.specularIntensity = source.specularIntensity;
  24508. this.specularIntensityMap = source.specularIntensityMap;
  24509. this.specularColor.copy( source.specularColor );
  24510. this.specularColorMap = source.specularColorMap;
  24511. return this;
  24512. }
  24513. }
  24514. class MeshPhongMaterial extends Material {
  24515. constructor( parameters ) {
  24516. super();
  24517. this.isMeshPhongMaterial = true;
  24518. this.type = 'MeshPhongMaterial';
  24519. this.color = new Color( 0xffffff ); // diffuse
  24520. this.specular = new Color( 0x111111 );
  24521. this.shininess = 30;
  24522. this.map = null;
  24523. this.lightMap = null;
  24524. this.lightMapIntensity = 1.0;
  24525. this.aoMap = null;
  24526. this.aoMapIntensity = 1.0;
  24527. this.emissive = new Color( 0x000000 );
  24528. this.emissiveIntensity = 1.0;
  24529. this.emissiveMap = null;
  24530. this.bumpMap = null;
  24531. this.bumpScale = 1;
  24532. this.normalMap = null;
  24533. this.normalMapType = TangentSpaceNormalMap;
  24534. this.normalScale = new Vector2( 1, 1 );
  24535. this.displacementMap = null;
  24536. this.displacementScale = 1;
  24537. this.displacementBias = 0;
  24538. this.specularMap = null;
  24539. this.alphaMap = null;
  24540. this.envMap = null;
  24541. this.envMapRotation = new Euler();
  24542. this.combine = MultiplyOperation;
  24543. this.reflectivity = 1;
  24544. this.refractionRatio = 0.98;
  24545. this.wireframe = false;
  24546. this.wireframeLinewidth = 1;
  24547. this.wireframeLinecap = 'round';
  24548. this.wireframeLinejoin = 'round';
  24549. this.flatShading = false;
  24550. this.fog = true;
  24551. this.setValues( parameters );
  24552. }
  24553. copy( source ) {
  24554. super.copy( source );
  24555. this.color.copy( source.color );
  24556. this.specular.copy( source.specular );
  24557. this.shininess = source.shininess;
  24558. this.map = source.map;
  24559. this.lightMap = source.lightMap;
  24560. this.lightMapIntensity = source.lightMapIntensity;
  24561. this.aoMap = source.aoMap;
  24562. this.aoMapIntensity = source.aoMapIntensity;
  24563. this.emissive.copy( source.emissive );
  24564. this.emissiveMap = source.emissiveMap;
  24565. this.emissiveIntensity = source.emissiveIntensity;
  24566. this.bumpMap = source.bumpMap;
  24567. this.bumpScale = source.bumpScale;
  24568. this.normalMap = source.normalMap;
  24569. this.normalMapType = source.normalMapType;
  24570. this.normalScale.copy( source.normalScale );
  24571. this.displacementMap = source.displacementMap;
  24572. this.displacementScale = source.displacementScale;
  24573. this.displacementBias = source.displacementBias;
  24574. this.specularMap = source.specularMap;
  24575. this.alphaMap = source.alphaMap;
  24576. this.envMap = source.envMap;
  24577. this.envMapRotation.copy( source.envMapRotation );
  24578. this.combine = source.combine;
  24579. this.reflectivity = source.reflectivity;
  24580. this.refractionRatio = source.refractionRatio;
  24581. this.wireframe = source.wireframe;
  24582. this.wireframeLinewidth = source.wireframeLinewidth;
  24583. this.wireframeLinecap = source.wireframeLinecap;
  24584. this.wireframeLinejoin = source.wireframeLinejoin;
  24585. this.flatShading = source.flatShading;
  24586. this.fog = source.fog;
  24587. return this;
  24588. }
  24589. }
  24590. class MeshToonMaterial extends Material {
  24591. constructor( parameters ) {
  24592. super();
  24593. this.isMeshToonMaterial = true;
  24594. this.defines = { 'TOON': '' };
  24595. this.type = 'MeshToonMaterial';
  24596. this.color = new Color( 0xffffff );
  24597. this.map = null;
  24598. this.gradientMap = null;
  24599. this.lightMap = null;
  24600. this.lightMapIntensity = 1.0;
  24601. this.aoMap = null;
  24602. this.aoMapIntensity = 1.0;
  24603. this.emissive = new Color( 0x000000 );
  24604. this.emissiveIntensity = 1.0;
  24605. this.emissiveMap = null;
  24606. this.bumpMap = null;
  24607. this.bumpScale = 1;
  24608. this.normalMap = null;
  24609. this.normalMapType = TangentSpaceNormalMap;
  24610. this.normalScale = new Vector2( 1, 1 );
  24611. this.displacementMap = null;
  24612. this.displacementScale = 1;
  24613. this.displacementBias = 0;
  24614. this.alphaMap = null;
  24615. this.wireframe = false;
  24616. this.wireframeLinewidth = 1;
  24617. this.wireframeLinecap = 'round';
  24618. this.wireframeLinejoin = 'round';
  24619. this.fog = true;
  24620. this.setValues( parameters );
  24621. }
  24622. copy( source ) {
  24623. super.copy( source );
  24624. this.color.copy( source.color );
  24625. this.map = source.map;
  24626. this.gradientMap = source.gradientMap;
  24627. this.lightMap = source.lightMap;
  24628. this.lightMapIntensity = source.lightMapIntensity;
  24629. this.aoMap = source.aoMap;
  24630. this.aoMapIntensity = source.aoMapIntensity;
  24631. this.emissive.copy( source.emissive );
  24632. this.emissiveMap = source.emissiveMap;
  24633. this.emissiveIntensity = source.emissiveIntensity;
  24634. this.bumpMap = source.bumpMap;
  24635. this.bumpScale = source.bumpScale;
  24636. this.normalMap = source.normalMap;
  24637. this.normalMapType = source.normalMapType;
  24638. this.normalScale.copy( source.normalScale );
  24639. this.displacementMap = source.displacementMap;
  24640. this.displacementScale = source.displacementScale;
  24641. this.displacementBias = source.displacementBias;
  24642. this.alphaMap = source.alphaMap;
  24643. this.wireframe = source.wireframe;
  24644. this.wireframeLinewidth = source.wireframeLinewidth;
  24645. this.wireframeLinecap = source.wireframeLinecap;
  24646. this.wireframeLinejoin = source.wireframeLinejoin;
  24647. this.fog = source.fog;
  24648. return this;
  24649. }
  24650. }
  24651. class MeshNormalMaterial extends Material {
  24652. constructor( parameters ) {
  24653. super();
  24654. this.isMeshNormalMaterial = true;
  24655. this.type = 'MeshNormalMaterial';
  24656. this.bumpMap = null;
  24657. this.bumpScale = 1;
  24658. this.normalMap = null;
  24659. this.normalMapType = TangentSpaceNormalMap;
  24660. this.normalScale = new Vector2( 1, 1 );
  24661. this.displacementMap = null;
  24662. this.displacementScale = 1;
  24663. this.displacementBias = 0;
  24664. this.wireframe = false;
  24665. this.wireframeLinewidth = 1;
  24666. this.flatShading = false;
  24667. this.setValues( parameters );
  24668. }
  24669. copy( source ) {
  24670. super.copy( source );
  24671. this.bumpMap = source.bumpMap;
  24672. this.bumpScale = source.bumpScale;
  24673. this.normalMap = source.normalMap;
  24674. this.normalMapType = source.normalMapType;
  24675. this.normalScale.copy( source.normalScale );
  24676. this.displacementMap = source.displacementMap;
  24677. this.displacementScale = source.displacementScale;
  24678. this.displacementBias = source.displacementBias;
  24679. this.wireframe = source.wireframe;
  24680. this.wireframeLinewidth = source.wireframeLinewidth;
  24681. this.flatShading = source.flatShading;
  24682. return this;
  24683. }
  24684. }
  24685. class MeshLambertMaterial extends Material {
  24686. constructor( parameters ) {
  24687. super();
  24688. this.isMeshLambertMaterial = true;
  24689. this.type = 'MeshLambertMaterial';
  24690. this.color = new Color( 0xffffff ); // diffuse
  24691. this.map = null;
  24692. this.lightMap = null;
  24693. this.lightMapIntensity = 1.0;
  24694. this.aoMap = null;
  24695. this.aoMapIntensity = 1.0;
  24696. this.emissive = new Color( 0x000000 );
  24697. this.emissiveIntensity = 1.0;
  24698. this.emissiveMap = null;
  24699. this.bumpMap = null;
  24700. this.bumpScale = 1;
  24701. this.normalMap = null;
  24702. this.normalMapType = TangentSpaceNormalMap;
  24703. this.normalScale = new Vector2( 1, 1 );
  24704. this.displacementMap = null;
  24705. this.displacementScale = 1;
  24706. this.displacementBias = 0;
  24707. this.specularMap = null;
  24708. this.alphaMap = null;
  24709. this.envMap = null;
  24710. this.envMapRotation = new Euler();
  24711. this.combine = MultiplyOperation;
  24712. this.reflectivity = 1;
  24713. this.refractionRatio = 0.98;
  24714. this.wireframe = false;
  24715. this.wireframeLinewidth = 1;
  24716. this.wireframeLinecap = 'round';
  24717. this.wireframeLinejoin = 'round';
  24718. this.flatShading = false;
  24719. this.fog = true;
  24720. this.setValues( parameters );
  24721. }
  24722. copy( source ) {
  24723. super.copy( source );
  24724. this.color.copy( source.color );
  24725. this.map = source.map;
  24726. this.lightMap = source.lightMap;
  24727. this.lightMapIntensity = source.lightMapIntensity;
  24728. this.aoMap = source.aoMap;
  24729. this.aoMapIntensity = source.aoMapIntensity;
  24730. this.emissive.copy( source.emissive );
  24731. this.emissiveMap = source.emissiveMap;
  24732. this.emissiveIntensity = source.emissiveIntensity;
  24733. this.bumpMap = source.bumpMap;
  24734. this.bumpScale = source.bumpScale;
  24735. this.normalMap = source.normalMap;
  24736. this.normalMapType = source.normalMapType;
  24737. this.normalScale.copy( source.normalScale );
  24738. this.displacementMap = source.displacementMap;
  24739. this.displacementScale = source.displacementScale;
  24740. this.displacementBias = source.displacementBias;
  24741. this.specularMap = source.specularMap;
  24742. this.alphaMap = source.alphaMap;
  24743. this.envMap = source.envMap;
  24744. this.envMapRotation.copy( source.envMapRotation );
  24745. this.combine = source.combine;
  24746. this.reflectivity = source.reflectivity;
  24747. this.refractionRatio = source.refractionRatio;
  24748. this.wireframe = source.wireframe;
  24749. this.wireframeLinewidth = source.wireframeLinewidth;
  24750. this.wireframeLinecap = source.wireframeLinecap;
  24751. this.wireframeLinejoin = source.wireframeLinejoin;
  24752. this.flatShading = source.flatShading;
  24753. this.fog = source.fog;
  24754. return this;
  24755. }
  24756. }
  24757. class MeshMatcapMaterial extends Material {
  24758. constructor( parameters ) {
  24759. super();
  24760. this.isMeshMatcapMaterial = true;
  24761. this.defines = { 'MATCAP': '' };
  24762. this.type = 'MeshMatcapMaterial';
  24763. this.color = new Color( 0xffffff ); // diffuse
  24764. this.matcap = null;
  24765. this.map = null;
  24766. this.bumpMap = null;
  24767. this.bumpScale = 1;
  24768. this.normalMap = null;
  24769. this.normalMapType = TangentSpaceNormalMap;
  24770. this.normalScale = new Vector2( 1, 1 );
  24771. this.displacementMap = null;
  24772. this.displacementScale = 1;
  24773. this.displacementBias = 0;
  24774. this.alphaMap = null;
  24775. this.flatShading = false;
  24776. this.fog = true;
  24777. this.setValues( parameters );
  24778. }
  24779. copy( source ) {
  24780. super.copy( source );
  24781. this.defines = { 'MATCAP': '' };
  24782. this.color.copy( source.color );
  24783. this.matcap = source.matcap;
  24784. this.map = source.map;
  24785. this.bumpMap = source.bumpMap;
  24786. this.bumpScale = source.bumpScale;
  24787. this.normalMap = source.normalMap;
  24788. this.normalMapType = source.normalMapType;
  24789. this.normalScale.copy( source.normalScale );
  24790. this.displacementMap = source.displacementMap;
  24791. this.displacementScale = source.displacementScale;
  24792. this.displacementBias = source.displacementBias;
  24793. this.alphaMap = source.alphaMap;
  24794. this.flatShading = source.flatShading;
  24795. this.fog = source.fog;
  24796. return this;
  24797. }
  24798. }
  24799. class LineDashedMaterial extends LineBasicMaterial {
  24800. constructor( parameters ) {
  24801. super();
  24802. this.isLineDashedMaterial = true;
  24803. this.type = 'LineDashedMaterial';
  24804. this.scale = 1;
  24805. this.dashSize = 3;
  24806. this.gapSize = 1;
  24807. this.setValues( parameters );
  24808. }
  24809. copy( source ) {
  24810. super.copy( source );
  24811. this.scale = source.scale;
  24812. this.dashSize = source.dashSize;
  24813. this.gapSize = source.gapSize;
  24814. return this;
  24815. }
  24816. }
  24817. // converts an array to a specific type
  24818. function convertArray( array, type, forceClone ) {
  24819. if ( ! array || // let 'undefined' and 'null' pass
  24820. ! forceClone && array.constructor === type ) return array;
  24821. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24822. return new type( array ); // create typed array
  24823. }
  24824. return Array.prototype.slice.call( array ); // create Array
  24825. }
  24826. function isTypedArray( object ) {
  24827. return ArrayBuffer.isView( object ) &&
  24828. ! ( object instanceof DataView );
  24829. }
  24830. // returns an array by which times and values can be sorted
  24831. function getKeyframeOrder( times ) {
  24832. function compareTime( i, j ) {
  24833. return times[ i ] - times[ j ];
  24834. }
  24835. const n = times.length;
  24836. const result = new Array( n );
  24837. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  24838. result.sort( compareTime );
  24839. return result;
  24840. }
  24841. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24842. function sortedArray( values, stride, order ) {
  24843. const nValues = values.length;
  24844. const result = new values.constructor( nValues );
  24845. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24846. const srcOffset = order[ i ] * stride;
  24847. for ( let j = 0; j !== stride; ++ j ) {
  24848. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24849. }
  24850. }
  24851. return result;
  24852. }
  24853. // function for parsing AOS keyframe formats
  24854. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  24855. let i = 1, key = jsonKeys[ 0 ];
  24856. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24857. key = jsonKeys[ i ++ ];
  24858. }
  24859. if ( key === undefined ) return; // no data
  24860. let value = key[ valuePropertyName ];
  24861. if ( value === undefined ) return; // no data
  24862. if ( Array.isArray( value ) ) {
  24863. do {
  24864. value = key[ valuePropertyName ];
  24865. if ( value !== undefined ) {
  24866. times.push( key.time );
  24867. values.push.apply( values, value ); // push all elements
  24868. }
  24869. key = jsonKeys[ i ++ ];
  24870. } while ( key !== undefined );
  24871. } else if ( value.toArray !== undefined ) {
  24872. // ...assume THREE.Math-ish
  24873. do {
  24874. value = key[ valuePropertyName ];
  24875. if ( value !== undefined ) {
  24876. times.push( key.time );
  24877. value.toArray( values, values.length );
  24878. }
  24879. key = jsonKeys[ i ++ ];
  24880. } while ( key !== undefined );
  24881. } else {
  24882. // otherwise push as-is
  24883. do {
  24884. value = key[ valuePropertyName ];
  24885. if ( value !== undefined ) {
  24886. times.push( key.time );
  24887. values.push( value );
  24888. }
  24889. key = jsonKeys[ i ++ ];
  24890. } while ( key !== undefined );
  24891. }
  24892. }
  24893. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  24894. const clip = sourceClip.clone();
  24895. clip.name = name;
  24896. const tracks = [];
  24897. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24898. const track = clip.tracks[ i ];
  24899. const valueSize = track.getValueSize();
  24900. const times = [];
  24901. const values = [];
  24902. for ( let j = 0; j < track.times.length; ++ j ) {
  24903. const frame = track.times[ j ] * fps;
  24904. if ( frame < startFrame || frame >= endFrame ) continue;
  24905. times.push( track.times[ j ] );
  24906. for ( let k = 0; k < valueSize; ++ k ) {
  24907. values.push( track.values[ j * valueSize + k ] );
  24908. }
  24909. }
  24910. if ( times.length === 0 ) continue;
  24911. track.times = convertArray( times, track.times.constructor );
  24912. track.values = convertArray( values, track.values.constructor );
  24913. tracks.push( track );
  24914. }
  24915. clip.tracks = tracks;
  24916. // find minimum .times value across all tracks in the trimmed clip
  24917. let minStartTime = Infinity;
  24918. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24919. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  24920. minStartTime = clip.tracks[ i ].times[ 0 ];
  24921. }
  24922. }
  24923. // shift all tracks such that clip begins at t=0
  24924. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24925. clip.tracks[ i ].shift( - 1 * minStartTime );
  24926. }
  24927. clip.resetDuration();
  24928. return clip;
  24929. }
  24930. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  24931. if ( fps <= 0 ) fps = 30;
  24932. const numTracks = referenceClip.tracks.length;
  24933. const referenceTime = referenceFrame / fps;
  24934. // Make each track's values relative to the values at the reference frame
  24935. for ( let i = 0; i < numTracks; ++ i ) {
  24936. const referenceTrack = referenceClip.tracks[ i ];
  24937. const referenceTrackType = referenceTrack.ValueTypeName;
  24938. // Skip this track if it's non-numeric
  24939. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  24940. // Find the track in the target clip whose name and type matches the reference track
  24941. const targetTrack = targetClip.tracks.find( function ( track ) {
  24942. return track.name === referenceTrack.name
  24943. && track.ValueTypeName === referenceTrackType;
  24944. } );
  24945. if ( targetTrack === undefined ) continue;
  24946. let referenceOffset = 0;
  24947. const referenceValueSize = referenceTrack.getValueSize();
  24948. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24949. referenceOffset = referenceValueSize / 3;
  24950. }
  24951. let targetOffset = 0;
  24952. const targetValueSize = targetTrack.getValueSize();
  24953. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24954. targetOffset = targetValueSize / 3;
  24955. }
  24956. const lastIndex = referenceTrack.times.length - 1;
  24957. let referenceValue;
  24958. // Find the value to subtract out of the track
  24959. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  24960. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  24961. const startIndex = referenceOffset;
  24962. const endIndex = referenceValueSize - referenceOffset;
  24963. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24964. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  24965. // Reference frame is after the last keyframe, so just use the last keyframe
  24966. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  24967. const endIndex = startIndex + referenceValueSize - referenceOffset;
  24968. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24969. } else {
  24970. // Interpolate to the reference value
  24971. const interpolant = referenceTrack.createInterpolant();
  24972. const startIndex = referenceOffset;
  24973. const endIndex = referenceValueSize - referenceOffset;
  24974. interpolant.evaluate( referenceTime );
  24975. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  24976. }
  24977. // Conjugate the quaternion
  24978. if ( referenceTrackType === 'quaternion' ) {
  24979. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  24980. referenceQuat.toArray( referenceValue );
  24981. }
  24982. // Subtract the reference value from all of the track values
  24983. const numTimes = targetTrack.times.length;
  24984. for ( let j = 0; j < numTimes; ++ j ) {
  24985. const valueStart = j * targetValueSize + targetOffset;
  24986. if ( referenceTrackType === 'quaternion' ) {
  24987. // Multiply the conjugate for quaternion track types
  24988. Quaternion.multiplyQuaternionsFlat(
  24989. targetTrack.values,
  24990. valueStart,
  24991. referenceValue,
  24992. 0,
  24993. targetTrack.values,
  24994. valueStart
  24995. );
  24996. } else {
  24997. const valueEnd = targetValueSize - targetOffset * 2;
  24998. // Subtract each value for all other numeric track types
  24999. for ( let k = 0; k < valueEnd; ++ k ) {
  25000. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  25001. }
  25002. }
  25003. }
  25004. }
  25005. targetClip.blendMode = AdditiveAnimationBlendMode;
  25006. return targetClip;
  25007. }
  25008. const AnimationUtils = {
  25009. convertArray: convertArray,
  25010. isTypedArray: isTypedArray,
  25011. getKeyframeOrder: getKeyframeOrder,
  25012. sortedArray: sortedArray,
  25013. flattenJSON: flattenJSON,
  25014. subclip: subclip,
  25015. makeClipAdditive: makeClipAdditive
  25016. };
  25017. /**
  25018. * Abstract base class of interpolants over parametric samples.
  25019. *
  25020. * The parameter domain is one dimensional, typically the time or a path
  25021. * along a curve defined by the data.
  25022. *
  25023. * The sample values can have any dimensionality and derived classes may
  25024. * apply special interpretations to the data.
  25025. *
  25026. * This class provides the interval seek in a Template Method, deferring
  25027. * the actual interpolation to derived classes.
  25028. *
  25029. * Time complexity is O(1) for linear access crossing at most two points
  25030. * and O(log N) for random access, where N is the number of positions.
  25031. *
  25032. * References:
  25033. *
  25034. * http://www.oodesign.com/template-method-pattern.html
  25035. *
  25036. */
  25037. class Interpolant {
  25038. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25039. this.parameterPositions = parameterPositions;
  25040. this._cachedIndex = 0;
  25041. this.resultBuffer = resultBuffer !== undefined ?
  25042. resultBuffer : new sampleValues.constructor( sampleSize );
  25043. this.sampleValues = sampleValues;
  25044. this.valueSize = sampleSize;
  25045. this.settings = null;
  25046. this.DefaultSettings_ = {};
  25047. }
  25048. evaluate( t ) {
  25049. const pp = this.parameterPositions;
  25050. let i1 = this._cachedIndex,
  25051. t1 = pp[ i1 ],
  25052. t0 = pp[ i1 - 1 ];
  25053. validate_interval: {
  25054. seek: {
  25055. let right;
  25056. linear_scan: {
  25057. //- See http://jsperf.com/comparison-to-undefined/3
  25058. //- slower code:
  25059. //-
  25060. //- if ( t >= t1 || t1 === undefined ) {
  25061. forward_scan: if ( ! ( t < t1 ) ) {
  25062. for ( let giveUpAt = i1 + 2; ; ) {
  25063. if ( t1 === undefined ) {
  25064. if ( t < t0 ) break forward_scan;
  25065. // after end
  25066. i1 = pp.length;
  25067. this._cachedIndex = i1;
  25068. return this.copySampleValue_( i1 - 1 );
  25069. }
  25070. if ( i1 === giveUpAt ) break; // this loop
  25071. t0 = t1;
  25072. t1 = pp[ ++ i1 ];
  25073. if ( t < t1 ) {
  25074. // we have arrived at the sought interval
  25075. break seek;
  25076. }
  25077. }
  25078. // prepare binary search on the right side of the index
  25079. right = pp.length;
  25080. break linear_scan;
  25081. }
  25082. //- slower code:
  25083. //- if ( t < t0 || t0 === undefined ) {
  25084. if ( ! ( t >= t0 ) ) {
  25085. // looping?
  25086. const t1global = pp[ 1 ];
  25087. if ( t < t1global ) {
  25088. i1 = 2; // + 1, using the scan for the details
  25089. t0 = t1global;
  25090. }
  25091. // linear reverse scan
  25092. for ( let giveUpAt = i1 - 2; ; ) {
  25093. if ( t0 === undefined ) {
  25094. // before start
  25095. this._cachedIndex = 0;
  25096. return this.copySampleValue_( 0 );
  25097. }
  25098. if ( i1 === giveUpAt ) break; // this loop
  25099. t1 = t0;
  25100. t0 = pp[ -- i1 - 1 ];
  25101. if ( t >= t0 ) {
  25102. // we have arrived at the sought interval
  25103. break seek;
  25104. }
  25105. }
  25106. // prepare binary search on the left side of the index
  25107. right = i1;
  25108. i1 = 0;
  25109. break linear_scan;
  25110. }
  25111. // the interval is valid
  25112. break validate_interval;
  25113. } // linear scan
  25114. // binary search
  25115. while ( i1 < right ) {
  25116. const mid = ( i1 + right ) >>> 1;
  25117. if ( t < pp[ mid ] ) {
  25118. right = mid;
  25119. } else {
  25120. i1 = mid + 1;
  25121. }
  25122. }
  25123. t1 = pp[ i1 ];
  25124. t0 = pp[ i1 - 1 ];
  25125. // check boundary cases, again
  25126. if ( t0 === undefined ) {
  25127. this._cachedIndex = 0;
  25128. return this.copySampleValue_( 0 );
  25129. }
  25130. if ( t1 === undefined ) {
  25131. i1 = pp.length;
  25132. this._cachedIndex = i1;
  25133. return this.copySampleValue_( i1 - 1 );
  25134. }
  25135. } // seek
  25136. this._cachedIndex = i1;
  25137. this.intervalChanged_( i1, t0, t1 );
  25138. } // validate_interval
  25139. return this.interpolate_( i1, t0, t, t1 );
  25140. }
  25141. getSettings_() {
  25142. return this.settings || this.DefaultSettings_;
  25143. }
  25144. copySampleValue_( index ) {
  25145. // copies a sample value to the result buffer
  25146. const result = this.resultBuffer,
  25147. values = this.sampleValues,
  25148. stride = this.valueSize,
  25149. offset = index * stride;
  25150. for ( let i = 0; i !== stride; ++ i ) {
  25151. result[ i ] = values[ offset + i ];
  25152. }
  25153. return result;
  25154. }
  25155. // Template methods for derived classes:
  25156. interpolate_( /* i1, t0, t, t1 */ ) {
  25157. throw new Error( 'call to abstract method' );
  25158. // implementations shall return this.resultBuffer
  25159. }
  25160. intervalChanged_( /* i1, t0, t1 */ ) {
  25161. // empty
  25162. }
  25163. }
  25164. /**
  25165. * Fast and simple cubic spline interpolant.
  25166. *
  25167. * It was derived from a Hermitian construction setting the first derivative
  25168. * at each sample position to the linear slope between neighboring positions
  25169. * over their parameter interval.
  25170. */
  25171. class CubicInterpolant extends Interpolant {
  25172. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25173. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25174. this._weightPrev = - 0;
  25175. this._offsetPrev = - 0;
  25176. this._weightNext = - 0;
  25177. this._offsetNext = - 0;
  25178. this.DefaultSettings_ = {
  25179. endingStart: ZeroCurvatureEnding,
  25180. endingEnd: ZeroCurvatureEnding
  25181. };
  25182. }
  25183. intervalChanged_( i1, t0, t1 ) {
  25184. const pp = this.parameterPositions;
  25185. let iPrev = i1 - 2,
  25186. iNext = i1 + 1,
  25187. tPrev = pp[ iPrev ],
  25188. tNext = pp[ iNext ];
  25189. if ( tPrev === undefined ) {
  25190. switch ( this.getSettings_().endingStart ) {
  25191. case ZeroSlopeEnding:
  25192. // f'(t0) = 0
  25193. iPrev = i1;
  25194. tPrev = 2 * t0 - t1;
  25195. break;
  25196. case WrapAroundEnding:
  25197. // use the other end of the curve
  25198. iPrev = pp.length - 2;
  25199. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  25200. break;
  25201. default: // ZeroCurvatureEnding
  25202. // f''(t0) = 0 a.k.a. Natural Spline
  25203. iPrev = i1;
  25204. tPrev = t1;
  25205. }
  25206. }
  25207. if ( tNext === undefined ) {
  25208. switch ( this.getSettings_().endingEnd ) {
  25209. case ZeroSlopeEnding:
  25210. // f'(tN) = 0
  25211. iNext = i1;
  25212. tNext = 2 * t1 - t0;
  25213. break;
  25214. case WrapAroundEnding:
  25215. // use the other end of the curve
  25216. iNext = 1;
  25217. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  25218. break;
  25219. default: // ZeroCurvatureEnding
  25220. // f''(tN) = 0, a.k.a. Natural Spline
  25221. iNext = i1 - 1;
  25222. tNext = t0;
  25223. }
  25224. }
  25225. const halfDt = ( t1 - t0 ) * 0.5,
  25226. stride = this.valueSize;
  25227. this._weightPrev = halfDt / ( t0 - tPrev );
  25228. this._weightNext = halfDt / ( tNext - t1 );
  25229. this._offsetPrev = iPrev * stride;
  25230. this._offsetNext = iNext * stride;
  25231. }
  25232. interpolate_( i1, t0, t, t1 ) {
  25233. const result = this.resultBuffer,
  25234. values = this.sampleValues,
  25235. stride = this.valueSize,
  25236. o1 = i1 * stride, o0 = o1 - stride,
  25237. oP = this._offsetPrev, oN = this._offsetNext,
  25238. wP = this._weightPrev, wN = this._weightNext,
  25239. p = ( t - t0 ) / ( t1 - t0 ),
  25240. pp = p * p,
  25241. ppp = pp * p;
  25242. // evaluate polynomials
  25243. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  25244. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  25245. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  25246. const sN = wN * ppp - wN * pp;
  25247. // combine data linearly
  25248. for ( let i = 0; i !== stride; ++ i ) {
  25249. result[ i ] =
  25250. sP * values[ oP + i ] +
  25251. s0 * values[ o0 + i ] +
  25252. s1 * values[ o1 + i ] +
  25253. sN * values[ oN + i ];
  25254. }
  25255. return result;
  25256. }
  25257. }
  25258. class LinearInterpolant extends Interpolant {
  25259. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25260. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25261. }
  25262. interpolate_( i1, t0, t, t1 ) {
  25263. const result = this.resultBuffer,
  25264. values = this.sampleValues,
  25265. stride = this.valueSize,
  25266. offset1 = i1 * stride,
  25267. offset0 = offset1 - stride,
  25268. weight1 = ( t - t0 ) / ( t1 - t0 ),
  25269. weight0 = 1 - weight1;
  25270. for ( let i = 0; i !== stride; ++ i ) {
  25271. result[ i ] =
  25272. values[ offset0 + i ] * weight0 +
  25273. values[ offset1 + i ] * weight1;
  25274. }
  25275. return result;
  25276. }
  25277. }
  25278. /**
  25279. *
  25280. * Interpolant that evaluates to the sample value at the position preceding
  25281. * the parameter.
  25282. */
  25283. class DiscreteInterpolant extends Interpolant {
  25284. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25285. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25286. }
  25287. interpolate_( i1 /*, t0, t, t1 */ ) {
  25288. return this.copySampleValue_( i1 - 1 );
  25289. }
  25290. }
  25291. class KeyframeTrack {
  25292. constructor( name, times, values, interpolation ) {
  25293. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25294. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25295. this.name = name;
  25296. this.times = convertArray( times, this.TimeBufferType );
  25297. this.values = convertArray( values, this.ValueBufferType );
  25298. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25299. }
  25300. // Serialization (in static context, because of constructor invocation
  25301. // and automatic invocation of .toJSON):
  25302. static toJSON( track ) {
  25303. const trackType = track.constructor;
  25304. let json;
  25305. // derived classes can define a static toJSON method
  25306. if ( trackType.toJSON !== this.toJSON ) {
  25307. json = trackType.toJSON( track );
  25308. } else {
  25309. // by default, we assume the data can be serialized as-is
  25310. json = {
  25311. 'name': track.name,
  25312. 'times': convertArray( track.times, Array ),
  25313. 'values': convertArray( track.values, Array )
  25314. };
  25315. const interpolation = track.getInterpolation();
  25316. if ( interpolation !== track.DefaultInterpolation ) {
  25317. json.interpolation = interpolation;
  25318. }
  25319. }
  25320. json.type = track.ValueTypeName; // mandatory
  25321. return json;
  25322. }
  25323. InterpolantFactoryMethodDiscrete( result ) {
  25324. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25325. }
  25326. InterpolantFactoryMethodLinear( result ) {
  25327. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25328. }
  25329. InterpolantFactoryMethodSmooth( result ) {
  25330. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25331. }
  25332. setInterpolation( interpolation ) {
  25333. let factoryMethod;
  25334. switch ( interpolation ) {
  25335. case InterpolateDiscrete:
  25336. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25337. break;
  25338. case InterpolateLinear:
  25339. factoryMethod = this.InterpolantFactoryMethodLinear;
  25340. break;
  25341. case InterpolateSmooth:
  25342. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25343. break;
  25344. }
  25345. if ( factoryMethod === undefined ) {
  25346. const message = 'unsupported interpolation for ' +
  25347. this.ValueTypeName + ' keyframe track named ' + this.name;
  25348. if ( this.createInterpolant === undefined ) {
  25349. // fall back to default, unless the default itself is messed up
  25350. if ( interpolation !== this.DefaultInterpolation ) {
  25351. this.setInterpolation( this.DefaultInterpolation );
  25352. } else {
  25353. throw new Error( message ); // fatal, in this case
  25354. }
  25355. }
  25356. console.warn( 'THREE.KeyframeTrack:', message );
  25357. return this;
  25358. }
  25359. this.createInterpolant = factoryMethod;
  25360. return this;
  25361. }
  25362. getInterpolation() {
  25363. switch ( this.createInterpolant ) {
  25364. case this.InterpolantFactoryMethodDiscrete:
  25365. return InterpolateDiscrete;
  25366. case this.InterpolantFactoryMethodLinear:
  25367. return InterpolateLinear;
  25368. case this.InterpolantFactoryMethodSmooth:
  25369. return InterpolateSmooth;
  25370. }
  25371. }
  25372. getValueSize() {
  25373. return this.values.length / this.times.length;
  25374. }
  25375. // move all keyframes either forwards or backwards in time
  25376. shift( timeOffset ) {
  25377. if ( timeOffset !== 0.0 ) {
  25378. const times = this.times;
  25379. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25380. times[ i ] += timeOffset;
  25381. }
  25382. }
  25383. return this;
  25384. }
  25385. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25386. scale( timeScale ) {
  25387. if ( timeScale !== 1.0 ) {
  25388. const times = this.times;
  25389. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25390. times[ i ] *= timeScale;
  25391. }
  25392. }
  25393. return this;
  25394. }
  25395. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25396. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25397. trim( startTime, endTime ) {
  25398. const times = this.times,
  25399. nKeys = times.length;
  25400. let from = 0,
  25401. to = nKeys - 1;
  25402. while ( from !== nKeys && times[ from ] < startTime ) {
  25403. ++ from;
  25404. }
  25405. while ( to !== - 1 && times[ to ] > endTime ) {
  25406. -- to;
  25407. }
  25408. ++ to; // inclusive -> exclusive bound
  25409. if ( from !== 0 || to !== nKeys ) {
  25410. // empty tracks are forbidden, so keep at least one keyframe
  25411. if ( from >= to ) {
  25412. to = Math.max( to, 1 );
  25413. from = to - 1;
  25414. }
  25415. const stride = this.getValueSize();
  25416. this.times = times.slice( from, to );
  25417. this.values = this.values.slice( from * stride, to * stride );
  25418. }
  25419. return this;
  25420. }
  25421. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25422. validate() {
  25423. let valid = true;
  25424. const valueSize = this.getValueSize();
  25425. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25426. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25427. valid = false;
  25428. }
  25429. const times = this.times,
  25430. values = this.values,
  25431. nKeys = times.length;
  25432. if ( nKeys === 0 ) {
  25433. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25434. valid = false;
  25435. }
  25436. let prevTime = null;
  25437. for ( let i = 0; i !== nKeys; i ++ ) {
  25438. const currTime = times[ i ];
  25439. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25440. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25441. valid = false;
  25442. break;
  25443. }
  25444. if ( prevTime !== null && prevTime > currTime ) {
  25445. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25446. valid = false;
  25447. break;
  25448. }
  25449. prevTime = currTime;
  25450. }
  25451. if ( values !== undefined ) {
  25452. if ( isTypedArray( values ) ) {
  25453. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  25454. const value = values[ i ];
  25455. if ( isNaN( value ) ) {
  25456. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25457. valid = false;
  25458. break;
  25459. }
  25460. }
  25461. }
  25462. }
  25463. return valid;
  25464. }
  25465. // removes equivalent sequential keys as common in morph target sequences
  25466. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25467. optimize() {
  25468. // times or values may be shared with other tracks, so overwriting is unsafe
  25469. const times = this.times.slice(),
  25470. values = this.values.slice(),
  25471. stride = this.getValueSize(),
  25472. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25473. lastIndex = times.length - 1;
  25474. let writeIndex = 1;
  25475. for ( let i = 1; i < lastIndex; ++ i ) {
  25476. let keep = false;
  25477. const time = times[ i ];
  25478. const timeNext = times[ i + 1 ];
  25479. // remove adjacent keyframes scheduled at the same time
  25480. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  25481. if ( ! smoothInterpolation ) {
  25482. // remove unnecessary keyframes same as their neighbors
  25483. const offset = i * stride,
  25484. offsetP = offset - stride,
  25485. offsetN = offset + stride;
  25486. for ( let j = 0; j !== stride; ++ j ) {
  25487. const value = values[ offset + j ];
  25488. if ( value !== values[ offsetP + j ] ||
  25489. value !== values[ offsetN + j ] ) {
  25490. keep = true;
  25491. break;
  25492. }
  25493. }
  25494. } else {
  25495. keep = true;
  25496. }
  25497. }
  25498. // in-place compaction
  25499. if ( keep ) {
  25500. if ( i !== writeIndex ) {
  25501. times[ writeIndex ] = times[ i ];
  25502. const readOffset = i * stride,
  25503. writeOffset = writeIndex * stride;
  25504. for ( let j = 0; j !== stride; ++ j ) {
  25505. values[ writeOffset + j ] = values[ readOffset + j ];
  25506. }
  25507. }
  25508. ++ writeIndex;
  25509. }
  25510. }
  25511. // flush last keyframe (compaction looks ahead)
  25512. if ( lastIndex > 0 ) {
  25513. times[ writeIndex ] = times[ lastIndex ];
  25514. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25515. values[ writeOffset + j ] = values[ readOffset + j ];
  25516. }
  25517. ++ writeIndex;
  25518. }
  25519. if ( writeIndex !== times.length ) {
  25520. this.times = times.slice( 0, writeIndex );
  25521. this.values = values.slice( 0, writeIndex * stride );
  25522. } else {
  25523. this.times = times;
  25524. this.values = values;
  25525. }
  25526. return this;
  25527. }
  25528. clone() {
  25529. const times = this.times.slice();
  25530. const values = this.values.slice();
  25531. const TypedKeyframeTrack = this.constructor;
  25532. const track = new TypedKeyframeTrack( this.name, times, values );
  25533. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  25534. track.createInterpolant = this.createInterpolant;
  25535. return track;
  25536. }
  25537. }
  25538. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  25539. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  25540. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25541. /**
  25542. * A Track of Boolean keyframe values.
  25543. */
  25544. class BooleanKeyframeTrack extends KeyframeTrack {
  25545. // No interpolation parameter because only InterpolateDiscrete is valid.
  25546. constructor( name, times, values ) {
  25547. super( name, times, values );
  25548. }
  25549. }
  25550. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  25551. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  25552. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25553. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25554. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25555. /**
  25556. * A Track of keyframe values that represent color.
  25557. */
  25558. class ColorKeyframeTrack extends KeyframeTrack {}
  25559. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  25560. /**
  25561. * A Track of numeric keyframe values.
  25562. */
  25563. class NumberKeyframeTrack extends KeyframeTrack {}
  25564. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  25565. /**
  25566. * Spherical linear unit quaternion interpolant.
  25567. */
  25568. class QuaternionLinearInterpolant extends Interpolant {
  25569. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25570. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25571. }
  25572. interpolate_( i1, t0, t, t1 ) {
  25573. const result = this.resultBuffer,
  25574. values = this.sampleValues,
  25575. stride = this.valueSize,
  25576. alpha = ( t - t0 ) / ( t1 - t0 );
  25577. let offset = i1 * stride;
  25578. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  25579. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25580. }
  25581. return result;
  25582. }
  25583. }
  25584. /**
  25585. * A Track of quaternion keyframe values.
  25586. */
  25587. class QuaternionKeyframeTrack extends KeyframeTrack {
  25588. InterpolantFactoryMethodLinear( result ) {
  25589. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25590. }
  25591. }
  25592. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  25593. // ValueBufferType is inherited
  25594. // DefaultInterpolation is inherited;
  25595. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25596. /**
  25597. * A Track that interpolates Strings
  25598. */
  25599. class StringKeyframeTrack extends KeyframeTrack {
  25600. // No interpolation parameter because only InterpolateDiscrete is valid.
  25601. constructor( name, times, values ) {
  25602. super( name, times, values );
  25603. }
  25604. }
  25605. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  25606. StringKeyframeTrack.prototype.ValueBufferType = Array;
  25607. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25608. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25609. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25610. /**
  25611. * A Track of vectored keyframe values.
  25612. */
  25613. class VectorKeyframeTrack extends KeyframeTrack {}
  25614. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  25615. class AnimationClip {
  25616. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  25617. this.name = name;
  25618. this.tracks = tracks;
  25619. this.duration = duration;
  25620. this.blendMode = blendMode;
  25621. this.uuid = generateUUID();
  25622. // this means it should figure out its duration by scanning the tracks
  25623. if ( this.duration < 0 ) {
  25624. this.resetDuration();
  25625. }
  25626. }
  25627. static parse( json ) {
  25628. const tracks = [],
  25629. jsonTracks = json.tracks,
  25630. frameTime = 1.0 / ( json.fps || 1.0 );
  25631. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25632. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25633. }
  25634. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  25635. clip.uuid = json.uuid;
  25636. return clip;
  25637. }
  25638. static toJSON( clip ) {
  25639. const tracks = [],
  25640. clipTracks = clip.tracks;
  25641. const json = {
  25642. 'name': clip.name,
  25643. 'duration': clip.duration,
  25644. 'tracks': tracks,
  25645. 'uuid': clip.uuid,
  25646. 'blendMode': clip.blendMode
  25647. };
  25648. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25649. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25650. }
  25651. return json;
  25652. }
  25653. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  25654. const numMorphTargets = morphTargetSequence.length;
  25655. const tracks = [];
  25656. for ( let i = 0; i < numMorphTargets; i ++ ) {
  25657. let times = [];
  25658. let values = [];
  25659. times.push(
  25660. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25661. i,
  25662. ( i + 1 ) % numMorphTargets );
  25663. values.push( 0, 1, 0 );
  25664. const order = getKeyframeOrder( times );
  25665. times = sortedArray( times, 1, order );
  25666. values = sortedArray( values, 1, order );
  25667. // if there is a key at the first frame, duplicate it as the
  25668. // last frame as well for perfect loop.
  25669. if ( ! noLoop && times[ 0 ] === 0 ) {
  25670. times.push( numMorphTargets );
  25671. values.push( values[ 0 ] );
  25672. }
  25673. tracks.push(
  25674. new NumberKeyframeTrack(
  25675. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25676. times, values
  25677. ).scale( 1.0 / fps ) );
  25678. }
  25679. return new this( name, - 1, tracks );
  25680. }
  25681. static findByName( objectOrClipArray, name ) {
  25682. let clipArray = objectOrClipArray;
  25683. if ( ! Array.isArray( objectOrClipArray ) ) {
  25684. const o = objectOrClipArray;
  25685. clipArray = o.geometry && o.geometry.animations || o.animations;
  25686. }
  25687. for ( let i = 0; i < clipArray.length; i ++ ) {
  25688. if ( clipArray[ i ].name === name ) {
  25689. return clipArray[ i ];
  25690. }
  25691. }
  25692. return null;
  25693. }
  25694. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  25695. const animationToMorphTargets = {};
  25696. // tested with https://regex101.com/ on trick sequences
  25697. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25698. const pattern = /^([\w-]*?)([\d]+)$/;
  25699. // sort morph target names into animation groups based
  25700. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25701. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  25702. const morphTarget = morphTargets[ i ];
  25703. const parts = morphTarget.name.match( pattern );
  25704. if ( parts && parts.length > 1 ) {
  25705. const name = parts[ 1 ];
  25706. let animationMorphTargets = animationToMorphTargets[ name ];
  25707. if ( ! animationMorphTargets ) {
  25708. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25709. }
  25710. animationMorphTargets.push( morphTarget );
  25711. }
  25712. }
  25713. const clips = [];
  25714. for ( const name in animationToMorphTargets ) {
  25715. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25716. }
  25717. return clips;
  25718. }
  25719. // parse the animation.hierarchy format
  25720. static parseAnimation( animation, bones ) {
  25721. if ( ! animation ) {
  25722. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25723. return null;
  25724. }
  25725. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25726. // only return track if there are actually keys.
  25727. if ( animationKeys.length !== 0 ) {
  25728. const times = [];
  25729. const values = [];
  25730. flattenJSON( animationKeys, times, values, propertyName );
  25731. // empty keys are filtered out, so check again
  25732. if ( times.length !== 0 ) {
  25733. destTracks.push( new trackType( trackName, times, values ) );
  25734. }
  25735. }
  25736. };
  25737. const tracks = [];
  25738. const clipName = animation.name || 'default';
  25739. const fps = animation.fps || 30;
  25740. const blendMode = animation.blendMode;
  25741. // automatic length determination in AnimationClip.
  25742. let duration = animation.length || - 1;
  25743. const hierarchyTracks = animation.hierarchy || [];
  25744. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  25745. const animationKeys = hierarchyTracks[ h ].keys;
  25746. // skip empty tracks
  25747. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25748. // process morph targets
  25749. if ( animationKeys[ 0 ].morphTargets ) {
  25750. // figure out all morph targets used in this track
  25751. const morphTargetNames = {};
  25752. let k;
  25753. for ( k = 0; k < animationKeys.length; k ++ ) {
  25754. if ( animationKeys[ k ].morphTargets ) {
  25755. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25756. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25757. }
  25758. }
  25759. }
  25760. // create a track for each morph target with all zero
  25761. // morphTargetInfluences except for the keys in which
  25762. // the morphTarget is named.
  25763. for ( const morphTargetName in morphTargetNames ) {
  25764. const times = [];
  25765. const values = [];
  25766. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25767. const animationKey = animationKeys[ k ];
  25768. times.push( animationKey.time );
  25769. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25770. }
  25771. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25772. }
  25773. duration = morphTargetNames.length * fps;
  25774. } else {
  25775. // ...assume skeletal animation
  25776. const boneName = '.bones[' + bones[ h ].name + ']';
  25777. addNonemptyTrack(
  25778. VectorKeyframeTrack, boneName + '.position',
  25779. animationKeys, 'pos', tracks );
  25780. addNonemptyTrack(
  25781. QuaternionKeyframeTrack, boneName + '.quaternion',
  25782. animationKeys, 'rot', tracks );
  25783. addNonemptyTrack(
  25784. VectorKeyframeTrack, boneName + '.scale',
  25785. animationKeys, 'scl', tracks );
  25786. }
  25787. }
  25788. if ( tracks.length === 0 ) {
  25789. return null;
  25790. }
  25791. const clip = new this( clipName, duration, tracks, blendMode );
  25792. return clip;
  25793. }
  25794. resetDuration() {
  25795. const tracks = this.tracks;
  25796. let duration = 0;
  25797. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  25798. const track = this.tracks[ i ];
  25799. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25800. }
  25801. this.duration = duration;
  25802. return this;
  25803. }
  25804. trim() {
  25805. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25806. this.tracks[ i ].trim( 0, this.duration );
  25807. }
  25808. return this;
  25809. }
  25810. validate() {
  25811. let valid = true;
  25812. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25813. valid = valid && this.tracks[ i ].validate();
  25814. }
  25815. return valid;
  25816. }
  25817. optimize() {
  25818. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25819. this.tracks[ i ].optimize();
  25820. }
  25821. return this;
  25822. }
  25823. clone() {
  25824. const tracks = [];
  25825. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25826. tracks.push( this.tracks[ i ].clone() );
  25827. }
  25828. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  25829. }
  25830. toJSON() {
  25831. return this.constructor.toJSON( this );
  25832. }
  25833. }
  25834. function getTrackTypeForValueTypeName( typeName ) {
  25835. switch ( typeName.toLowerCase() ) {
  25836. case 'scalar':
  25837. case 'double':
  25838. case 'float':
  25839. case 'number':
  25840. case 'integer':
  25841. return NumberKeyframeTrack;
  25842. case 'vector':
  25843. case 'vector2':
  25844. case 'vector3':
  25845. case 'vector4':
  25846. return VectorKeyframeTrack;
  25847. case 'color':
  25848. return ColorKeyframeTrack;
  25849. case 'quaternion':
  25850. return QuaternionKeyframeTrack;
  25851. case 'bool':
  25852. case 'boolean':
  25853. return BooleanKeyframeTrack;
  25854. case 'string':
  25855. return StringKeyframeTrack;
  25856. }
  25857. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25858. }
  25859. function parseKeyframeTrack( json ) {
  25860. if ( json.type === undefined ) {
  25861. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25862. }
  25863. const trackType = getTrackTypeForValueTypeName( json.type );
  25864. if ( json.times === undefined ) {
  25865. const times = [], values = [];
  25866. flattenJSON( json.keys, times, values, 'value' );
  25867. json.times = times;
  25868. json.values = values;
  25869. }
  25870. // derived classes can define a static parse method
  25871. if ( trackType.parse !== undefined ) {
  25872. return trackType.parse( json );
  25873. } else {
  25874. // by default, we assume a constructor compatible with the base
  25875. return new trackType( json.name, json.times, json.values, json.interpolation );
  25876. }
  25877. }
  25878. const Cache = {
  25879. enabled: false,
  25880. files: {},
  25881. add: function ( key, file ) {
  25882. if ( this.enabled === false ) return;
  25883. // console.log( 'THREE.Cache', 'Adding key:', key );
  25884. this.files[ key ] = file;
  25885. },
  25886. get: function ( key ) {
  25887. if ( this.enabled === false ) return;
  25888. // console.log( 'THREE.Cache', 'Checking key:', key );
  25889. return this.files[ key ];
  25890. },
  25891. remove: function ( key ) {
  25892. delete this.files[ key ];
  25893. },
  25894. clear: function () {
  25895. this.files = {};
  25896. }
  25897. };
  25898. class LoadingManager {
  25899. constructor( onLoad, onProgress, onError ) {
  25900. const scope = this;
  25901. let isLoading = false;
  25902. let itemsLoaded = 0;
  25903. let itemsTotal = 0;
  25904. let urlModifier = undefined;
  25905. const handlers = [];
  25906. // Refer to #5689 for the reason why we don't set .onStart
  25907. // in the constructor
  25908. this.onStart = undefined;
  25909. this.onLoad = onLoad;
  25910. this.onProgress = onProgress;
  25911. this.onError = onError;
  25912. this.itemStart = function ( url ) {
  25913. itemsTotal ++;
  25914. if ( isLoading === false ) {
  25915. if ( scope.onStart !== undefined ) {
  25916. scope.onStart( url, itemsLoaded, itemsTotal );
  25917. }
  25918. }
  25919. isLoading = true;
  25920. };
  25921. this.itemEnd = function ( url ) {
  25922. itemsLoaded ++;
  25923. if ( scope.onProgress !== undefined ) {
  25924. scope.onProgress( url, itemsLoaded, itemsTotal );
  25925. }
  25926. if ( itemsLoaded === itemsTotal ) {
  25927. isLoading = false;
  25928. if ( scope.onLoad !== undefined ) {
  25929. scope.onLoad();
  25930. }
  25931. }
  25932. };
  25933. this.itemError = function ( url ) {
  25934. if ( scope.onError !== undefined ) {
  25935. scope.onError( url );
  25936. }
  25937. };
  25938. this.resolveURL = function ( url ) {
  25939. if ( urlModifier ) {
  25940. return urlModifier( url );
  25941. }
  25942. return url;
  25943. };
  25944. this.setURLModifier = function ( transform ) {
  25945. urlModifier = transform;
  25946. return this;
  25947. };
  25948. this.addHandler = function ( regex, loader ) {
  25949. handlers.push( regex, loader );
  25950. return this;
  25951. };
  25952. this.removeHandler = function ( regex ) {
  25953. const index = handlers.indexOf( regex );
  25954. if ( index !== - 1 ) {
  25955. handlers.splice( index, 2 );
  25956. }
  25957. return this;
  25958. };
  25959. this.getHandler = function ( file ) {
  25960. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  25961. const regex = handlers[ i ];
  25962. const loader = handlers[ i + 1 ];
  25963. if ( regex.global ) regex.lastIndex = 0; // see #17920
  25964. if ( regex.test( file ) ) {
  25965. return loader;
  25966. }
  25967. }
  25968. return null;
  25969. };
  25970. }
  25971. }
  25972. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  25973. class Loader {
  25974. constructor( manager ) {
  25975. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25976. this.crossOrigin = 'anonymous';
  25977. this.withCredentials = false;
  25978. this.path = '';
  25979. this.resourcePath = '';
  25980. this.requestHeader = {};
  25981. }
  25982. load( /* url, onLoad, onProgress, onError */ ) {}
  25983. loadAsync( url, onProgress ) {
  25984. const scope = this;
  25985. return new Promise( function ( resolve, reject ) {
  25986. scope.load( url, resolve, onProgress, reject );
  25987. } );
  25988. }
  25989. parse( /* data */ ) {}
  25990. setCrossOrigin( crossOrigin ) {
  25991. this.crossOrigin = crossOrigin;
  25992. return this;
  25993. }
  25994. setWithCredentials( value ) {
  25995. this.withCredentials = value;
  25996. return this;
  25997. }
  25998. setPath( path ) {
  25999. this.path = path;
  26000. return this;
  26001. }
  26002. setResourcePath( resourcePath ) {
  26003. this.resourcePath = resourcePath;
  26004. return this;
  26005. }
  26006. setRequestHeader( requestHeader ) {
  26007. this.requestHeader = requestHeader;
  26008. return this;
  26009. }
  26010. }
  26011. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  26012. const loading = {};
  26013. class HttpError extends Error {
  26014. constructor( message, response ) {
  26015. super( message );
  26016. this.response = response;
  26017. }
  26018. }
  26019. class FileLoader extends Loader {
  26020. constructor( manager ) {
  26021. super( manager );
  26022. }
  26023. load( url, onLoad, onProgress, onError ) {
  26024. if ( url === undefined ) url = '';
  26025. if ( this.path !== undefined ) url = this.path + url;
  26026. url = this.manager.resolveURL( url );
  26027. const cached = Cache.get( url );
  26028. if ( cached !== undefined ) {
  26029. this.manager.itemStart( url );
  26030. setTimeout( () => {
  26031. if ( onLoad ) onLoad( cached );
  26032. this.manager.itemEnd( url );
  26033. }, 0 );
  26034. return cached;
  26035. }
  26036. // Check if request is duplicate
  26037. if ( loading[ url ] !== undefined ) {
  26038. loading[ url ].push( {
  26039. onLoad: onLoad,
  26040. onProgress: onProgress,
  26041. onError: onError
  26042. } );
  26043. return;
  26044. }
  26045. // Initialise array for duplicate requests
  26046. loading[ url ] = [];
  26047. loading[ url ].push( {
  26048. onLoad: onLoad,
  26049. onProgress: onProgress,
  26050. onError: onError,
  26051. } );
  26052. // create request
  26053. const req = new Request( url, {
  26054. headers: new Headers( this.requestHeader ),
  26055. credentials: this.withCredentials ? 'include' : 'same-origin',
  26056. // An abort controller could be added within a future PR
  26057. } );
  26058. // record states ( avoid data race )
  26059. const mimeType = this.mimeType;
  26060. const responseType = this.responseType;
  26061. // start the fetch
  26062. fetch( req )
  26063. .then( response => {
  26064. if ( response.status === 200 || response.status === 0 ) {
  26065. // Some browsers return HTTP Status 0 when using non-http protocol
  26066. // e.g. 'file://' or 'data://'. Handle as success.
  26067. if ( response.status === 0 ) {
  26068. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  26069. }
  26070. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  26071. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  26072. return response;
  26073. }
  26074. const callbacks = loading[ url ];
  26075. const reader = response.body.getReader();
  26076. // Nginx needs X-File-Size check
  26077. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  26078. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  26079. const total = contentLength ? parseInt( contentLength ) : 0;
  26080. const lengthComputable = total !== 0;
  26081. let loaded = 0;
  26082. // periodically read data into the new stream tracking while download progress
  26083. const stream = new ReadableStream( {
  26084. start( controller ) {
  26085. readData();
  26086. function readData() {
  26087. reader.read().then( ( { done, value } ) => {
  26088. if ( done ) {
  26089. controller.close();
  26090. } else {
  26091. loaded += value.byteLength;
  26092. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  26093. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26094. const callback = callbacks[ i ];
  26095. if ( callback.onProgress ) callback.onProgress( event );
  26096. }
  26097. controller.enqueue( value );
  26098. readData();
  26099. }
  26100. }, ( e ) => {
  26101. controller.error( e );
  26102. } );
  26103. }
  26104. }
  26105. } );
  26106. return new Response( stream );
  26107. } else {
  26108. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  26109. }
  26110. } )
  26111. .then( response => {
  26112. switch ( responseType ) {
  26113. case 'arraybuffer':
  26114. return response.arrayBuffer();
  26115. case 'blob':
  26116. return response.blob();
  26117. case 'document':
  26118. return response.text()
  26119. .then( text => {
  26120. const parser = new DOMParser();
  26121. return parser.parseFromString( text, mimeType );
  26122. } );
  26123. case 'json':
  26124. return response.json();
  26125. default:
  26126. if ( mimeType === undefined ) {
  26127. return response.text();
  26128. } else {
  26129. // sniff encoding
  26130. const re = /charset="?([^;"\s]*)"?/i;
  26131. const exec = re.exec( mimeType );
  26132. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  26133. const decoder = new TextDecoder( label );
  26134. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  26135. }
  26136. }
  26137. } )
  26138. .then( data => {
  26139. // Add to cache only on HTTP success, so that we do not cache
  26140. // error response bodies as proper responses to requests.
  26141. Cache.add( url, data );
  26142. const callbacks = loading[ url ];
  26143. delete loading[ url ];
  26144. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26145. const callback = callbacks[ i ];
  26146. if ( callback.onLoad ) callback.onLoad( data );
  26147. }
  26148. } )
  26149. .catch( err => {
  26150. // Abort errors and other errors are handled the same
  26151. const callbacks = loading[ url ];
  26152. if ( callbacks === undefined ) {
  26153. // When onLoad was called and url was deleted in `loading`
  26154. this.manager.itemError( url );
  26155. throw err;
  26156. }
  26157. delete loading[ url ];
  26158. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26159. const callback = callbacks[ i ];
  26160. if ( callback.onError ) callback.onError( err );
  26161. }
  26162. this.manager.itemError( url );
  26163. } )
  26164. .finally( () => {
  26165. this.manager.itemEnd( url );
  26166. } );
  26167. this.manager.itemStart( url );
  26168. }
  26169. setResponseType( value ) {
  26170. this.responseType = value;
  26171. return this;
  26172. }
  26173. setMimeType( value ) {
  26174. this.mimeType = value;
  26175. return this;
  26176. }
  26177. }
  26178. class AnimationLoader extends Loader {
  26179. constructor( manager ) {
  26180. super( manager );
  26181. }
  26182. load( url, onLoad, onProgress, onError ) {
  26183. const scope = this;
  26184. const loader = new FileLoader( this.manager );
  26185. loader.setPath( this.path );
  26186. loader.setRequestHeader( this.requestHeader );
  26187. loader.setWithCredentials( this.withCredentials );
  26188. loader.load( url, function ( text ) {
  26189. try {
  26190. onLoad( scope.parse( JSON.parse( text ) ) );
  26191. } catch ( e ) {
  26192. if ( onError ) {
  26193. onError( e );
  26194. } else {
  26195. console.error( e );
  26196. }
  26197. scope.manager.itemError( url );
  26198. }
  26199. }, onProgress, onError );
  26200. }
  26201. parse( json ) {
  26202. const animations = [];
  26203. for ( let i = 0; i < json.length; i ++ ) {
  26204. const clip = AnimationClip.parse( json[ i ] );
  26205. animations.push( clip );
  26206. }
  26207. return animations;
  26208. }
  26209. }
  26210. /**
  26211. * Abstract Base class to block based textures loader (dds, pvr, ...)
  26212. *
  26213. * Sub classes have to implement the parse() method which will be used in load().
  26214. */
  26215. class CompressedTextureLoader extends Loader {
  26216. constructor( manager ) {
  26217. super( manager );
  26218. }
  26219. load( url, onLoad, onProgress, onError ) {
  26220. const scope = this;
  26221. const images = [];
  26222. const texture = new CompressedTexture();
  26223. const loader = new FileLoader( this.manager );
  26224. loader.setPath( this.path );
  26225. loader.setResponseType( 'arraybuffer' );
  26226. loader.setRequestHeader( this.requestHeader );
  26227. loader.setWithCredentials( scope.withCredentials );
  26228. let loaded = 0;
  26229. function loadTexture( i ) {
  26230. loader.load( url[ i ], function ( buffer ) {
  26231. const texDatas = scope.parse( buffer, true );
  26232. images[ i ] = {
  26233. width: texDatas.width,
  26234. height: texDatas.height,
  26235. format: texDatas.format,
  26236. mipmaps: texDatas.mipmaps
  26237. };
  26238. loaded += 1;
  26239. if ( loaded === 6 ) {
  26240. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  26241. texture.image = images;
  26242. texture.format = texDatas.format;
  26243. texture.needsUpdate = true;
  26244. if ( onLoad ) onLoad( texture );
  26245. }
  26246. }, onProgress, onError );
  26247. }
  26248. if ( Array.isArray( url ) ) {
  26249. for ( let i = 0, il = url.length; i < il; ++ i ) {
  26250. loadTexture( i );
  26251. }
  26252. } else {
  26253. // compressed cubemap texture stored in a single DDS file
  26254. loader.load( url, function ( buffer ) {
  26255. const texDatas = scope.parse( buffer, true );
  26256. if ( texDatas.isCubemap ) {
  26257. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  26258. for ( let f = 0; f < faces; f ++ ) {
  26259. images[ f ] = { mipmaps: [] };
  26260. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  26261. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  26262. images[ f ].format = texDatas.format;
  26263. images[ f ].width = texDatas.width;
  26264. images[ f ].height = texDatas.height;
  26265. }
  26266. }
  26267. texture.image = images;
  26268. } else {
  26269. texture.image.width = texDatas.width;
  26270. texture.image.height = texDatas.height;
  26271. texture.mipmaps = texDatas.mipmaps;
  26272. }
  26273. if ( texDatas.mipmapCount === 1 ) {
  26274. texture.minFilter = LinearFilter;
  26275. }
  26276. texture.format = texDatas.format;
  26277. texture.needsUpdate = true;
  26278. if ( onLoad ) onLoad( texture );
  26279. }, onProgress, onError );
  26280. }
  26281. return texture;
  26282. }
  26283. }
  26284. class ImageLoader extends Loader {
  26285. constructor( manager ) {
  26286. super( manager );
  26287. }
  26288. load( url, onLoad, onProgress, onError ) {
  26289. if ( this.path !== undefined ) url = this.path + url;
  26290. url = this.manager.resolveURL( url );
  26291. const scope = this;
  26292. const cached = Cache.get( url );
  26293. if ( cached !== undefined ) {
  26294. scope.manager.itemStart( url );
  26295. setTimeout( function () {
  26296. if ( onLoad ) onLoad( cached );
  26297. scope.manager.itemEnd( url );
  26298. }, 0 );
  26299. return cached;
  26300. }
  26301. const image = createElementNS( 'img' );
  26302. function onImageLoad() {
  26303. removeEventListeners();
  26304. Cache.add( url, this );
  26305. if ( onLoad ) onLoad( this );
  26306. scope.manager.itemEnd( url );
  26307. }
  26308. function onImageError( event ) {
  26309. removeEventListeners();
  26310. if ( onError ) onError( event );
  26311. scope.manager.itemError( url );
  26312. scope.manager.itemEnd( url );
  26313. }
  26314. function removeEventListeners() {
  26315. image.removeEventListener( 'load', onImageLoad, false );
  26316. image.removeEventListener( 'error', onImageError, false );
  26317. }
  26318. image.addEventListener( 'load', onImageLoad, false );
  26319. image.addEventListener( 'error', onImageError, false );
  26320. if ( url.slice( 0, 5 ) !== 'data:' ) {
  26321. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  26322. }
  26323. scope.manager.itemStart( url );
  26324. image.src = url;
  26325. return image;
  26326. }
  26327. }
  26328. class CubeTextureLoader extends Loader {
  26329. constructor( manager ) {
  26330. super( manager );
  26331. }
  26332. load( urls, onLoad, onProgress, onError ) {
  26333. const texture = new CubeTexture();
  26334. texture.colorSpace = SRGBColorSpace;
  26335. const loader = new ImageLoader( this.manager );
  26336. loader.setCrossOrigin( this.crossOrigin );
  26337. loader.setPath( this.path );
  26338. let loaded = 0;
  26339. function loadTexture( i ) {
  26340. loader.load( urls[ i ], function ( image ) {
  26341. texture.images[ i ] = image;
  26342. loaded ++;
  26343. if ( loaded === 6 ) {
  26344. texture.needsUpdate = true;
  26345. if ( onLoad ) onLoad( texture );
  26346. }
  26347. }, undefined, onError );
  26348. }
  26349. for ( let i = 0; i < urls.length; ++ i ) {
  26350. loadTexture( i );
  26351. }
  26352. return texture;
  26353. }
  26354. }
  26355. /**
  26356. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  26357. *
  26358. * Sub classes have to implement the parse() method which will be used in load().
  26359. */
  26360. class DataTextureLoader extends Loader {
  26361. constructor( manager ) {
  26362. super( manager );
  26363. }
  26364. load( url, onLoad, onProgress, onError ) {
  26365. const scope = this;
  26366. const texture = new DataTexture();
  26367. const loader = new FileLoader( this.manager );
  26368. loader.setResponseType( 'arraybuffer' );
  26369. loader.setRequestHeader( this.requestHeader );
  26370. loader.setPath( this.path );
  26371. loader.setWithCredentials( scope.withCredentials );
  26372. loader.load( url, function ( buffer ) {
  26373. let texData;
  26374. try {
  26375. texData = scope.parse( buffer );
  26376. } catch ( error ) {
  26377. if ( onError !== undefined ) {
  26378. onError( error );
  26379. } else {
  26380. console.error( error );
  26381. return;
  26382. }
  26383. }
  26384. if ( texData.image !== undefined ) {
  26385. texture.image = texData.image;
  26386. } else if ( texData.data !== undefined ) {
  26387. texture.image.width = texData.width;
  26388. texture.image.height = texData.height;
  26389. texture.image.data = texData.data;
  26390. }
  26391. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  26392. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  26393. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  26394. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  26395. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  26396. if ( texData.colorSpace !== undefined ) {
  26397. texture.colorSpace = texData.colorSpace;
  26398. }
  26399. if ( texData.flipY !== undefined ) {
  26400. texture.flipY = texData.flipY;
  26401. }
  26402. if ( texData.format !== undefined ) {
  26403. texture.format = texData.format;
  26404. }
  26405. if ( texData.type !== undefined ) {
  26406. texture.type = texData.type;
  26407. }
  26408. if ( texData.mipmaps !== undefined ) {
  26409. texture.mipmaps = texData.mipmaps;
  26410. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  26411. }
  26412. if ( texData.mipmapCount === 1 ) {
  26413. texture.minFilter = LinearFilter;
  26414. }
  26415. if ( texData.generateMipmaps !== undefined ) {
  26416. texture.generateMipmaps = texData.generateMipmaps;
  26417. }
  26418. texture.needsUpdate = true;
  26419. if ( onLoad ) onLoad( texture, texData );
  26420. }, onProgress, onError );
  26421. return texture;
  26422. }
  26423. }
  26424. class TextureLoader extends Loader {
  26425. constructor( manager ) {
  26426. super( manager );
  26427. }
  26428. load( url, onLoad, onProgress, onError ) {
  26429. const texture = new Texture();
  26430. const loader = new ImageLoader( this.manager );
  26431. loader.setCrossOrigin( this.crossOrigin );
  26432. loader.setPath( this.path );
  26433. loader.load( url, function ( image ) {
  26434. texture.image = image;
  26435. texture.needsUpdate = true;
  26436. if ( onLoad !== undefined ) {
  26437. onLoad( texture );
  26438. }
  26439. }, onProgress, onError );
  26440. return texture;
  26441. }
  26442. }
  26443. class Light extends Object3D {
  26444. constructor( color, intensity = 1 ) {
  26445. super();
  26446. this.isLight = true;
  26447. this.type = 'Light';
  26448. this.color = new Color( color );
  26449. this.intensity = intensity;
  26450. }
  26451. dispose() {
  26452. // Empty here in base class; some subclasses override.
  26453. }
  26454. copy( source, recursive ) {
  26455. super.copy( source, recursive );
  26456. this.color.copy( source.color );
  26457. this.intensity = source.intensity;
  26458. return this;
  26459. }
  26460. toJSON( meta ) {
  26461. const data = super.toJSON( meta );
  26462. data.object.color = this.color.getHex();
  26463. data.object.intensity = this.intensity;
  26464. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26465. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26466. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26467. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26468. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26469. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26470. return data;
  26471. }
  26472. }
  26473. class HemisphereLight extends Light {
  26474. constructor( skyColor, groundColor, intensity ) {
  26475. super( skyColor, intensity );
  26476. this.isHemisphereLight = true;
  26477. this.type = 'HemisphereLight';
  26478. this.position.copy( Object3D.DEFAULT_UP );
  26479. this.updateMatrix();
  26480. this.groundColor = new Color( groundColor );
  26481. }
  26482. copy( source, recursive ) {
  26483. super.copy( source, recursive );
  26484. this.groundColor.copy( source.groundColor );
  26485. return this;
  26486. }
  26487. }
  26488. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  26489. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  26490. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  26491. class LightShadow {
  26492. constructor( camera ) {
  26493. this.camera = camera;
  26494. this.bias = 0;
  26495. this.normalBias = 0;
  26496. this.radius = 1;
  26497. this.blurSamples = 8;
  26498. this.mapSize = new Vector2( 512, 512 );
  26499. this.map = null;
  26500. this.mapPass = null;
  26501. this.matrix = new Matrix4();
  26502. this.autoUpdate = true;
  26503. this.needsUpdate = false;
  26504. this._frustum = new Frustum();
  26505. this._frameExtents = new Vector2( 1, 1 );
  26506. this._viewportCount = 1;
  26507. this._viewports = [
  26508. new Vector4( 0, 0, 1, 1 )
  26509. ];
  26510. }
  26511. getViewportCount() {
  26512. return this._viewportCount;
  26513. }
  26514. getFrustum() {
  26515. return this._frustum;
  26516. }
  26517. updateMatrices( light ) {
  26518. const shadowCamera = this.camera;
  26519. const shadowMatrix = this.matrix;
  26520. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  26521. shadowCamera.position.copy( _lightPositionWorld$1 );
  26522. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  26523. shadowCamera.lookAt( _lookTarget$1 );
  26524. shadowCamera.updateMatrixWorld();
  26525. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  26526. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  26527. shadowMatrix.set(
  26528. 0.5, 0.0, 0.0, 0.5,
  26529. 0.0, 0.5, 0.0, 0.5,
  26530. 0.0, 0.0, 0.5, 0.5,
  26531. 0.0, 0.0, 0.0, 1.0
  26532. );
  26533. shadowMatrix.multiply( _projScreenMatrix$1 );
  26534. }
  26535. getViewport( viewportIndex ) {
  26536. return this._viewports[ viewportIndex ];
  26537. }
  26538. getFrameExtents() {
  26539. return this._frameExtents;
  26540. }
  26541. dispose() {
  26542. if ( this.map ) {
  26543. this.map.dispose();
  26544. }
  26545. if ( this.mapPass ) {
  26546. this.mapPass.dispose();
  26547. }
  26548. }
  26549. copy( source ) {
  26550. this.camera = source.camera.clone();
  26551. this.bias = source.bias;
  26552. this.radius = source.radius;
  26553. this.mapSize.copy( source.mapSize );
  26554. return this;
  26555. }
  26556. clone() {
  26557. return new this.constructor().copy( this );
  26558. }
  26559. toJSON() {
  26560. const object = {};
  26561. if ( this.bias !== 0 ) object.bias = this.bias;
  26562. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  26563. if ( this.radius !== 1 ) object.radius = this.radius;
  26564. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26565. object.camera = this.camera.toJSON( false ).object;
  26566. delete object.camera.matrix;
  26567. return object;
  26568. }
  26569. }
  26570. class SpotLightShadow extends LightShadow {
  26571. constructor() {
  26572. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26573. this.isSpotLightShadow = true;
  26574. this.focus = 1;
  26575. }
  26576. updateMatrices( light ) {
  26577. const camera = this.camera;
  26578. const fov = RAD2DEG * 2 * light.angle * this.focus;
  26579. const aspect = this.mapSize.width / this.mapSize.height;
  26580. const far = light.distance || camera.far;
  26581. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  26582. camera.fov = fov;
  26583. camera.aspect = aspect;
  26584. camera.far = far;
  26585. camera.updateProjectionMatrix();
  26586. }
  26587. super.updateMatrices( light );
  26588. }
  26589. copy( source ) {
  26590. super.copy( source );
  26591. this.focus = source.focus;
  26592. return this;
  26593. }
  26594. }
  26595. class SpotLight extends Light {
  26596. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  26597. super( color, intensity );
  26598. this.isSpotLight = true;
  26599. this.type = 'SpotLight';
  26600. this.position.copy( Object3D.DEFAULT_UP );
  26601. this.updateMatrix();
  26602. this.target = new Object3D();
  26603. this.distance = distance;
  26604. this.angle = angle;
  26605. this.penumbra = penumbra;
  26606. this.decay = decay;
  26607. this.map = null;
  26608. this.shadow = new SpotLightShadow();
  26609. }
  26610. get power() {
  26611. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26612. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  26613. return this.intensity * Math.PI;
  26614. }
  26615. set power( power ) {
  26616. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26617. this.intensity = power / Math.PI;
  26618. }
  26619. dispose() {
  26620. this.shadow.dispose();
  26621. }
  26622. copy( source, recursive ) {
  26623. super.copy( source, recursive );
  26624. this.distance = source.distance;
  26625. this.angle = source.angle;
  26626. this.penumbra = source.penumbra;
  26627. this.decay = source.decay;
  26628. this.target = source.target.clone();
  26629. this.shadow = source.shadow.clone();
  26630. return this;
  26631. }
  26632. }
  26633. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  26634. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  26635. const _lookTarget = /*@__PURE__*/ new Vector3();
  26636. class PointLightShadow extends LightShadow {
  26637. constructor() {
  26638. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  26639. this.isPointLightShadow = true;
  26640. this._frameExtents = new Vector2( 4, 2 );
  26641. this._viewportCount = 6;
  26642. this._viewports = [
  26643. // These viewports map a cube-map onto a 2D texture with the
  26644. // following orientation:
  26645. //
  26646. // xzXZ
  26647. // y Y
  26648. //
  26649. // X - Positive x direction
  26650. // x - Negative x direction
  26651. // Y - Positive y direction
  26652. // y - Negative y direction
  26653. // Z - Positive z direction
  26654. // z - Negative z direction
  26655. // positive X
  26656. new Vector4( 2, 1, 1, 1 ),
  26657. // negative X
  26658. new Vector4( 0, 1, 1, 1 ),
  26659. // positive Z
  26660. new Vector4( 3, 1, 1, 1 ),
  26661. // negative Z
  26662. new Vector4( 1, 1, 1, 1 ),
  26663. // positive Y
  26664. new Vector4( 3, 0, 1, 1 ),
  26665. // negative Y
  26666. new Vector4( 1, 0, 1, 1 )
  26667. ];
  26668. this._cubeDirections = [
  26669. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  26670. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  26671. ];
  26672. this._cubeUps = [
  26673. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  26674. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  26675. ];
  26676. }
  26677. updateMatrices( light, viewportIndex = 0 ) {
  26678. const camera = this.camera;
  26679. const shadowMatrix = this.matrix;
  26680. const far = light.distance || camera.far;
  26681. if ( far !== camera.far ) {
  26682. camera.far = far;
  26683. camera.updateProjectionMatrix();
  26684. }
  26685. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  26686. camera.position.copy( _lightPositionWorld );
  26687. _lookTarget.copy( camera.position );
  26688. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  26689. camera.up.copy( this._cubeUps[ viewportIndex ] );
  26690. camera.lookAt( _lookTarget );
  26691. camera.updateMatrixWorld();
  26692. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  26693. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  26694. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  26695. }
  26696. }
  26697. class PointLight extends Light {
  26698. constructor( color, intensity, distance = 0, decay = 2 ) {
  26699. super( color, intensity );
  26700. this.isPointLight = true;
  26701. this.type = 'PointLight';
  26702. this.distance = distance;
  26703. this.decay = decay;
  26704. this.shadow = new PointLightShadow();
  26705. }
  26706. get power() {
  26707. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26708. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  26709. return this.intensity * 4 * Math.PI;
  26710. }
  26711. set power( power ) {
  26712. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26713. this.intensity = power / ( 4 * Math.PI );
  26714. }
  26715. dispose() {
  26716. this.shadow.dispose();
  26717. }
  26718. copy( source, recursive ) {
  26719. super.copy( source, recursive );
  26720. this.distance = source.distance;
  26721. this.decay = source.decay;
  26722. this.shadow = source.shadow.clone();
  26723. return this;
  26724. }
  26725. }
  26726. class DirectionalLightShadow extends LightShadow {
  26727. constructor() {
  26728. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  26729. this.isDirectionalLightShadow = true;
  26730. }
  26731. }
  26732. class DirectionalLight extends Light {
  26733. constructor( color, intensity ) {
  26734. super( color, intensity );
  26735. this.isDirectionalLight = true;
  26736. this.type = 'DirectionalLight';
  26737. this.position.copy( Object3D.DEFAULT_UP );
  26738. this.updateMatrix();
  26739. this.target = new Object3D();
  26740. this.shadow = new DirectionalLightShadow();
  26741. }
  26742. dispose() {
  26743. this.shadow.dispose();
  26744. }
  26745. copy( source ) {
  26746. super.copy( source );
  26747. this.target = source.target.clone();
  26748. this.shadow = source.shadow.clone();
  26749. return this;
  26750. }
  26751. }
  26752. class AmbientLight extends Light {
  26753. constructor( color, intensity ) {
  26754. super( color, intensity );
  26755. this.isAmbientLight = true;
  26756. this.type = 'AmbientLight';
  26757. }
  26758. }
  26759. class RectAreaLight extends Light {
  26760. constructor( color, intensity, width = 10, height = 10 ) {
  26761. super( color, intensity );
  26762. this.isRectAreaLight = true;
  26763. this.type = 'RectAreaLight';
  26764. this.width = width;
  26765. this.height = height;
  26766. }
  26767. get power() {
  26768. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26769. return this.intensity * this.width * this.height * Math.PI;
  26770. }
  26771. set power( power ) {
  26772. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26773. this.intensity = power / ( this.width * this.height * Math.PI );
  26774. }
  26775. copy( source ) {
  26776. super.copy( source );
  26777. this.width = source.width;
  26778. this.height = source.height;
  26779. return this;
  26780. }
  26781. toJSON( meta ) {
  26782. const data = super.toJSON( meta );
  26783. data.object.width = this.width;
  26784. data.object.height = this.height;
  26785. return data;
  26786. }
  26787. }
  26788. /**
  26789. * Primary reference:
  26790. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26791. *
  26792. * Secondary reference:
  26793. * https://www.ppsloan.org/publications/StupidSH36.pdf
  26794. */
  26795. // 3-band SH defined by 9 coefficients
  26796. class SphericalHarmonics3 {
  26797. constructor() {
  26798. this.isSphericalHarmonics3 = true;
  26799. this.coefficients = [];
  26800. for ( let i = 0; i < 9; i ++ ) {
  26801. this.coefficients.push( new Vector3() );
  26802. }
  26803. }
  26804. set( coefficients ) {
  26805. for ( let i = 0; i < 9; i ++ ) {
  26806. this.coefficients[ i ].copy( coefficients[ i ] );
  26807. }
  26808. return this;
  26809. }
  26810. zero() {
  26811. for ( let i = 0; i < 9; i ++ ) {
  26812. this.coefficients[ i ].set( 0, 0, 0 );
  26813. }
  26814. return this;
  26815. }
  26816. // get the radiance in the direction of the normal
  26817. // target is a Vector3
  26818. getAt( normal, target ) {
  26819. // normal is assumed to be unit length
  26820. const x = normal.x, y = normal.y, z = normal.z;
  26821. const coeff = this.coefficients;
  26822. // band 0
  26823. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  26824. // band 1
  26825. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  26826. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  26827. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  26828. // band 2
  26829. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  26830. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  26831. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  26832. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  26833. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  26834. return target;
  26835. }
  26836. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  26837. // target is a Vector3
  26838. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26839. getIrradianceAt( normal, target ) {
  26840. // normal is assumed to be unit length
  26841. const x = normal.x, y = normal.y, z = normal.z;
  26842. const coeff = this.coefficients;
  26843. // band 0
  26844. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  26845. // band 1
  26846. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  26847. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  26848. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  26849. // band 2
  26850. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  26851. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  26852. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  26853. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  26854. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  26855. return target;
  26856. }
  26857. add( sh ) {
  26858. for ( let i = 0; i < 9; i ++ ) {
  26859. this.coefficients[ i ].add( sh.coefficients[ i ] );
  26860. }
  26861. return this;
  26862. }
  26863. addScaledSH( sh, s ) {
  26864. for ( let i = 0; i < 9; i ++ ) {
  26865. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  26866. }
  26867. return this;
  26868. }
  26869. scale( s ) {
  26870. for ( let i = 0; i < 9; i ++ ) {
  26871. this.coefficients[ i ].multiplyScalar( s );
  26872. }
  26873. return this;
  26874. }
  26875. lerp( sh, alpha ) {
  26876. for ( let i = 0; i < 9; i ++ ) {
  26877. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  26878. }
  26879. return this;
  26880. }
  26881. equals( sh ) {
  26882. for ( let i = 0; i < 9; i ++ ) {
  26883. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  26884. return false;
  26885. }
  26886. }
  26887. return true;
  26888. }
  26889. copy( sh ) {
  26890. return this.set( sh.coefficients );
  26891. }
  26892. clone() {
  26893. return new this.constructor().copy( this );
  26894. }
  26895. fromArray( array, offset = 0 ) {
  26896. const coefficients = this.coefficients;
  26897. for ( let i = 0; i < 9; i ++ ) {
  26898. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  26899. }
  26900. return this;
  26901. }
  26902. toArray( array = [], offset = 0 ) {
  26903. const coefficients = this.coefficients;
  26904. for ( let i = 0; i < 9; i ++ ) {
  26905. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  26906. }
  26907. return array;
  26908. }
  26909. // evaluate the basis functions
  26910. // shBasis is an Array[ 9 ]
  26911. static getBasisAt( normal, shBasis ) {
  26912. // normal is assumed to be unit length
  26913. const x = normal.x, y = normal.y, z = normal.z;
  26914. // band 0
  26915. shBasis[ 0 ] = 0.282095;
  26916. // band 1
  26917. shBasis[ 1 ] = 0.488603 * y;
  26918. shBasis[ 2 ] = 0.488603 * z;
  26919. shBasis[ 3 ] = 0.488603 * x;
  26920. // band 2
  26921. shBasis[ 4 ] = 1.092548 * x * y;
  26922. shBasis[ 5 ] = 1.092548 * y * z;
  26923. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  26924. shBasis[ 7 ] = 1.092548 * x * z;
  26925. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  26926. }
  26927. }
  26928. class LightProbe extends Light {
  26929. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  26930. super( undefined, intensity );
  26931. this.isLightProbe = true;
  26932. this.sh = sh;
  26933. }
  26934. copy( source ) {
  26935. super.copy( source );
  26936. this.sh.copy( source.sh );
  26937. return this;
  26938. }
  26939. fromJSON( json ) {
  26940. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  26941. this.sh.fromArray( json.sh );
  26942. return this;
  26943. }
  26944. toJSON( meta ) {
  26945. const data = super.toJSON( meta );
  26946. data.object.sh = this.sh.toArray();
  26947. return data;
  26948. }
  26949. }
  26950. class MaterialLoader extends Loader {
  26951. constructor( manager ) {
  26952. super( manager );
  26953. this.textures = {};
  26954. }
  26955. load( url, onLoad, onProgress, onError ) {
  26956. const scope = this;
  26957. const loader = new FileLoader( scope.manager );
  26958. loader.setPath( scope.path );
  26959. loader.setRequestHeader( scope.requestHeader );
  26960. loader.setWithCredentials( scope.withCredentials );
  26961. loader.load( url, function ( text ) {
  26962. try {
  26963. onLoad( scope.parse( JSON.parse( text ) ) );
  26964. } catch ( e ) {
  26965. if ( onError ) {
  26966. onError( e );
  26967. } else {
  26968. console.error( e );
  26969. }
  26970. scope.manager.itemError( url );
  26971. }
  26972. }, onProgress, onError );
  26973. }
  26974. parse( json ) {
  26975. const textures = this.textures;
  26976. function getTexture( name ) {
  26977. if ( textures[ name ] === undefined ) {
  26978. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26979. }
  26980. return textures[ name ];
  26981. }
  26982. const material = MaterialLoader.createMaterialFromType( json.type );
  26983. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26984. if ( json.name !== undefined ) material.name = json.name;
  26985. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  26986. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26987. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26988. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  26989. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  26990. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  26991. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26992. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  26993. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  26994. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  26995. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26996. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  26997. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  26998. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  26999. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  27000. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  27001. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  27002. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  27003. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  27004. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  27005. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  27006. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  27007. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  27008. if ( json.fog !== undefined ) material.fog = json.fog;
  27009. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  27010. if ( json.blending !== undefined ) material.blending = json.blending;
  27011. if ( json.combine !== undefined ) material.combine = json.combine;
  27012. if ( json.side !== undefined ) material.side = json.side;
  27013. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  27014. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  27015. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  27016. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  27017. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  27018. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  27019. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  27020. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  27021. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  27022. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  27023. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  27024. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  27025. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  27026. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  27027. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  27028. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  27029. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  27030. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  27031. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  27032. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  27033. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  27034. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  27035. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  27036. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  27037. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  27038. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  27039. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  27040. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  27041. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  27042. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  27043. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  27044. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  27045. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  27046. if ( json.scale !== undefined ) material.scale = json.scale;
  27047. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  27048. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  27049. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  27050. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  27051. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  27052. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  27053. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  27054. if ( json.visible !== undefined ) material.visible = json.visible;
  27055. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  27056. if ( json.userData !== undefined ) material.userData = json.userData;
  27057. if ( json.vertexColors !== undefined ) {
  27058. if ( typeof json.vertexColors === 'number' ) {
  27059. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  27060. } else {
  27061. material.vertexColors = json.vertexColors;
  27062. }
  27063. }
  27064. // Shader Material
  27065. if ( json.uniforms !== undefined ) {
  27066. for ( const name in json.uniforms ) {
  27067. const uniform = json.uniforms[ name ];
  27068. material.uniforms[ name ] = {};
  27069. switch ( uniform.type ) {
  27070. case 't':
  27071. material.uniforms[ name ].value = getTexture( uniform.value );
  27072. break;
  27073. case 'c':
  27074. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  27075. break;
  27076. case 'v2':
  27077. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  27078. break;
  27079. case 'v3':
  27080. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  27081. break;
  27082. case 'v4':
  27083. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  27084. break;
  27085. case 'm3':
  27086. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  27087. break;
  27088. case 'm4':
  27089. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  27090. break;
  27091. default:
  27092. material.uniforms[ name ].value = uniform.value;
  27093. }
  27094. }
  27095. }
  27096. if ( json.defines !== undefined ) material.defines = json.defines;
  27097. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  27098. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  27099. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  27100. if ( json.extensions !== undefined ) {
  27101. for ( const key in json.extensions ) {
  27102. material.extensions[ key ] = json.extensions[ key ];
  27103. }
  27104. }
  27105. if ( json.lights !== undefined ) material.lights = json.lights;
  27106. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  27107. // for PointsMaterial
  27108. if ( json.size !== undefined ) material.size = json.size;
  27109. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  27110. // maps
  27111. if ( json.map !== undefined ) material.map = getTexture( json.map );
  27112. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  27113. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  27114. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  27115. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  27116. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  27117. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  27118. if ( json.normalScale !== undefined ) {
  27119. let normalScale = json.normalScale;
  27120. if ( Array.isArray( normalScale ) === false ) {
  27121. // Blender exporter used to export a scalar. See #7459
  27122. normalScale = [ normalScale, normalScale ];
  27123. }
  27124. material.normalScale = new Vector2().fromArray( normalScale );
  27125. }
  27126. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  27127. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  27128. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  27129. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  27130. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  27131. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  27132. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  27133. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  27134. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  27135. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  27136. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  27137. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  27138. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  27139. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  27140. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  27141. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  27142. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  27143. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  27144. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  27145. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  27146. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  27147. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  27148. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  27149. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  27150. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  27151. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  27152. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  27153. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  27154. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  27155. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  27156. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  27157. return material;
  27158. }
  27159. setTextures( value ) {
  27160. this.textures = value;
  27161. return this;
  27162. }
  27163. static createMaterialFromType( type ) {
  27164. const materialLib = {
  27165. ShadowMaterial,
  27166. SpriteMaterial,
  27167. RawShaderMaterial,
  27168. ShaderMaterial,
  27169. PointsMaterial,
  27170. MeshPhysicalMaterial,
  27171. MeshStandardMaterial,
  27172. MeshPhongMaterial,
  27173. MeshToonMaterial,
  27174. MeshNormalMaterial,
  27175. MeshLambertMaterial,
  27176. MeshDepthMaterial,
  27177. MeshDistanceMaterial,
  27178. MeshBasicMaterial,
  27179. MeshMatcapMaterial,
  27180. LineDashedMaterial,
  27181. LineBasicMaterial,
  27182. Material
  27183. };
  27184. return new materialLib[ type ]();
  27185. }
  27186. }
  27187. class LoaderUtils {
  27188. static decodeText( array ) { // @deprecated, r165
  27189. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  27190. if ( typeof TextDecoder !== 'undefined' ) {
  27191. return new TextDecoder().decode( array );
  27192. }
  27193. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  27194. // throws a "maximum call stack size exceeded" error for large arrays.
  27195. let s = '';
  27196. for ( let i = 0, il = array.length; i < il; i ++ ) {
  27197. // Implicitly assumes little-endian.
  27198. s += String.fromCharCode( array[ i ] );
  27199. }
  27200. try {
  27201. // merges multi-byte utf-8 characters.
  27202. return decodeURIComponent( escape( s ) );
  27203. } catch ( e ) { // see #16358
  27204. return s;
  27205. }
  27206. }
  27207. static extractUrlBase( url ) {
  27208. const index = url.lastIndexOf( '/' );
  27209. if ( index === - 1 ) return './';
  27210. return url.slice( 0, index + 1 );
  27211. }
  27212. static resolveURL( url, path ) {
  27213. // Invalid URL
  27214. if ( typeof url !== 'string' || url === '' ) return '';
  27215. // Host Relative URL
  27216. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  27217. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  27218. }
  27219. // Absolute URL http://,https://,//
  27220. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  27221. // Data URI
  27222. if ( /^data:.*,.*$/i.test( url ) ) return url;
  27223. // Blob URL
  27224. if ( /^blob:.*$/i.test( url ) ) return url;
  27225. // Relative URL
  27226. return path + url;
  27227. }
  27228. }
  27229. class InstancedBufferGeometry extends BufferGeometry {
  27230. constructor() {
  27231. super();
  27232. this.isInstancedBufferGeometry = true;
  27233. this.type = 'InstancedBufferGeometry';
  27234. this.instanceCount = Infinity;
  27235. }
  27236. copy( source ) {
  27237. super.copy( source );
  27238. this.instanceCount = source.instanceCount;
  27239. return this;
  27240. }
  27241. toJSON() {
  27242. const data = super.toJSON();
  27243. data.instanceCount = this.instanceCount;
  27244. data.isInstancedBufferGeometry = true;
  27245. return data;
  27246. }
  27247. }
  27248. class BufferGeometryLoader extends Loader {
  27249. constructor( manager ) {
  27250. super( manager );
  27251. }
  27252. load( url, onLoad, onProgress, onError ) {
  27253. const scope = this;
  27254. const loader = new FileLoader( scope.manager );
  27255. loader.setPath( scope.path );
  27256. loader.setRequestHeader( scope.requestHeader );
  27257. loader.setWithCredentials( scope.withCredentials );
  27258. loader.load( url, function ( text ) {
  27259. try {
  27260. onLoad( scope.parse( JSON.parse( text ) ) );
  27261. } catch ( e ) {
  27262. if ( onError ) {
  27263. onError( e );
  27264. } else {
  27265. console.error( e );
  27266. }
  27267. scope.manager.itemError( url );
  27268. }
  27269. }, onProgress, onError );
  27270. }
  27271. parse( json ) {
  27272. const interleavedBufferMap = {};
  27273. const arrayBufferMap = {};
  27274. function getInterleavedBuffer( json, uuid ) {
  27275. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  27276. const interleavedBuffers = json.interleavedBuffers;
  27277. const interleavedBuffer = interleavedBuffers[ uuid ];
  27278. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  27279. const array = getTypedArray( interleavedBuffer.type, buffer );
  27280. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  27281. ib.uuid = interleavedBuffer.uuid;
  27282. interleavedBufferMap[ uuid ] = ib;
  27283. return ib;
  27284. }
  27285. function getArrayBuffer( json, uuid ) {
  27286. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  27287. const arrayBuffers = json.arrayBuffers;
  27288. const arrayBuffer = arrayBuffers[ uuid ];
  27289. const ab = new Uint32Array( arrayBuffer ).buffer;
  27290. arrayBufferMap[ uuid ] = ab;
  27291. return ab;
  27292. }
  27293. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  27294. const index = json.data.index;
  27295. if ( index !== undefined ) {
  27296. const typedArray = getTypedArray( index.type, index.array );
  27297. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  27298. }
  27299. const attributes = json.data.attributes;
  27300. for ( const key in attributes ) {
  27301. const attribute = attributes[ key ];
  27302. let bufferAttribute;
  27303. if ( attribute.isInterleavedBufferAttribute ) {
  27304. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27305. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27306. } else {
  27307. const typedArray = getTypedArray( attribute.type, attribute.array );
  27308. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  27309. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  27310. }
  27311. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27312. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  27313. geometry.setAttribute( key, bufferAttribute );
  27314. }
  27315. const morphAttributes = json.data.morphAttributes;
  27316. if ( morphAttributes ) {
  27317. for ( const key in morphAttributes ) {
  27318. const attributeArray = morphAttributes[ key ];
  27319. const array = [];
  27320. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  27321. const attribute = attributeArray[ i ];
  27322. let bufferAttribute;
  27323. if ( attribute.isInterleavedBufferAttribute ) {
  27324. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27325. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27326. } else {
  27327. const typedArray = getTypedArray( attribute.type, attribute.array );
  27328. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27329. }
  27330. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27331. array.push( bufferAttribute );
  27332. }
  27333. geometry.morphAttributes[ key ] = array;
  27334. }
  27335. }
  27336. const morphTargetsRelative = json.data.morphTargetsRelative;
  27337. if ( morphTargetsRelative ) {
  27338. geometry.morphTargetsRelative = true;
  27339. }
  27340. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  27341. if ( groups !== undefined ) {
  27342. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  27343. const group = groups[ i ];
  27344. geometry.addGroup( group.start, group.count, group.materialIndex );
  27345. }
  27346. }
  27347. const boundingSphere = json.data.boundingSphere;
  27348. if ( boundingSphere !== undefined ) {
  27349. const center = new Vector3();
  27350. if ( boundingSphere.center !== undefined ) {
  27351. center.fromArray( boundingSphere.center );
  27352. }
  27353. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  27354. }
  27355. if ( json.name ) geometry.name = json.name;
  27356. if ( json.userData ) geometry.userData = json.userData;
  27357. return geometry;
  27358. }
  27359. }
  27360. class ObjectLoader extends Loader {
  27361. constructor( manager ) {
  27362. super( manager );
  27363. }
  27364. load( url, onLoad, onProgress, onError ) {
  27365. const scope = this;
  27366. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27367. this.resourcePath = this.resourcePath || path;
  27368. const loader = new FileLoader( this.manager );
  27369. loader.setPath( this.path );
  27370. loader.setRequestHeader( this.requestHeader );
  27371. loader.setWithCredentials( this.withCredentials );
  27372. loader.load( url, function ( text ) {
  27373. let json = null;
  27374. try {
  27375. json = JSON.parse( text );
  27376. } catch ( error ) {
  27377. if ( onError !== undefined ) onError( error );
  27378. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  27379. return;
  27380. }
  27381. const metadata = json.metadata;
  27382. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27383. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  27384. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27385. return;
  27386. }
  27387. scope.parse( json, onLoad );
  27388. }, onProgress, onError );
  27389. }
  27390. async loadAsync( url, onProgress ) {
  27391. const scope = this;
  27392. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27393. this.resourcePath = this.resourcePath || path;
  27394. const loader = new FileLoader( this.manager );
  27395. loader.setPath( this.path );
  27396. loader.setRequestHeader( this.requestHeader );
  27397. loader.setWithCredentials( this.withCredentials );
  27398. const text = await loader.loadAsync( url, onProgress );
  27399. const json = JSON.parse( text );
  27400. const metadata = json.metadata;
  27401. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27402. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27403. }
  27404. return await scope.parseAsync( json );
  27405. }
  27406. parse( json, onLoad ) {
  27407. const animations = this.parseAnimations( json.animations );
  27408. const shapes = this.parseShapes( json.shapes );
  27409. const geometries = this.parseGeometries( json.geometries, shapes );
  27410. const images = this.parseImages( json.images, function () {
  27411. if ( onLoad !== undefined ) onLoad( object );
  27412. } );
  27413. const textures = this.parseTextures( json.textures, images );
  27414. const materials = this.parseMaterials( json.materials, textures );
  27415. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27416. const skeletons = this.parseSkeletons( json.skeletons, object );
  27417. this.bindSkeletons( object, skeletons );
  27418. //
  27419. if ( onLoad !== undefined ) {
  27420. let hasImages = false;
  27421. for ( const uuid in images ) {
  27422. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27423. hasImages = true;
  27424. break;
  27425. }
  27426. }
  27427. if ( hasImages === false ) onLoad( object );
  27428. }
  27429. return object;
  27430. }
  27431. async parseAsync( json ) {
  27432. const animations = this.parseAnimations( json.animations );
  27433. const shapes = this.parseShapes( json.shapes );
  27434. const geometries = this.parseGeometries( json.geometries, shapes );
  27435. const images = await this.parseImagesAsync( json.images );
  27436. const textures = this.parseTextures( json.textures, images );
  27437. const materials = this.parseMaterials( json.materials, textures );
  27438. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27439. const skeletons = this.parseSkeletons( json.skeletons, object );
  27440. this.bindSkeletons( object, skeletons );
  27441. return object;
  27442. }
  27443. parseShapes( json ) {
  27444. const shapes = {};
  27445. if ( json !== undefined ) {
  27446. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27447. const shape = new Shape().fromJSON( json[ i ] );
  27448. shapes[ shape.uuid ] = shape;
  27449. }
  27450. }
  27451. return shapes;
  27452. }
  27453. parseSkeletons( json, object ) {
  27454. const skeletons = {};
  27455. const bones = {};
  27456. // generate bone lookup table
  27457. object.traverse( function ( child ) {
  27458. if ( child.isBone ) bones[ child.uuid ] = child;
  27459. } );
  27460. // create skeletons
  27461. if ( json !== undefined ) {
  27462. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27463. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27464. skeletons[ skeleton.uuid ] = skeleton;
  27465. }
  27466. }
  27467. return skeletons;
  27468. }
  27469. parseGeometries( json, shapes ) {
  27470. const geometries = {};
  27471. if ( json !== undefined ) {
  27472. const bufferGeometryLoader = new BufferGeometryLoader();
  27473. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27474. let geometry;
  27475. const data = json[ i ];
  27476. switch ( data.type ) {
  27477. case 'BufferGeometry':
  27478. case 'InstancedBufferGeometry':
  27479. geometry = bufferGeometryLoader.parse( data );
  27480. break;
  27481. default:
  27482. if ( data.type in Geometries ) {
  27483. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27484. } else {
  27485. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27486. }
  27487. }
  27488. geometry.uuid = data.uuid;
  27489. if ( data.name !== undefined ) geometry.name = data.name;
  27490. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27491. geometries[ data.uuid ] = geometry;
  27492. }
  27493. }
  27494. return geometries;
  27495. }
  27496. parseMaterials( json, textures ) {
  27497. const cache = {}; // MultiMaterial
  27498. const materials = {};
  27499. if ( json !== undefined ) {
  27500. const loader = new MaterialLoader();
  27501. loader.setTextures( textures );
  27502. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27503. const data = json[ i ];
  27504. if ( cache[ data.uuid ] === undefined ) {
  27505. cache[ data.uuid ] = loader.parse( data );
  27506. }
  27507. materials[ data.uuid ] = cache[ data.uuid ];
  27508. }
  27509. }
  27510. return materials;
  27511. }
  27512. parseAnimations( json ) {
  27513. const animations = {};
  27514. if ( json !== undefined ) {
  27515. for ( let i = 0; i < json.length; i ++ ) {
  27516. const data = json[ i ];
  27517. const clip = AnimationClip.parse( data );
  27518. animations[ clip.uuid ] = clip;
  27519. }
  27520. }
  27521. return animations;
  27522. }
  27523. parseImages( json, onLoad ) {
  27524. const scope = this;
  27525. const images = {};
  27526. let loader;
  27527. function loadImage( url ) {
  27528. scope.manager.itemStart( url );
  27529. return loader.load( url, function () {
  27530. scope.manager.itemEnd( url );
  27531. }, undefined, function () {
  27532. scope.manager.itemError( url );
  27533. scope.manager.itemEnd( url );
  27534. } );
  27535. }
  27536. function deserializeImage( image ) {
  27537. if ( typeof image === 'string' ) {
  27538. const url = image;
  27539. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27540. return loadImage( path );
  27541. } else {
  27542. if ( image.data ) {
  27543. return {
  27544. data: getTypedArray( image.type, image.data ),
  27545. width: image.width,
  27546. height: image.height
  27547. };
  27548. } else {
  27549. return null;
  27550. }
  27551. }
  27552. }
  27553. if ( json !== undefined && json.length > 0 ) {
  27554. const manager = new LoadingManager( onLoad );
  27555. loader = new ImageLoader( manager );
  27556. loader.setCrossOrigin( this.crossOrigin );
  27557. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27558. const image = json[ i ];
  27559. const url = image.url;
  27560. if ( Array.isArray( url ) ) {
  27561. // load array of images e.g CubeTexture
  27562. const imageArray = [];
  27563. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27564. const currentUrl = url[ j ];
  27565. const deserializedImage = deserializeImage( currentUrl );
  27566. if ( deserializedImage !== null ) {
  27567. if ( deserializedImage instanceof HTMLImageElement ) {
  27568. imageArray.push( deserializedImage );
  27569. } else {
  27570. // special case: handle array of data textures for cube textures
  27571. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27572. }
  27573. }
  27574. }
  27575. images[ image.uuid ] = new Source( imageArray );
  27576. } else {
  27577. // load single image
  27578. const deserializedImage = deserializeImage( image.url );
  27579. images[ image.uuid ] = new Source( deserializedImage );
  27580. }
  27581. }
  27582. }
  27583. return images;
  27584. }
  27585. async parseImagesAsync( json ) {
  27586. const scope = this;
  27587. const images = {};
  27588. let loader;
  27589. async function deserializeImage( image ) {
  27590. if ( typeof image === 'string' ) {
  27591. const url = image;
  27592. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27593. return await loader.loadAsync( path );
  27594. } else {
  27595. if ( image.data ) {
  27596. return {
  27597. data: getTypedArray( image.type, image.data ),
  27598. width: image.width,
  27599. height: image.height
  27600. };
  27601. } else {
  27602. return null;
  27603. }
  27604. }
  27605. }
  27606. if ( json !== undefined && json.length > 0 ) {
  27607. loader = new ImageLoader( this.manager );
  27608. loader.setCrossOrigin( this.crossOrigin );
  27609. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27610. const image = json[ i ];
  27611. const url = image.url;
  27612. if ( Array.isArray( url ) ) {
  27613. // load array of images e.g CubeTexture
  27614. const imageArray = [];
  27615. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27616. const currentUrl = url[ j ];
  27617. const deserializedImage = await deserializeImage( currentUrl );
  27618. if ( deserializedImage !== null ) {
  27619. if ( deserializedImage instanceof HTMLImageElement ) {
  27620. imageArray.push( deserializedImage );
  27621. } else {
  27622. // special case: handle array of data textures for cube textures
  27623. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27624. }
  27625. }
  27626. }
  27627. images[ image.uuid ] = new Source( imageArray );
  27628. } else {
  27629. // load single image
  27630. const deserializedImage = await deserializeImage( image.url );
  27631. images[ image.uuid ] = new Source( deserializedImage );
  27632. }
  27633. }
  27634. }
  27635. return images;
  27636. }
  27637. parseTextures( json, images ) {
  27638. function parseConstant( value, type ) {
  27639. if ( typeof value === 'number' ) return value;
  27640. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27641. return type[ value ];
  27642. }
  27643. const textures = {};
  27644. if ( json !== undefined ) {
  27645. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27646. const data = json[ i ];
  27647. if ( data.image === undefined ) {
  27648. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27649. }
  27650. if ( images[ data.image ] === undefined ) {
  27651. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27652. }
  27653. const source = images[ data.image ];
  27654. const image = source.data;
  27655. let texture;
  27656. if ( Array.isArray( image ) ) {
  27657. texture = new CubeTexture();
  27658. if ( image.length === 6 ) texture.needsUpdate = true;
  27659. } else {
  27660. if ( image && image.data ) {
  27661. texture = new DataTexture();
  27662. } else {
  27663. texture = new Texture();
  27664. }
  27665. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27666. }
  27667. texture.source = source;
  27668. texture.uuid = data.uuid;
  27669. if ( data.name !== undefined ) texture.name = data.name;
  27670. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27671. if ( data.channel !== undefined ) texture.channel = data.channel;
  27672. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27673. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27674. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27675. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27676. if ( data.wrap !== undefined ) {
  27677. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27678. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27679. }
  27680. if ( data.format !== undefined ) texture.format = data.format;
  27681. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27682. if ( data.type !== undefined ) texture.type = data.type;
  27683. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27684. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27685. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27686. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27687. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27688. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27689. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27690. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27691. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27692. if ( data.userData !== undefined ) texture.userData = data.userData;
  27693. textures[ data.uuid ] = texture;
  27694. }
  27695. }
  27696. return textures;
  27697. }
  27698. parseObject( data, geometries, materials, textures, animations ) {
  27699. let object;
  27700. function getGeometry( name ) {
  27701. if ( geometries[ name ] === undefined ) {
  27702. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27703. }
  27704. return geometries[ name ];
  27705. }
  27706. function getMaterial( name ) {
  27707. if ( name === undefined ) return undefined;
  27708. if ( Array.isArray( name ) ) {
  27709. const array = [];
  27710. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27711. const uuid = name[ i ];
  27712. if ( materials[ uuid ] === undefined ) {
  27713. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27714. }
  27715. array.push( materials[ uuid ] );
  27716. }
  27717. return array;
  27718. }
  27719. if ( materials[ name ] === undefined ) {
  27720. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27721. }
  27722. return materials[ name ];
  27723. }
  27724. function getTexture( uuid ) {
  27725. if ( textures[ uuid ] === undefined ) {
  27726. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27727. }
  27728. return textures[ uuid ];
  27729. }
  27730. let geometry, material;
  27731. switch ( data.type ) {
  27732. case 'Scene':
  27733. object = new Scene();
  27734. if ( data.background !== undefined ) {
  27735. if ( Number.isInteger( data.background ) ) {
  27736. object.background = new Color( data.background );
  27737. } else {
  27738. object.background = getTexture( data.background );
  27739. }
  27740. }
  27741. if ( data.environment !== undefined ) {
  27742. object.environment = getTexture( data.environment );
  27743. }
  27744. if ( data.fog !== undefined ) {
  27745. if ( data.fog.type === 'Fog' ) {
  27746. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27747. } else if ( data.fog.type === 'FogExp2' ) {
  27748. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27749. }
  27750. if ( data.fog.name !== '' ) {
  27751. object.fog.name = data.fog.name;
  27752. }
  27753. }
  27754. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27755. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27756. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  27757. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  27758. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  27759. break;
  27760. case 'PerspectiveCamera':
  27761. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27762. if ( data.focus !== undefined ) object.focus = data.focus;
  27763. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27764. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27765. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27766. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27767. break;
  27768. case 'OrthographicCamera':
  27769. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27770. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27771. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27772. break;
  27773. case 'AmbientLight':
  27774. object = new AmbientLight( data.color, data.intensity );
  27775. break;
  27776. case 'DirectionalLight':
  27777. object = new DirectionalLight( data.color, data.intensity );
  27778. break;
  27779. case 'PointLight':
  27780. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27781. break;
  27782. case 'RectAreaLight':
  27783. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27784. break;
  27785. case 'SpotLight':
  27786. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27787. break;
  27788. case 'HemisphereLight':
  27789. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27790. break;
  27791. case 'LightProbe':
  27792. object = new LightProbe().fromJSON( data );
  27793. break;
  27794. case 'SkinnedMesh':
  27795. geometry = getGeometry( data.geometry );
  27796. material = getMaterial( data.material );
  27797. object = new SkinnedMesh( geometry, material );
  27798. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27799. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27800. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27801. break;
  27802. case 'Mesh':
  27803. geometry = getGeometry( data.geometry );
  27804. material = getMaterial( data.material );
  27805. object = new Mesh( geometry, material );
  27806. break;
  27807. case 'InstancedMesh':
  27808. geometry = getGeometry( data.geometry );
  27809. material = getMaterial( data.material );
  27810. const count = data.count;
  27811. const instanceMatrix = data.instanceMatrix;
  27812. const instanceColor = data.instanceColor;
  27813. object = new InstancedMesh( geometry, material, count );
  27814. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27815. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27816. break;
  27817. case 'BatchedMesh':
  27818. geometry = getGeometry( data.geometry );
  27819. material = getMaterial( data.material );
  27820. object = new BatchedMesh( data.maxGeometryCount, data.maxVertexCount, data.maxIndexCount, material );
  27821. object.geometry = geometry;
  27822. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  27823. object.sortObjects = data.sortObjects;
  27824. object._drawRanges = data.drawRanges;
  27825. object._reservedRanges = data.reservedRanges;
  27826. object._visibility = data.visibility;
  27827. object._active = data.active;
  27828. object._bounds = data.bounds.map( bound => {
  27829. const box = new Box3();
  27830. box.min.fromArray( bound.boxMin );
  27831. box.max.fromArray( bound.boxMax );
  27832. const sphere = new Sphere();
  27833. sphere.radius = bound.sphereRadius;
  27834. sphere.center.fromArray( bound.sphereCenter );
  27835. return {
  27836. boxInitialized: bound.boxInitialized,
  27837. box: box,
  27838. sphereInitialized: bound.sphereInitialized,
  27839. sphere: sphere
  27840. };
  27841. } );
  27842. object._maxGeometryCount = data.maxGeometryCount;
  27843. object._maxVertexCount = data.maxVertexCount;
  27844. object._maxIndexCount = data.maxIndexCount;
  27845. object._geometryInitialized = data.geometryInitialized;
  27846. object._geometryCount = data.geometryCount;
  27847. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  27848. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  27849. break;
  27850. case 'LOD':
  27851. object = new LOD();
  27852. break;
  27853. case 'Line':
  27854. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  27855. break;
  27856. case 'LineLoop':
  27857. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27858. break;
  27859. case 'LineSegments':
  27860. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27861. break;
  27862. case 'PointCloud':
  27863. case 'Points':
  27864. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27865. break;
  27866. case 'Sprite':
  27867. object = new Sprite( getMaterial( data.material ) );
  27868. break;
  27869. case 'Group':
  27870. object = new Group();
  27871. break;
  27872. case 'Bone':
  27873. object = new Bone();
  27874. break;
  27875. default:
  27876. object = new Object3D();
  27877. }
  27878. object.uuid = data.uuid;
  27879. if ( data.name !== undefined ) object.name = data.name;
  27880. if ( data.matrix !== undefined ) {
  27881. object.matrix.fromArray( data.matrix );
  27882. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27883. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27884. } else {
  27885. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27886. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27887. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27888. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27889. }
  27890. if ( data.up !== undefined ) object.up.fromArray( data.up );
  27891. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27892. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27893. if ( data.shadow ) {
  27894. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27895. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  27896. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27897. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27898. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27899. }
  27900. if ( data.visible !== undefined ) object.visible = data.visible;
  27901. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27902. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27903. if ( data.userData !== undefined ) object.userData = data.userData;
  27904. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27905. if ( data.children !== undefined ) {
  27906. const children = data.children;
  27907. for ( let i = 0; i < children.length; i ++ ) {
  27908. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  27909. }
  27910. }
  27911. if ( data.animations !== undefined ) {
  27912. const objectAnimations = data.animations;
  27913. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  27914. const uuid = objectAnimations[ i ];
  27915. object.animations.push( animations[ uuid ] );
  27916. }
  27917. }
  27918. if ( data.type === 'LOD' ) {
  27919. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  27920. const levels = data.levels;
  27921. for ( let l = 0; l < levels.length; l ++ ) {
  27922. const level = levels[ l ];
  27923. const child = object.getObjectByProperty( 'uuid', level.object );
  27924. if ( child !== undefined ) {
  27925. object.addLevel( child, level.distance, level.hysteresis );
  27926. }
  27927. }
  27928. }
  27929. return object;
  27930. }
  27931. bindSkeletons( object, skeletons ) {
  27932. if ( Object.keys( skeletons ).length === 0 ) return;
  27933. object.traverse( function ( child ) {
  27934. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  27935. const skeleton = skeletons[ child.skeleton ];
  27936. if ( skeleton === undefined ) {
  27937. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  27938. } else {
  27939. child.bind( skeleton, child.bindMatrix );
  27940. }
  27941. }
  27942. } );
  27943. }
  27944. }
  27945. const TEXTURE_MAPPING = {
  27946. UVMapping: UVMapping,
  27947. CubeReflectionMapping: CubeReflectionMapping,
  27948. CubeRefractionMapping: CubeRefractionMapping,
  27949. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27950. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27951. CubeUVReflectionMapping: CubeUVReflectionMapping
  27952. };
  27953. const TEXTURE_WRAPPING = {
  27954. RepeatWrapping: RepeatWrapping,
  27955. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27956. MirroredRepeatWrapping: MirroredRepeatWrapping
  27957. };
  27958. const TEXTURE_FILTER = {
  27959. NearestFilter: NearestFilter,
  27960. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  27961. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  27962. LinearFilter: LinearFilter,
  27963. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  27964. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  27965. };
  27966. class ImageBitmapLoader extends Loader {
  27967. constructor( manager ) {
  27968. super( manager );
  27969. this.isImageBitmapLoader = true;
  27970. if ( typeof createImageBitmap === 'undefined' ) {
  27971. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27972. }
  27973. if ( typeof fetch === 'undefined' ) {
  27974. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27975. }
  27976. this.options = { premultiplyAlpha: 'none' };
  27977. }
  27978. setOptions( options ) {
  27979. this.options = options;
  27980. return this;
  27981. }
  27982. load( url, onLoad, onProgress, onError ) {
  27983. if ( url === undefined ) url = '';
  27984. if ( this.path !== undefined ) url = this.path + url;
  27985. url = this.manager.resolveURL( url );
  27986. const scope = this;
  27987. const cached = Cache.get( url );
  27988. if ( cached !== undefined ) {
  27989. scope.manager.itemStart( url );
  27990. // If cached is a promise, wait for it to resolve
  27991. if ( cached.then ) {
  27992. cached.then( imageBitmap => {
  27993. if ( onLoad ) onLoad( imageBitmap );
  27994. scope.manager.itemEnd( url );
  27995. } ).catch( e => {
  27996. if ( onError ) onError( e );
  27997. } );
  27998. return;
  27999. }
  28000. // If cached is not a promise (i.e., it's already an imageBitmap)
  28001. setTimeout( function () {
  28002. if ( onLoad ) onLoad( cached );
  28003. scope.manager.itemEnd( url );
  28004. }, 0 );
  28005. return cached;
  28006. }
  28007. const fetchOptions = {};
  28008. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  28009. fetchOptions.headers = this.requestHeader;
  28010. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  28011. return res.blob();
  28012. } ).then( function ( blob ) {
  28013. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  28014. } ).then( function ( imageBitmap ) {
  28015. Cache.add( url, imageBitmap );
  28016. if ( onLoad ) onLoad( imageBitmap );
  28017. scope.manager.itemEnd( url );
  28018. return imageBitmap;
  28019. } ).catch( function ( e ) {
  28020. if ( onError ) onError( e );
  28021. Cache.remove( url );
  28022. scope.manager.itemError( url );
  28023. scope.manager.itemEnd( url );
  28024. } );
  28025. Cache.add( url, promise );
  28026. scope.manager.itemStart( url );
  28027. }
  28028. }
  28029. let _context;
  28030. class AudioContext {
  28031. static getContext() {
  28032. if ( _context === undefined ) {
  28033. _context = new ( window.AudioContext || window.webkitAudioContext )();
  28034. }
  28035. return _context;
  28036. }
  28037. static setContext( value ) {
  28038. _context = value;
  28039. }
  28040. }
  28041. class AudioLoader extends Loader {
  28042. constructor( manager ) {
  28043. super( manager );
  28044. }
  28045. load( url, onLoad, onProgress, onError ) {
  28046. const scope = this;
  28047. const loader = new FileLoader( this.manager );
  28048. loader.setResponseType( 'arraybuffer' );
  28049. loader.setPath( this.path );
  28050. loader.setRequestHeader( this.requestHeader );
  28051. loader.setWithCredentials( this.withCredentials );
  28052. loader.load( url, function ( buffer ) {
  28053. try {
  28054. // Create a copy of the buffer. The `decodeAudioData` method
  28055. // detaches the buffer when complete, preventing reuse.
  28056. const bufferCopy = buffer.slice( 0 );
  28057. const context = AudioContext.getContext();
  28058. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  28059. onLoad( audioBuffer );
  28060. } ).catch( handleError );
  28061. } catch ( e ) {
  28062. handleError( e );
  28063. }
  28064. }, onProgress, onError );
  28065. function handleError( e ) {
  28066. if ( onError ) {
  28067. onError( e );
  28068. } else {
  28069. console.error( e );
  28070. }
  28071. scope.manager.itemError( url );
  28072. }
  28073. }
  28074. }
  28075. const _eyeRight = /*@__PURE__*/ new Matrix4();
  28076. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  28077. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  28078. class StereoCamera {
  28079. constructor() {
  28080. this.type = 'StereoCamera';
  28081. this.aspect = 1;
  28082. this.eyeSep = 0.064;
  28083. this.cameraL = new PerspectiveCamera();
  28084. this.cameraL.layers.enable( 1 );
  28085. this.cameraL.matrixAutoUpdate = false;
  28086. this.cameraR = new PerspectiveCamera();
  28087. this.cameraR.layers.enable( 2 );
  28088. this.cameraR.matrixAutoUpdate = false;
  28089. this._cache = {
  28090. focus: null,
  28091. fov: null,
  28092. aspect: null,
  28093. near: null,
  28094. far: null,
  28095. zoom: null,
  28096. eyeSep: null
  28097. };
  28098. }
  28099. update( camera ) {
  28100. const cache = this._cache;
  28101. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  28102. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  28103. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  28104. if ( needsUpdate ) {
  28105. cache.focus = camera.focus;
  28106. cache.fov = camera.fov;
  28107. cache.aspect = camera.aspect * this.aspect;
  28108. cache.near = camera.near;
  28109. cache.far = camera.far;
  28110. cache.zoom = camera.zoom;
  28111. cache.eyeSep = this.eyeSep;
  28112. // Off-axis stereoscopic effect based on
  28113. // http://paulbourke.net/stereographics/stereorender/
  28114. _projectionMatrix.copy( camera.projectionMatrix );
  28115. const eyeSepHalf = cache.eyeSep / 2;
  28116. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  28117. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  28118. let xmin, xmax;
  28119. // translate xOffset
  28120. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  28121. _eyeRight.elements[ 12 ] = eyeSepHalf;
  28122. // for left eye
  28123. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  28124. xmax = ymax * cache.aspect + eyeSepOnProjection;
  28125. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  28126. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28127. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  28128. // for right eye
  28129. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  28130. xmax = ymax * cache.aspect - eyeSepOnProjection;
  28131. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  28132. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28133. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  28134. }
  28135. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  28136. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  28137. }
  28138. }
  28139. class Clock {
  28140. constructor( autoStart = true ) {
  28141. this.autoStart = autoStart;
  28142. this.startTime = 0;
  28143. this.oldTime = 0;
  28144. this.elapsedTime = 0;
  28145. this.running = false;
  28146. }
  28147. start() {
  28148. this.startTime = now();
  28149. this.oldTime = this.startTime;
  28150. this.elapsedTime = 0;
  28151. this.running = true;
  28152. }
  28153. stop() {
  28154. this.getElapsedTime();
  28155. this.running = false;
  28156. this.autoStart = false;
  28157. }
  28158. getElapsedTime() {
  28159. this.getDelta();
  28160. return this.elapsedTime;
  28161. }
  28162. getDelta() {
  28163. let diff = 0;
  28164. if ( this.autoStart && ! this.running ) {
  28165. this.start();
  28166. return 0;
  28167. }
  28168. if ( this.running ) {
  28169. const newTime = now();
  28170. diff = ( newTime - this.oldTime ) / 1000;
  28171. this.oldTime = newTime;
  28172. this.elapsedTime += diff;
  28173. }
  28174. return diff;
  28175. }
  28176. }
  28177. function now() {
  28178. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  28179. }
  28180. const _position$1 = /*@__PURE__*/ new Vector3();
  28181. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  28182. const _scale$1 = /*@__PURE__*/ new Vector3();
  28183. const _orientation$1 = /*@__PURE__*/ new Vector3();
  28184. class AudioListener extends Object3D {
  28185. constructor() {
  28186. super();
  28187. this.type = 'AudioListener';
  28188. this.context = AudioContext.getContext();
  28189. this.gain = this.context.createGain();
  28190. this.gain.connect( this.context.destination );
  28191. this.filter = null;
  28192. this.timeDelta = 0;
  28193. // private
  28194. this._clock = new Clock();
  28195. }
  28196. getInput() {
  28197. return this.gain;
  28198. }
  28199. removeFilter() {
  28200. if ( this.filter !== null ) {
  28201. this.gain.disconnect( this.filter );
  28202. this.filter.disconnect( this.context.destination );
  28203. this.gain.connect( this.context.destination );
  28204. this.filter = null;
  28205. }
  28206. return this;
  28207. }
  28208. getFilter() {
  28209. return this.filter;
  28210. }
  28211. setFilter( value ) {
  28212. if ( this.filter !== null ) {
  28213. this.gain.disconnect( this.filter );
  28214. this.filter.disconnect( this.context.destination );
  28215. } else {
  28216. this.gain.disconnect( this.context.destination );
  28217. }
  28218. this.filter = value;
  28219. this.gain.connect( this.filter );
  28220. this.filter.connect( this.context.destination );
  28221. return this;
  28222. }
  28223. getMasterVolume() {
  28224. return this.gain.gain.value;
  28225. }
  28226. setMasterVolume( value ) {
  28227. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28228. return this;
  28229. }
  28230. updateMatrixWorld( force ) {
  28231. super.updateMatrixWorld( force );
  28232. const listener = this.context.listener;
  28233. const up = this.up;
  28234. this.timeDelta = this._clock.getDelta();
  28235. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  28236. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  28237. if ( listener.positionX ) {
  28238. // code path for Chrome (see #14393)
  28239. const endTime = this.context.currentTime + this.timeDelta;
  28240. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  28241. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  28242. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  28243. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  28244. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  28245. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  28246. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28247. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28248. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28249. } else {
  28250. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  28251. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  28252. }
  28253. }
  28254. }
  28255. class Audio extends Object3D {
  28256. constructor( listener ) {
  28257. super();
  28258. this.type = 'Audio';
  28259. this.listener = listener;
  28260. this.context = listener.context;
  28261. this.gain = this.context.createGain();
  28262. this.gain.connect( listener.getInput() );
  28263. this.autoplay = false;
  28264. this.buffer = null;
  28265. this.detune = 0;
  28266. this.loop = false;
  28267. this.loopStart = 0;
  28268. this.loopEnd = 0;
  28269. this.offset = 0;
  28270. this.duration = undefined;
  28271. this.playbackRate = 1;
  28272. this.isPlaying = false;
  28273. this.hasPlaybackControl = true;
  28274. this.source = null;
  28275. this.sourceType = 'empty';
  28276. this._startedAt = 0;
  28277. this._progress = 0;
  28278. this._connected = false;
  28279. this.filters = [];
  28280. }
  28281. getOutput() {
  28282. return this.gain;
  28283. }
  28284. setNodeSource( audioNode ) {
  28285. this.hasPlaybackControl = false;
  28286. this.sourceType = 'audioNode';
  28287. this.source = audioNode;
  28288. this.connect();
  28289. return this;
  28290. }
  28291. setMediaElementSource( mediaElement ) {
  28292. this.hasPlaybackControl = false;
  28293. this.sourceType = 'mediaNode';
  28294. this.source = this.context.createMediaElementSource( mediaElement );
  28295. this.connect();
  28296. return this;
  28297. }
  28298. setMediaStreamSource( mediaStream ) {
  28299. this.hasPlaybackControl = false;
  28300. this.sourceType = 'mediaStreamNode';
  28301. this.source = this.context.createMediaStreamSource( mediaStream );
  28302. this.connect();
  28303. return this;
  28304. }
  28305. setBuffer( audioBuffer ) {
  28306. this.buffer = audioBuffer;
  28307. this.sourceType = 'buffer';
  28308. if ( this.autoplay ) this.play();
  28309. return this;
  28310. }
  28311. play( delay = 0 ) {
  28312. if ( this.isPlaying === true ) {
  28313. console.warn( 'THREE.Audio: Audio is already playing.' );
  28314. return;
  28315. }
  28316. if ( this.hasPlaybackControl === false ) {
  28317. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28318. return;
  28319. }
  28320. this._startedAt = this.context.currentTime + delay;
  28321. const source = this.context.createBufferSource();
  28322. source.buffer = this.buffer;
  28323. source.loop = this.loop;
  28324. source.loopStart = this.loopStart;
  28325. source.loopEnd = this.loopEnd;
  28326. source.onended = this.onEnded.bind( this );
  28327. source.start( this._startedAt, this._progress + this.offset, this.duration );
  28328. this.isPlaying = true;
  28329. this.source = source;
  28330. this.setDetune( this.detune );
  28331. this.setPlaybackRate( this.playbackRate );
  28332. return this.connect();
  28333. }
  28334. pause() {
  28335. if ( this.hasPlaybackControl === false ) {
  28336. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28337. return;
  28338. }
  28339. if ( this.isPlaying === true ) {
  28340. // update current progress
  28341. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  28342. if ( this.loop === true ) {
  28343. // ensure _progress does not exceed duration with looped audios
  28344. this._progress = this._progress % ( this.duration || this.buffer.duration );
  28345. }
  28346. this.source.stop();
  28347. this.source.onended = null;
  28348. this.isPlaying = false;
  28349. }
  28350. return this;
  28351. }
  28352. stop() {
  28353. if ( this.hasPlaybackControl === false ) {
  28354. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28355. return;
  28356. }
  28357. this._progress = 0;
  28358. if ( this.source !== null ) {
  28359. this.source.stop();
  28360. this.source.onended = null;
  28361. }
  28362. this.isPlaying = false;
  28363. return this;
  28364. }
  28365. connect() {
  28366. if ( this.filters.length > 0 ) {
  28367. this.source.connect( this.filters[ 0 ] );
  28368. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28369. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28370. }
  28371. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28372. } else {
  28373. this.source.connect( this.getOutput() );
  28374. }
  28375. this._connected = true;
  28376. return this;
  28377. }
  28378. disconnect() {
  28379. if ( this._connected === false ) {
  28380. return;
  28381. }
  28382. if ( this.filters.length > 0 ) {
  28383. this.source.disconnect( this.filters[ 0 ] );
  28384. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28385. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28386. }
  28387. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28388. } else {
  28389. this.source.disconnect( this.getOutput() );
  28390. }
  28391. this._connected = false;
  28392. return this;
  28393. }
  28394. getFilters() {
  28395. return this.filters;
  28396. }
  28397. setFilters( value ) {
  28398. if ( ! value ) value = [];
  28399. if ( this._connected === true ) {
  28400. this.disconnect();
  28401. this.filters = value.slice();
  28402. this.connect();
  28403. } else {
  28404. this.filters = value.slice();
  28405. }
  28406. return this;
  28407. }
  28408. setDetune( value ) {
  28409. this.detune = value;
  28410. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  28411. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28412. }
  28413. return this;
  28414. }
  28415. getDetune() {
  28416. return this.detune;
  28417. }
  28418. getFilter() {
  28419. return this.getFilters()[ 0 ];
  28420. }
  28421. setFilter( filter ) {
  28422. return this.setFilters( filter ? [ filter ] : [] );
  28423. }
  28424. setPlaybackRate( value ) {
  28425. if ( this.hasPlaybackControl === false ) {
  28426. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28427. return;
  28428. }
  28429. this.playbackRate = value;
  28430. if ( this.isPlaying === true ) {
  28431. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28432. }
  28433. return this;
  28434. }
  28435. getPlaybackRate() {
  28436. return this.playbackRate;
  28437. }
  28438. onEnded() {
  28439. this.isPlaying = false;
  28440. }
  28441. getLoop() {
  28442. if ( this.hasPlaybackControl === false ) {
  28443. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28444. return false;
  28445. }
  28446. return this.loop;
  28447. }
  28448. setLoop( value ) {
  28449. if ( this.hasPlaybackControl === false ) {
  28450. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28451. return;
  28452. }
  28453. this.loop = value;
  28454. if ( this.isPlaying === true ) {
  28455. this.source.loop = this.loop;
  28456. }
  28457. return this;
  28458. }
  28459. setLoopStart( value ) {
  28460. this.loopStart = value;
  28461. return this;
  28462. }
  28463. setLoopEnd( value ) {
  28464. this.loopEnd = value;
  28465. return this;
  28466. }
  28467. getVolume() {
  28468. return this.gain.gain.value;
  28469. }
  28470. setVolume( value ) {
  28471. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28472. return this;
  28473. }
  28474. }
  28475. const _position = /*@__PURE__*/ new Vector3();
  28476. const _quaternion = /*@__PURE__*/ new Quaternion();
  28477. const _scale = /*@__PURE__*/ new Vector3();
  28478. const _orientation = /*@__PURE__*/ new Vector3();
  28479. class PositionalAudio extends Audio {
  28480. constructor( listener ) {
  28481. super( listener );
  28482. this.panner = this.context.createPanner();
  28483. this.panner.panningModel = 'HRTF';
  28484. this.panner.connect( this.gain );
  28485. }
  28486. connect() {
  28487. super.connect();
  28488. this.panner.connect( this.gain );
  28489. }
  28490. disconnect() {
  28491. super.disconnect();
  28492. this.panner.disconnect( this.gain );
  28493. }
  28494. getOutput() {
  28495. return this.panner;
  28496. }
  28497. getRefDistance() {
  28498. return this.panner.refDistance;
  28499. }
  28500. setRefDistance( value ) {
  28501. this.panner.refDistance = value;
  28502. return this;
  28503. }
  28504. getRolloffFactor() {
  28505. return this.panner.rolloffFactor;
  28506. }
  28507. setRolloffFactor( value ) {
  28508. this.panner.rolloffFactor = value;
  28509. return this;
  28510. }
  28511. getDistanceModel() {
  28512. return this.panner.distanceModel;
  28513. }
  28514. setDistanceModel( value ) {
  28515. this.panner.distanceModel = value;
  28516. return this;
  28517. }
  28518. getMaxDistance() {
  28519. return this.panner.maxDistance;
  28520. }
  28521. setMaxDistance( value ) {
  28522. this.panner.maxDistance = value;
  28523. return this;
  28524. }
  28525. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28526. this.panner.coneInnerAngle = coneInnerAngle;
  28527. this.panner.coneOuterAngle = coneOuterAngle;
  28528. this.panner.coneOuterGain = coneOuterGain;
  28529. return this;
  28530. }
  28531. updateMatrixWorld( force ) {
  28532. super.updateMatrixWorld( force );
  28533. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28534. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28535. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28536. const panner = this.panner;
  28537. if ( panner.positionX ) {
  28538. // code path for Chrome and Firefox (see #14393)
  28539. const endTime = this.context.currentTime + this.listener.timeDelta;
  28540. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28541. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28542. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28543. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28544. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28545. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28546. } else {
  28547. panner.setPosition( _position.x, _position.y, _position.z );
  28548. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28549. }
  28550. }
  28551. }
  28552. class AudioAnalyser {
  28553. constructor( audio, fftSize = 2048 ) {
  28554. this.analyser = audio.context.createAnalyser();
  28555. this.analyser.fftSize = fftSize;
  28556. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28557. audio.getOutput().connect( this.analyser );
  28558. }
  28559. getFrequencyData() {
  28560. this.analyser.getByteFrequencyData( this.data );
  28561. return this.data;
  28562. }
  28563. getAverageFrequency() {
  28564. let value = 0;
  28565. const data = this.getFrequencyData();
  28566. for ( let i = 0; i < data.length; i ++ ) {
  28567. value += data[ i ];
  28568. }
  28569. return value / data.length;
  28570. }
  28571. }
  28572. class PropertyMixer {
  28573. constructor( binding, typeName, valueSize ) {
  28574. this.binding = binding;
  28575. this.valueSize = valueSize;
  28576. let mixFunction,
  28577. mixFunctionAdditive,
  28578. setIdentity;
  28579. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28580. //
  28581. // interpolators can use .buffer as their .result
  28582. // the data then goes to 'incoming'
  28583. //
  28584. // 'accu0' and 'accu1' are used frame-interleaved for
  28585. // the cumulative result and are compared to detect
  28586. // changes
  28587. //
  28588. // 'orig' stores the original state of the property
  28589. //
  28590. // 'add' is used for additive cumulative results
  28591. //
  28592. // 'work' is optional and is only present for quaternion types. It is used
  28593. // to store intermediate quaternion multiplication results
  28594. switch ( typeName ) {
  28595. case 'quaternion':
  28596. mixFunction = this._slerp;
  28597. mixFunctionAdditive = this._slerpAdditive;
  28598. setIdentity = this._setAdditiveIdentityQuaternion;
  28599. this.buffer = new Float64Array( valueSize * 6 );
  28600. this._workIndex = 5;
  28601. break;
  28602. case 'string':
  28603. case 'bool':
  28604. mixFunction = this._select;
  28605. // Use the regular mix function and for additive on these types,
  28606. // additive is not relevant for non-numeric types
  28607. mixFunctionAdditive = this._select;
  28608. setIdentity = this._setAdditiveIdentityOther;
  28609. this.buffer = new Array( valueSize * 5 );
  28610. break;
  28611. default:
  28612. mixFunction = this._lerp;
  28613. mixFunctionAdditive = this._lerpAdditive;
  28614. setIdentity = this._setAdditiveIdentityNumeric;
  28615. this.buffer = new Float64Array( valueSize * 5 );
  28616. }
  28617. this._mixBufferRegion = mixFunction;
  28618. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28619. this._setIdentity = setIdentity;
  28620. this._origIndex = 3;
  28621. this._addIndex = 4;
  28622. this.cumulativeWeight = 0;
  28623. this.cumulativeWeightAdditive = 0;
  28624. this.useCount = 0;
  28625. this.referenceCount = 0;
  28626. }
  28627. // accumulate data in the 'incoming' region into 'accu<i>'
  28628. accumulate( accuIndex, weight ) {
  28629. // note: happily accumulating nothing when weight = 0, the caller knows
  28630. // the weight and shouldn't have made the call in the first place
  28631. const buffer = this.buffer,
  28632. stride = this.valueSize,
  28633. offset = accuIndex * stride + stride;
  28634. let currentWeight = this.cumulativeWeight;
  28635. if ( currentWeight === 0 ) {
  28636. // accuN := incoming * weight
  28637. for ( let i = 0; i !== stride; ++ i ) {
  28638. buffer[ offset + i ] = buffer[ i ];
  28639. }
  28640. currentWeight = weight;
  28641. } else {
  28642. // accuN := accuN + incoming * weight
  28643. currentWeight += weight;
  28644. const mix = weight / currentWeight;
  28645. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28646. }
  28647. this.cumulativeWeight = currentWeight;
  28648. }
  28649. // accumulate data in the 'incoming' region into 'add'
  28650. accumulateAdditive( weight ) {
  28651. const buffer = this.buffer,
  28652. stride = this.valueSize,
  28653. offset = stride * this._addIndex;
  28654. if ( this.cumulativeWeightAdditive === 0 ) {
  28655. // add = identity
  28656. this._setIdentity();
  28657. }
  28658. // add := add + incoming * weight
  28659. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28660. this.cumulativeWeightAdditive += weight;
  28661. }
  28662. // apply the state of 'accu<i>' to the binding when accus differ
  28663. apply( accuIndex ) {
  28664. const stride = this.valueSize,
  28665. buffer = this.buffer,
  28666. offset = accuIndex * stride + stride,
  28667. weight = this.cumulativeWeight,
  28668. weightAdditive = this.cumulativeWeightAdditive,
  28669. binding = this.binding;
  28670. this.cumulativeWeight = 0;
  28671. this.cumulativeWeightAdditive = 0;
  28672. if ( weight < 1 ) {
  28673. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28674. const originalValueOffset = stride * this._origIndex;
  28675. this._mixBufferRegion(
  28676. buffer, offset, originalValueOffset, 1 - weight, stride );
  28677. }
  28678. if ( weightAdditive > 0 ) {
  28679. // accuN := accuN + additive accuN
  28680. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28681. }
  28682. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28683. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28684. // value has changed -> update scene graph
  28685. binding.setValue( buffer, offset );
  28686. break;
  28687. }
  28688. }
  28689. }
  28690. // remember the state of the bound property and copy it to both accus
  28691. saveOriginalState() {
  28692. const binding = this.binding;
  28693. const buffer = this.buffer,
  28694. stride = this.valueSize,
  28695. originalValueOffset = stride * this._origIndex;
  28696. binding.getValue( buffer, originalValueOffset );
  28697. // accu[0..1] := orig -- initially detect changes against the original
  28698. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28699. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28700. }
  28701. // Add to identity for additive
  28702. this._setIdentity();
  28703. this.cumulativeWeight = 0;
  28704. this.cumulativeWeightAdditive = 0;
  28705. }
  28706. // apply the state previously taken via 'saveOriginalState' to the binding
  28707. restoreOriginalState() {
  28708. const originalValueOffset = this.valueSize * 3;
  28709. this.binding.setValue( this.buffer, originalValueOffset );
  28710. }
  28711. _setAdditiveIdentityNumeric() {
  28712. const startIndex = this._addIndex * this.valueSize;
  28713. const endIndex = startIndex + this.valueSize;
  28714. for ( let i = startIndex; i < endIndex; i ++ ) {
  28715. this.buffer[ i ] = 0;
  28716. }
  28717. }
  28718. _setAdditiveIdentityQuaternion() {
  28719. this._setAdditiveIdentityNumeric();
  28720. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  28721. }
  28722. _setAdditiveIdentityOther() {
  28723. const startIndex = this._origIndex * this.valueSize;
  28724. const targetIndex = this._addIndex * this.valueSize;
  28725. for ( let i = 0; i < this.valueSize; i ++ ) {
  28726. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  28727. }
  28728. }
  28729. // mix functions
  28730. _select( buffer, dstOffset, srcOffset, t, stride ) {
  28731. if ( t >= 0.5 ) {
  28732. for ( let i = 0; i !== stride; ++ i ) {
  28733. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  28734. }
  28735. }
  28736. }
  28737. _slerp( buffer, dstOffset, srcOffset, t ) {
  28738. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  28739. }
  28740. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28741. const workOffset = this._workIndex * stride;
  28742. // Store result in intermediate buffer offset
  28743. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  28744. // Slerp to the intermediate result
  28745. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  28746. }
  28747. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  28748. const s = 1 - t;
  28749. for ( let i = 0; i !== stride; ++ i ) {
  28750. const j = dstOffset + i;
  28751. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  28752. }
  28753. }
  28754. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28755. for ( let i = 0; i !== stride; ++ i ) {
  28756. const j = dstOffset + i;
  28757. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  28758. }
  28759. }
  28760. }
  28761. // Characters [].:/ are reserved for track binding syntax.
  28762. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  28763. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  28764. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  28765. // only latin characters, and the unicode \p{L} is not yet supported. So
  28766. // instead, we exclude reserved characters and match everything else.
  28767. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  28768. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28769. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28770. // be matched to parse the rest of the track name.
  28771. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  28772. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28773. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  28774. // Object on target node, and accessor. May not contain reserved
  28775. // characters. Accessor may contain any character except closing bracket.
  28776. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  28777. // Property and accessor. May not contain reserved characters. Accessor may
  28778. // contain any non-bracket characters.
  28779. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  28780. const _trackRe = new RegExp( ''
  28781. + '^'
  28782. + _directoryRe
  28783. + _nodeRe
  28784. + _objectRe
  28785. + _propertyRe
  28786. + '$'
  28787. );
  28788. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  28789. class Composite {
  28790. constructor( targetGroup, path, optionalParsedPath ) {
  28791. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  28792. this._targetGroup = targetGroup;
  28793. this._bindings = targetGroup.subscribe_( path, parsedPath );
  28794. }
  28795. getValue( array, offset ) {
  28796. this.bind(); // bind all binding
  28797. const firstValidIndex = this._targetGroup.nCachedObjects_,
  28798. binding = this._bindings[ firstValidIndex ];
  28799. // and only call .getValue on the first
  28800. if ( binding !== undefined ) binding.getValue( array, offset );
  28801. }
  28802. setValue( array, offset ) {
  28803. const bindings = this._bindings;
  28804. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28805. bindings[ i ].setValue( array, offset );
  28806. }
  28807. }
  28808. bind() {
  28809. const bindings = this._bindings;
  28810. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28811. bindings[ i ].bind();
  28812. }
  28813. }
  28814. unbind() {
  28815. const bindings = this._bindings;
  28816. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28817. bindings[ i ].unbind();
  28818. }
  28819. }
  28820. }
  28821. // Note: This class uses a State pattern on a per-method basis:
  28822. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28823. // prototype version of these methods with one that represents
  28824. // the bound state. When the property is not found, the methods
  28825. // become no-ops.
  28826. class PropertyBinding {
  28827. constructor( rootNode, path, parsedPath ) {
  28828. this.path = path;
  28829. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  28830. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  28831. this.rootNode = rootNode;
  28832. // initial state of these methods that calls 'bind'
  28833. this.getValue = this._getValue_unbound;
  28834. this.setValue = this._setValue_unbound;
  28835. }
  28836. static create( root, path, parsedPath ) {
  28837. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  28838. return new PropertyBinding( root, path, parsedPath );
  28839. } else {
  28840. return new PropertyBinding.Composite( root, path, parsedPath );
  28841. }
  28842. }
  28843. /**
  28844. * Replaces spaces with underscores and removes unsupported characters from
  28845. * node names, to ensure compatibility with parseTrackName().
  28846. *
  28847. * @param {string} name Node name to be sanitized.
  28848. * @return {string}
  28849. */
  28850. static sanitizeNodeName( name ) {
  28851. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  28852. }
  28853. static parseTrackName( trackName ) {
  28854. const matches = _trackRe.exec( trackName );
  28855. if ( matches === null ) {
  28856. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  28857. }
  28858. const results = {
  28859. // directoryName: matches[ 1 ], // (tschw) currently unused
  28860. nodeName: matches[ 2 ],
  28861. objectName: matches[ 3 ],
  28862. objectIndex: matches[ 4 ],
  28863. propertyName: matches[ 5 ], // required
  28864. propertyIndex: matches[ 6 ]
  28865. };
  28866. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  28867. if ( lastDot !== undefined && lastDot !== - 1 ) {
  28868. const objectName = results.nodeName.substring( lastDot + 1 );
  28869. // Object names must be checked against an allowlist. Otherwise, there
  28870. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  28871. // 'bar' could be the objectName, or part of a nodeName (which can
  28872. // include '.' characters).
  28873. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  28874. results.nodeName = results.nodeName.substring( 0, lastDot );
  28875. results.objectName = objectName;
  28876. }
  28877. }
  28878. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  28879. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  28880. }
  28881. return results;
  28882. }
  28883. static findNode( root, nodeName ) {
  28884. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  28885. return root;
  28886. }
  28887. // search into skeleton bones.
  28888. if ( root.skeleton ) {
  28889. const bone = root.skeleton.getBoneByName( nodeName );
  28890. if ( bone !== undefined ) {
  28891. return bone;
  28892. }
  28893. }
  28894. // search into node subtree.
  28895. if ( root.children ) {
  28896. const searchNodeSubtree = function ( children ) {
  28897. for ( let i = 0; i < children.length; i ++ ) {
  28898. const childNode = children[ i ];
  28899. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  28900. return childNode;
  28901. }
  28902. const result = searchNodeSubtree( childNode.children );
  28903. if ( result ) return result;
  28904. }
  28905. return null;
  28906. };
  28907. const subTreeNode = searchNodeSubtree( root.children );
  28908. if ( subTreeNode ) {
  28909. return subTreeNode;
  28910. }
  28911. }
  28912. return null;
  28913. }
  28914. // these are used to "bind" a nonexistent property
  28915. _getValue_unavailable() {}
  28916. _setValue_unavailable() {}
  28917. // Getters
  28918. _getValue_direct( buffer, offset ) {
  28919. buffer[ offset ] = this.targetObject[ this.propertyName ];
  28920. }
  28921. _getValue_array( buffer, offset ) {
  28922. const source = this.resolvedProperty;
  28923. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  28924. buffer[ offset ++ ] = source[ i ];
  28925. }
  28926. }
  28927. _getValue_arrayElement( buffer, offset ) {
  28928. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  28929. }
  28930. _getValue_toArray( buffer, offset ) {
  28931. this.resolvedProperty.toArray( buffer, offset );
  28932. }
  28933. // Direct
  28934. _setValue_direct( buffer, offset ) {
  28935. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28936. }
  28937. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  28938. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28939. this.targetObject.needsUpdate = true;
  28940. }
  28941. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28942. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28943. this.targetObject.matrixWorldNeedsUpdate = true;
  28944. }
  28945. // EntireArray
  28946. _setValue_array( buffer, offset ) {
  28947. const dest = this.resolvedProperty;
  28948. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28949. dest[ i ] = buffer[ offset ++ ];
  28950. }
  28951. }
  28952. _setValue_array_setNeedsUpdate( buffer, offset ) {
  28953. const dest = this.resolvedProperty;
  28954. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28955. dest[ i ] = buffer[ offset ++ ];
  28956. }
  28957. this.targetObject.needsUpdate = true;
  28958. }
  28959. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28960. const dest = this.resolvedProperty;
  28961. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28962. dest[ i ] = buffer[ offset ++ ];
  28963. }
  28964. this.targetObject.matrixWorldNeedsUpdate = true;
  28965. }
  28966. // ArrayElement
  28967. _setValue_arrayElement( buffer, offset ) {
  28968. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28969. }
  28970. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28971. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28972. this.targetObject.needsUpdate = true;
  28973. }
  28974. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28975. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28976. this.targetObject.matrixWorldNeedsUpdate = true;
  28977. }
  28978. // HasToFromArray
  28979. _setValue_fromArray( buffer, offset ) {
  28980. this.resolvedProperty.fromArray( buffer, offset );
  28981. }
  28982. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28983. this.resolvedProperty.fromArray( buffer, offset );
  28984. this.targetObject.needsUpdate = true;
  28985. }
  28986. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28987. this.resolvedProperty.fromArray( buffer, offset );
  28988. this.targetObject.matrixWorldNeedsUpdate = true;
  28989. }
  28990. _getValue_unbound( targetArray, offset ) {
  28991. this.bind();
  28992. this.getValue( targetArray, offset );
  28993. }
  28994. _setValue_unbound( sourceArray, offset ) {
  28995. this.bind();
  28996. this.setValue( sourceArray, offset );
  28997. }
  28998. // create getter / setter pair for a property in the scene graph
  28999. bind() {
  29000. let targetObject = this.node;
  29001. const parsedPath = this.parsedPath;
  29002. const objectName = parsedPath.objectName;
  29003. const propertyName = parsedPath.propertyName;
  29004. let propertyIndex = parsedPath.propertyIndex;
  29005. if ( ! targetObject ) {
  29006. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  29007. this.node = targetObject;
  29008. }
  29009. // set fail state so we can just 'return' on error
  29010. this.getValue = this._getValue_unavailable;
  29011. this.setValue = this._setValue_unavailable;
  29012. // ensure there is a value node
  29013. if ( ! targetObject ) {
  29014. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  29015. return;
  29016. }
  29017. if ( objectName ) {
  29018. let objectIndex = parsedPath.objectIndex;
  29019. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  29020. switch ( objectName ) {
  29021. case 'materials':
  29022. if ( ! targetObject.material ) {
  29023. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29024. return;
  29025. }
  29026. if ( ! targetObject.material.materials ) {
  29027. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  29028. return;
  29029. }
  29030. targetObject = targetObject.material.materials;
  29031. break;
  29032. case 'bones':
  29033. if ( ! targetObject.skeleton ) {
  29034. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  29035. return;
  29036. }
  29037. // potential future optimization: skip this if propertyIndex is already an integer
  29038. // and convert the integer string to a true integer.
  29039. targetObject = targetObject.skeleton.bones;
  29040. // support resolving morphTarget names into indices.
  29041. for ( let i = 0; i < targetObject.length; i ++ ) {
  29042. if ( targetObject[ i ].name === objectIndex ) {
  29043. objectIndex = i;
  29044. break;
  29045. }
  29046. }
  29047. break;
  29048. case 'map':
  29049. if ( 'map' in targetObject ) {
  29050. targetObject = targetObject.map;
  29051. break;
  29052. }
  29053. if ( ! targetObject.material ) {
  29054. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  29055. return;
  29056. }
  29057. if ( ! targetObject.material.map ) {
  29058. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  29059. return;
  29060. }
  29061. targetObject = targetObject.material.map;
  29062. break;
  29063. default:
  29064. if ( targetObject[ objectName ] === undefined ) {
  29065. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  29066. return;
  29067. }
  29068. targetObject = targetObject[ objectName ];
  29069. }
  29070. if ( objectIndex !== undefined ) {
  29071. if ( targetObject[ objectIndex ] === undefined ) {
  29072. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  29073. return;
  29074. }
  29075. targetObject = targetObject[ objectIndex ];
  29076. }
  29077. }
  29078. // resolve property
  29079. const nodeProperty = targetObject[ propertyName ];
  29080. if ( nodeProperty === undefined ) {
  29081. const nodeName = parsedPath.nodeName;
  29082. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  29083. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  29084. return;
  29085. }
  29086. // determine versioning scheme
  29087. let versioning = this.Versioning.None;
  29088. this.targetObject = targetObject;
  29089. if ( targetObject.needsUpdate !== undefined ) { // material
  29090. versioning = this.Versioning.NeedsUpdate;
  29091. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  29092. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  29093. }
  29094. // determine how the property gets bound
  29095. let bindingType = this.BindingType.Direct;
  29096. if ( propertyIndex !== undefined ) {
  29097. // access a sub element of the property array (only primitives are supported right now)
  29098. if ( propertyName === 'morphTargetInfluences' ) {
  29099. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  29100. // support resolving morphTarget names into indices.
  29101. if ( ! targetObject.geometry ) {
  29102. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  29103. return;
  29104. }
  29105. if ( ! targetObject.geometry.morphAttributes ) {
  29106. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  29107. return;
  29108. }
  29109. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  29110. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  29111. }
  29112. }
  29113. bindingType = this.BindingType.ArrayElement;
  29114. this.resolvedProperty = nodeProperty;
  29115. this.propertyIndex = propertyIndex;
  29116. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  29117. // must use copy for Object3D.Euler/Quaternion
  29118. bindingType = this.BindingType.HasFromToArray;
  29119. this.resolvedProperty = nodeProperty;
  29120. } else if ( Array.isArray( nodeProperty ) ) {
  29121. bindingType = this.BindingType.EntireArray;
  29122. this.resolvedProperty = nodeProperty;
  29123. } else {
  29124. this.propertyName = propertyName;
  29125. }
  29126. // select getter / setter
  29127. this.getValue = this.GetterByBindingType[ bindingType ];
  29128. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  29129. }
  29130. unbind() {
  29131. this.node = null;
  29132. // back to the prototype version of getValue / setValue
  29133. // note: avoiding to mutate the shape of 'this' via 'delete'
  29134. this.getValue = this._getValue_unbound;
  29135. this.setValue = this._setValue_unbound;
  29136. }
  29137. }
  29138. PropertyBinding.Composite = Composite;
  29139. PropertyBinding.prototype.BindingType = {
  29140. Direct: 0,
  29141. EntireArray: 1,
  29142. ArrayElement: 2,
  29143. HasFromToArray: 3
  29144. };
  29145. PropertyBinding.prototype.Versioning = {
  29146. None: 0,
  29147. NeedsUpdate: 1,
  29148. MatrixWorldNeedsUpdate: 2
  29149. };
  29150. PropertyBinding.prototype.GetterByBindingType = [
  29151. PropertyBinding.prototype._getValue_direct,
  29152. PropertyBinding.prototype._getValue_array,
  29153. PropertyBinding.prototype._getValue_arrayElement,
  29154. PropertyBinding.prototype._getValue_toArray,
  29155. ];
  29156. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  29157. [
  29158. // Direct
  29159. PropertyBinding.prototype._setValue_direct,
  29160. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  29161. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  29162. ], [
  29163. // EntireArray
  29164. PropertyBinding.prototype._setValue_array,
  29165. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  29166. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  29167. ], [
  29168. // ArrayElement
  29169. PropertyBinding.prototype._setValue_arrayElement,
  29170. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  29171. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  29172. ], [
  29173. // HasToFromArray
  29174. PropertyBinding.prototype._setValue_fromArray,
  29175. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  29176. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  29177. ]
  29178. ];
  29179. /**
  29180. *
  29181. * A group of objects that receives a shared animation state.
  29182. *
  29183. * Usage:
  29184. *
  29185. * - Add objects you would otherwise pass as 'root' to the
  29186. * constructor or the .clipAction method of AnimationMixer.
  29187. *
  29188. * - Instead pass this object as 'root'.
  29189. *
  29190. * - You can also add and remove objects later when the mixer
  29191. * is running.
  29192. *
  29193. * Note:
  29194. *
  29195. * Objects of this class appear as one object to the mixer,
  29196. * so cache control of the individual objects must be done
  29197. * on the group.
  29198. *
  29199. * Limitation:
  29200. *
  29201. * - The animated properties must be compatible among the
  29202. * all objects in the group.
  29203. *
  29204. * - A single property can either be controlled through a
  29205. * target group or directly, but not both.
  29206. */
  29207. class AnimationObjectGroup {
  29208. constructor() {
  29209. this.isAnimationObjectGroup = true;
  29210. this.uuid = generateUUID();
  29211. // cached objects followed by the active ones
  29212. this._objects = Array.prototype.slice.call( arguments );
  29213. this.nCachedObjects_ = 0; // threshold
  29214. // note: read by PropertyBinding.Composite
  29215. const indices = {};
  29216. this._indicesByUUID = indices; // for bookkeeping
  29217. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29218. indices[ arguments[ i ].uuid ] = i;
  29219. }
  29220. this._paths = []; // inside: string
  29221. this._parsedPaths = []; // inside: { we don't care, here }
  29222. this._bindings = []; // inside: Array< PropertyBinding >
  29223. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29224. const scope = this;
  29225. this.stats = {
  29226. objects: {
  29227. get total() {
  29228. return scope._objects.length;
  29229. },
  29230. get inUse() {
  29231. return this.total - scope.nCachedObjects_;
  29232. }
  29233. },
  29234. get bindingsPerObject() {
  29235. return scope._bindings.length;
  29236. }
  29237. };
  29238. }
  29239. add() {
  29240. const objects = this._objects,
  29241. indicesByUUID = this._indicesByUUID,
  29242. paths = this._paths,
  29243. parsedPaths = this._parsedPaths,
  29244. bindings = this._bindings,
  29245. nBindings = bindings.length;
  29246. let knownObject = undefined,
  29247. nObjects = objects.length,
  29248. nCachedObjects = this.nCachedObjects_;
  29249. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29250. const object = arguments[ i ],
  29251. uuid = object.uuid;
  29252. let index = indicesByUUID[ uuid ];
  29253. if ( index === undefined ) {
  29254. // unknown object -> add it to the ACTIVE region
  29255. index = nObjects ++;
  29256. indicesByUUID[ uuid ] = index;
  29257. objects.push( object );
  29258. // accounting is done, now do the same for all bindings
  29259. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29260. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29261. }
  29262. } else if ( index < nCachedObjects ) {
  29263. knownObject = objects[ index ];
  29264. // move existing object to the ACTIVE region
  29265. const firstActiveIndex = -- nCachedObjects,
  29266. lastCachedObject = objects[ firstActiveIndex ];
  29267. indicesByUUID[ lastCachedObject.uuid ] = index;
  29268. objects[ index ] = lastCachedObject;
  29269. indicesByUUID[ uuid ] = firstActiveIndex;
  29270. objects[ firstActiveIndex ] = object;
  29271. // accounting is done, now do the same for all bindings
  29272. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29273. const bindingsForPath = bindings[ j ],
  29274. lastCached = bindingsForPath[ firstActiveIndex ];
  29275. let binding = bindingsForPath[ index ];
  29276. bindingsForPath[ index ] = lastCached;
  29277. if ( binding === undefined ) {
  29278. // since we do not bother to create new bindings
  29279. // for objects that are cached, the binding may
  29280. // or may not exist
  29281. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29282. }
  29283. bindingsForPath[ firstActiveIndex ] = binding;
  29284. }
  29285. } else if ( objects[ index ] !== knownObject ) {
  29286. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29287. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29288. } // else the object is already where we want it to be
  29289. } // for arguments
  29290. this.nCachedObjects_ = nCachedObjects;
  29291. }
  29292. remove() {
  29293. const objects = this._objects,
  29294. indicesByUUID = this._indicesByUUID,
  29295. bindings = this._bindings,
  29296. nBindings = bindings.length;
  29297. let nCachedObjects = this.nCachedObjects_;
  29298. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29299. const object = arguments[ i ],
  29300. uuid = object.uuid,
  29301. index = indicesByUUID[ uuid ];
  29302. if ( index !== undefined && index >= nCachedObjects ) {
  29303. // move existing object into the CACHED region
  29304. const lastCachedIndex = nCachedObjects ++,
  29305. firstActiveObject = objects[ lastCachedIndex ];
  29306. indicesByUUID[ firstActiveObject.uuid ] = index;
  29307. objects[ index ] = firstActiveObject;
  29308. indicesByUUID[ uuid ] = lastCachedIndex;
  29309. objects[ lastCachedIndex ] = object;
  29310. // accounting is done, now do the same for all bindings
  29311. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29312. const bindingsForPath = bindings[ j ],
  29313. firstActive = bindingsForPath[ lastCachedIndex ],
  29314. binding = bindingsForPath[ index ];
  29315. bindingsForPath[ index ] = firstActive;
  29316. bindingsForPath[ lastCachedIndex ] = binding;
  29317. }
  29318. }
  29319. } // for arguments
  29320. this.nCachedObjects_ = nCachedObjects;
  29321. }
  29322. // remove & forget
  29323. uncache() {
  29324. const objects = this._objects,
  29325. indicesByUUID = this._indicesByUUID,
  29326. bindings = this._bindings,
  29327. nBindings = bindings.length;
  29328. let nCachedObjects = this.nCachedObjects_,
  29329. nObjects = objects.length;
  29330. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29331. const object = arguments[ i ],
  29332. uuid = object.uuid,
  29333. index = indicesByUUID[ uuid ];
  29334. if ( index !== undefined ) {
  29335. delete indicesByUUID[ uuid ];
  29336. if ( index < nCachedObjects ) {
  29337. // object is cached, shrink the CACHED region
  29338. const firstActiveIndex = -- nCachedObjects,
  29339. lastCachedObject = objects[ firstActiveIndex ],
  29340. lastIndex = -- nObjects,
  29341. lastObject = objects[ lastIndex ];
  29342. // last cached object takes this object's place
  29343. indicesByUUID[ lastCachedObject.uuid ] = index;
  29344. objects[ index ] = lastCachedObject;
  29345. // last object goes to the activated slot and pop
  29346. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29347. objects[ firstActiveIndex ] = lastObject;
  29348. objects.pop();
  29349. // accounting is done, now do the same for all bindings
  29350. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29351. const bindingsForPath = bindings[ j ],
  29352. lastCached = bindingsForPath[ firstActiveIndex ],
  29353. last = bindingsForPath[ lastIndex ];
  29354. bindingsForPath[ index ] = lastCached;
  29355. bindingsForPath[ firstActiveIndex ] = last;
  29356. bindingsForPath.pop();
  29357. }
  29358. } else {
  29359. // object is active, just swap with the last and pop
  29360. const lastIndex = -- nObjects,
  29361. lastObject = objects[ lastIndex ];
  29362. if ( lastIndex > 0 ) {
  29363. indicesByUUID[ lastObject.uuid ] = index;
  29364. }
  29365. objects[ index ] = lastObject;
  29366. objects.pop();
  29367. // accounting is done, now do the same for all bindings
  29368. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29369. const bindingsForPath = bindings[ j ];
  29370. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29371. bindingsForPath.pop();
  29372. }
  29373. } // cached or active
  29374. } // if object is known
  29375. } // for arguments
  29376. this.nCachedObjects_ = nCachedObjects;
  29377. }
  29378. // Internal interface used by befriended PropertyBinding.Composite:
  29379. subscribe_( path, parsedPath ) {
  29380. // returns an array of bindings for the given path that is changed
  29381. // according to the contained objects in the group
  29382. const indicesByPath = this._bindingsIndicesByPath;
  29383. let index = indicesByPath[ path ];
  29384. const bindings = this._bindings;
  29385. if ( index !== undefined ) return bindings[ index ];
  29386. const paths = this._paths,
  29387. parsedPaths = this._parsedPaths,
  29388. objects = this._objects,
  29389. nObjects = objects.length,
  29390. nCachedObjects = this.nCachedObjects_,
  29391. bindingsForPath = new Array( nObjects );
  29392. index = bindings.length;
  29393. indicesByPath[ path ] = index;
  29394. paths.push( path );
  29395. parsedPaths.push( parsedPath );
  29396. bindings.push( bindingsForPath );
  29397. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29398. const object = objects[ i ];
  29399. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29400. }
  29401. return bindingsForPath;
  29402. }
  29403. unsubscribe_( path ) {
  29404. // tells the group to forget about a property path and no longer
  29405. // update the array previously obtained with 'subscribe_'
  29406. const indicesByPath = this._bindingsIndicesByPath,
  29407. index = indicesByPath[ path ];
  29408. if ( index !== undefined ) {
  29409. const paths = this._paths,
  29410. parsedPaths = this._parsedPaths,
  29411. bindings = this._bindings,
  29412. lastBindingsIndex = bindings.length - 1,
  29413. lastBindings = bindings[ lastBindingsIndex ],
  29414. lastBindingsPath = path[ lastBindingsIndex ];
  29415. indicesByPath[ lastBindingsPath ] = index;
  29416. bindings[ index ] = lastBindings;
  29417. bindings.pop();
  29418. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29419. parsedPaths.pop();
  29420. paths[ index ] = paths[ lastBindingsIndex ];
  29421. paths.pop();
  29422. }
  29423. }
  29424. }
  29425. class AnimationAction {
  29426. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29427. this._mixer = mixer;
  29428. this._clip = clip;
  29429. this._localRoot = localRoot;
  29430. this.blendMode = blendMode;
  29431. const tracks = clip.tracks,
  29432. nTracks = tracks.length,
  29433. interpolants = new Array( nTracks );
  29434. const interpolantSettings = {
  29435. endingStart: ZeroCurvatureEnding,
  29436. endingEnd: ZeroCurvatureEnding
  29437. };
  29438. for ( let i = 0; i !== nTracks; ++ i ) {
  29439. const interpolant = tracks[ i ].createInterpolant( null );
  29440. interpolants[ i ] = interpolant;
  29441. interpolant.settings = interpolantSettings;
  29442. }
  29443. this._interpolantSettings = interpolantSettings;
  29444. this._interpolants = interpolants; // bound by the mixer
  29445. // inside: PropertyMixer (managed by the mixer)
  29446. this._propertyBindings = new Array( nTracks );
  29447. this._cacheIndex = null; // for the memory manager
  29448. this._byClipCacheIndex = null; // for the memory manager
  29449. this._timeScaleInterpolant = null;
  29450. this._weightInterpolant = null;
  29451. this.loop = LoopRepeat;
  29452. this._loopCount = - 1;
  29453. // global mixer time when the action is to be started
  29454. // it's set back to 'null' upon start of the action
  29455. this._startTime = null;
  29456. // scaled local time of the action
  29457. // gets clamped or wrapped to 0..clip.duration according to loop
  29458. this.time = 0;
  29459. this.timeScale = 1;
  29460. this._effectiveTimeScale = 1;
  29461. this.weight = 1;
  29462. this._effectiveWeight = 1;
  29463. this.repetitions = Infinity; // no. of repetitions when looping
  29464. this.paused = false; // true -> zero effective time scale
  29465. this.enabled = true; // false -> zero effective weight
  29466. this.clampWhenFinished = false;// keep feeding the last frame?
  29467. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29468. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29469. }
  29470. // State & Scheduling
  29471. play() {
  29472. this._mixer._activateAction( this );
  29473. return this;
  29474. }
  29475. stop() {
  29476. this._mixer._deactivateAction( this );
  29477. return this.reset();
  29478. }
  29479. reset() {
  29480. this.paused = false;
  29481. this.enabled = true;
  29482. this.time = 0; // restart clip
  29483. this._loopCount = - 1;// forget previous loops
  29484. this._startTime = null;// forget scheduling
  29485. return this.stopFading().stopWarping();
  29486. }
  29487. isRunning() {
  29488. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29489. this._startTime === null && this._mixer._isActiveAction( this );
  29490. }
  29491. // return true when play has been called
  29492. isScheduled() {
  29493. return this._mixer._isActiveAction( this );
  29494. }
  29495. startAt( time ) {
  29496. this._startTime = time;
  29497. return this;
  29498. }
  29499. setLoop( mode, repetitions ) {
  29500. this.loop = mode;
  29501. this.repetitions = repetitions;
  29502. return this;
  29503. }
  29504. // Weight
  29505. // set the weight stopping any scheduled fading
  29506. // although .enabled = false yields an effective weight of zero, this
  29507. // method does *not* change .enabled, because it would be confusing
  29508. setEffectiveWeight( weight ) {
  29509. this.weight = weight;
  29510. // note: same logic as when updated at runtime
  29511. this._effectiveWeight = this.enabled ? weight : 0;
  29512. return this.stopFading();
  29513. }
  29514. // return the weight considering fading and .enabled
  29515. getEffectiveWeight() {
  29516. return this._effectiveWeight;
  29517. }
  29518. fadeIn( duration ) {
  29519. return this._scheduleFading( duration, 0, 1 );
  29520. }
  29521. fadeOut( duration ) {
  29522. return this._scheduleFading( duration, 1, 0 );
  29523. }
  29524. crossFadeFrom( fadeOutAction, duration, warp ) {
  29525. fadeOutAction.fadeOut( duration );
  29526. this.fadeIn( duration );
  29527. if ( warp ) {
  29528. const fadeInDuration = this._clip.duration,
  29529. fadeOutDuration = fadeOutAction._clip.duration,
  29530. startEndRatio = fadeOutDuration / fadeInDuration,
  29531. endStartRatio = fadeInDuration / fadeOutDuration;
  29532. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29533. this.warp( endStartRatio, 1.0, duration );
  29534. }
  29535. return this;
  29536. }
  29537. crossFadeTo( fadeInAction, duration, warp ) {
  29538. return fadeInAction.crossFadeFrom( this, duration, warp );
  29539. }
  29540. stopFading() {
  29541. const weightInterpolant = this._weightInterpolant;
  29542. if ( weightInterpolant !== null ) {
  29543. this._weightInterpolant = null;
  29544. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29545. }
  29546. return this;
  29547. }
  29548. // Time Scale Control
  29549. // set the time scale stopping any scheduled warping
  29550. // although .paused = true yields an effective time scale of zero, this
  29551. // method does *not* change .paused, because it would be confusing
  29552. setEffectiveTimeScale( timeScale ) {
  29553. this.timeScale = timeScale;
  29554. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29555. return this.stopWarping();
  29556. }
  29557. // return the time scale considering warping and .paused
  29558. getEffectiveTimeScale() {
  29559. return this._effectiveTimeScale;
  29560. }
  29561. setDuration( duration ) {
  29562. this.timeScale = this._clip.duration / duration;
  29563. return this.stopWarping();
  29564. }
  29565. syncWith( action ) {
  29566. this.time = action.time;
  29567. this.timeScale = action.timeScale;
  29568. return this.stopWarping();
  29569. }
  29570. halt( duration ) {
  29571. return this.warp( this._effectiveTimeScale, 0, duration );
  29572. }
  29573. warp( startTimeScale, endTimeScale, duration ) {
  29574. const mixer = this._mixer,
  29575. now = mixer.time,
  29576. timeScale = this.timeScale;
  29577. let interpolant = this._timeScaleInterpolant;
  29578. if ( interpolant === null ) {
  29579. interpolant = mixer._lendControlInterpolant();
  29580. this._timeScaleInterpolant = interpolant;
  29581. }
  29582. const times = interpolant.parameterPositions,
  29583. values = interpolant.sampleValues;
  29584. times[ 0 ] = now;
  29585. times[ 1 ] = now + duration;
  29586. values[ 0 ] = startTimeScale / timeScale;
  29587. values[ 1 ] = endTimeScale / timeScale;
  29588. return this;
  29589. }
  29590. stopWarping() {
  29591. const timeScaleInterpolant = this._timeScaleInterpolant;
  29592. if ( timeScaleInterpolant !== null ) {
  29593. this._timeScaleInterpolant = null;
  29594. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29595. }
  29596. return this;
  29597. }
  29598. // Object Accessors
  29599. getMixer() {
  29600. return this._mixer;
  29601. }
  29602. getClip() {
  29603. return this._clip;
  29604. }
  29605. getRoot() {
  29606. return this._localRoot || this._mixer._root;
  29607. }
  29608. // Interna
  29609. _update( time, deltaTime, timeDirection, accuIndex ) {
  29610. // called by the mixer
  29611. if ( ! this.enabled ) {
  29612. // call ._updateWeight() to update ._effectiveWeight
  29613. this._updateWeight( time );
  29614. return;
  29615. }
  29616. const startTime = this._startTime;
  29617. if ( startTime !== null ) {
  29618. // check for scheduled start of action
  29619. const timeRunning = ( time - startTime ) * timeDirection;
  29620. if ( timeRunning < 0 || timeDirection === 0 ) {
  29621. deltaTime = 0;
  29622. } else {
  29623. this._startTime = null; // unschedule
  29624. deltaTime = timeDirection * timeRunning;
  29625. }
  29626. }
  29627. // apply time scale and advance time
  29628. deltaTime *= this._updateTimeScale( time );
  29629. const clipTime = this._updateTime( deltaTime );
  29630. // note: _updateTime may disable the action resulting in
  29631. // an effective weight of 0
  29632. const weight = this._updateWeight( time );
  29633. if ( weight > 0 ) {
  29634. const interpolants = this._interpolants;
  29635. const propertyMixers = this._propertyBindings;
  29636. switch ( this.blendMode ) {
  29637. case AdditiveAnimationBlendMode:
  29638. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29639. interpolants[ j ].evaluate( clipTime );
  29640. propertyMixers[ j ].accumulateAdditive( weight );
  29641. }
  29642. break;
  29643. case NormalAnimationBlendMode:
  29644. default:
  29645. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29646. interpolants[ j ].evaluate( clipTime );
  29647. propertyMixers[ j ].accumulate( accuIndex, weight );
  29648. }
  29649. }
  29650. }
  29651. }
  29652. _updateWeight( time ) {
  29653. let weight = 0;
  29654. if ( this.enabled ) {
  29655. weight = this.weight;
  29656. const interpolant = this._weightInterpolant;
  29657. if ( interpolant !== null ) {
  29658. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29659. weight *= interpolantValue;
  29660. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29661. this.stopFading();
  29662. if ( interpolantValue === 0 ) {
  29663. // faded out, disable
  29664. this.enabled = false;
  29665. }
  29666. }
  29667. }
  29668. }
  29669. this._effectiveWeight = weight;
  29670. return weight;
  29671. }
  29672. _updateTimeScale( time ) {
  29673. let timeScale = 0;
  29674. if ( ! this.paused ) {
  29675. timeScale = this.timeScale;
  29676. const interpolant = this._timeScaleInterpolant;
  29677. if ( interpolant !== null ) {
  29678. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29679. timeScale *= interpolantValue;
  29680. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29681. this.stopWarping();
  29682. if ( timeScale === 0 ) {
  29683. // motion has halted, pause
  29684. this.paused = true;
  29685. } else {
  29686. // warp done - apply final time scale
  29687. this.timeScale = timeScale;
  29688. }
  29689. }
  29690. }
  29691. }
  29692. this._effectiveTimeScale = timeScale;
  29693. return timeScale;
  29694. }
  29695. _updateTime( deltaTime ) {
  29696. const duration = this._clip.duration;
  29697. const loop = this.loop;
  29698. let time = this.time + deltaTime;
  29699. let loopCount = this._loopCount;
  29700. const pingPong = ( loop === LoopPingPong );
  29701. if ( deltaTime === 0 ) {
  29702. if ( loopCount === - 1 ) return time;
  29703. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29704. }
  29705. if ( loop === LoopOnce ) {
  29706. if ( loopCount === - 1 ) {
  29707. // just started
  29708. this._loopCount = 0;
  29709. this._setEndings( true, true, false );
  29710. }
  29711. handle_stop: {
  29712. if ( time >= duration ) {
  29713. time = duration;
  29714. } else if ( time < 0 ) {
  29715. time = 0;
  29716. } else {
  29717. this.time = time;
  29718. break handle_stop;
  29719. }
  29720. if ( this.clampWhenFinished ) this.paused = true;
  29721. else this.enabled = false;
  29722. this.time = time;
  29723. this._mixer.dispatchEvent( {
  29724. type: 'finished', action: this,
  29725. direction: deltaTime < 0 ? - 1 : 1
  29726. } );
  29727. }
  29728. } else { // repetitive Repeat or PingPong
  29729. if ( loopCount === - 1 ) {
  29730. // just started
  29731. if ( deltaTime >= 0 ) {
  29732. loopCount = 0;
  29733. this._setEndings( true, this.repetitions === 0, pingPong );
  29734. } else {
  29735. // when looping in reverse direction, the initial
  29736. // transition through zero counts as a repetition,
  29737. // so leave loopCount at -1
  29738. this._setEndings( this.repetitions === 0, true, pingPong );
  29739. }
  29740. }
  29741. if ( time >= duration || time < 0 ) {
  29742. // wrap around
  29743. const loopDelta = Math.floor( time / duration ); // signed
  29744. time -= duration * loopDelta;
  29745. loopCount += Math.abs( loopDelta );
  29746. const pending = this.repetitions - loopCount;
  29747. if ( pending <= 0 ) {
  29748. // have to stop (switch state, clamp time, fire event)
  29749. if ( this.clampWhenFinished ) this.paused = true;
  29750. else this.enabled = false;
  29751. time = deltaTime > 0 ? duration : 0;
  29752. this.time = time;
  29753. this._mixer.dispatchEvent( {
  29754. type: 'finished', action: this,
  29755. direction: deltaTime > 0 ? 1 : - 1
  29756. } );
  29757. } else {
  29758. // keep running
  29759. if ( pending === 1 ) {
  29760. // entering the last round
  29761. const atStart = deltaTime < 0;
  29762. this._setEndings( atStart, ! atStart, pingPong );
  29763. } else {
  29764. this._setEndings( false, false, pingPong );
  29765. }
  29766. this._loopCount = loopCount;
  29767. this.time = time;
  29768. this._mixer.dispatchEvent( {
  29769. type: 'loop', action: this, loopDelta: loopDelta
  29770. } );
  29771. }
  29772. } else {
  29773. this.time = time;
  29774. }
  29775. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  29776. // invert time for the "pong round"
  29777. return duration - time;
  29778. }
  29779. }
  29780. return time;
  29781. }
  29782. _setEndings( atStart, atEnd, pingPong ) {
  29783. const settings = this._interpolantSettings;
  29784. if ( pingPong ) {
  29785. settings.endingStart = ZeroSlopeEnding;
  29786. settings.endingEnd = ZeroSlopeEnding;
  29787. } else {
  29788. // assuming for LoopOnce atStart == atEnd == true
  29789. if ( atStart ) {
  29790. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29791. } else {
  29792. settings.endingStart = WrapAroundEnding;
  29793. }
  29794. if ( atEnd ) {
  29795. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29796. } else {
  29797. settings.endingEnd = WrapAroundEnding;
  29798. }
  29799. }
  29800. }
  29801. _scheduleFading( duration, weightNow, weightThen ) {
  29802. const mixer = this._mixer, now = mixer.time;
  29803. let interpolant = this._weightInterpolant;
  29804. if ( interpolant === null ) {
  29805. interpolant = mixer._lendControlInterpolant();
  29806. this._weightInterpolant = interpolant;
  29807. }
  29808. const times = interpolant.parameterPositions,
  29809. values = interpolant.sampleValues;
  29810. times[ 0 ] = now;
  29811. values[ 0 ] = weightNow;
  29812. times[ 1 ] = now + duration;
  29813. values[ 1 ] = weightThen;
  29814. return this;
  29815. }
  29816. }
  29817. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  29818. class AnimationMixer extends EventDispatcher {
  29819. constructor( root ) {
  29820. super();
  29821. this._root = root;
  29822. this._initMemoryManager();
  29823. this._accuIndex = 0;
  29824. this.time = 0;
  29825. this.timeScale = 1.0;
  29826. }
  29827. _bindAction( action, prototypeAction ) {
  29828. const root = action._localRoot || this._root,
  29829. tracks = action._clip.tracks,
  29830. nTracks = tracks.length,
  29831. bindings = action._propertyBindings,
  29832. interpolants = action._interpolants,
  29833. rootUuid = root.uuid,
  29834. bindingsByRoot = this._bindingsByRootAndName;
  29835. let bindingsByName = bindingsByRoot[ rootUuid ];
  29836. if ( bindingsByName === undefined ) {
  29837. bindingsByName = {};
  29838. bindingsByRoot[ rootUuid ] = bindingsByName;
  29839. }
  29840. for ( let i = 0; i !== nTracks; ++ i ) {
  29841. const track = tracks[ i ],
  29842. trackName = track.name;
  29843. let binding = bindingsByName[ trackName ];
  29844. if ( binding !== undefined ) {
  29845. ++ binding.referenceCount;
  29846. bindings[ i ] = binding;
  29847. } else {
  29848. binding = bindings[ i ];
  29849. if ( binding !== undefined ) {
  29850. // existing binding, make sure the cache knows
  29851. if ( binding._cacheIndex === null ) {
  29852. ++ binding.referenceCount;
  29853. this._addInactiveBinding( binding, rootUuid, trackName );
  29854. }
  29855. continue;
  29856. }
  29857. const path = prototypeAction && prototypeAction.
  29858. _propertyBindings[ i ].binding.parsedPath;
  29859. binding = new PropertyMixer(
  29860. PropertyBinding.create( root, trackName, path ),
  29861. track.ValueTypeName, track.getValueSize() );
  29862. ++ binding.referenceCount;
  29863. this._addInactiveBinding( binding, rootUuid, trackName );
  29864. bindings[ i ] = binding;
  29865. }
  29866. interpolants[ i ].resultBuffer = binding.buffer;
  29867. }
  29868. }
  29869. _activateAction( action ) {
  29870. if ( ! this._isActiveAction( action ) ) {
  29871. if ( action._cacheIndex === null ) {
  29872. // this action has been forgotten by the cache, but the user
  29873. // appears to be still using it -> rebind
  29874. const rootUuid = ( action._localRoot || this._root ).uuid,
  29875. clipUuid = action._clip.uuid,
  29876. actionsForClip = this._actionsByClip[ clipUuid ];
  29877. this._bindAction( action,
  29878. actionsForClip && actionsForClip.knownActions[ 0 ] );
  29879. this._addInactiveAction( action, clipUuid, rootUuid );
  29880. }
  29881. const bindings = action._propertyBindings;
  29882. // increment reference counts / sort out state
  29883. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29884. const binding = bindings[ i ];
  29885. if ( binding.useCount ++ === 0 ) {
  29886. this._lendBinding( binding );
  29887. binding.saveOriginalState();
  29888. }
  29889. }
  29890. this._lendAction( action );
  29891. }
  29892. }
  29893. _deactivateAction( action ) {
  29894. if ( this._isActiveAction( action ) ) {
  29895. const bindings = action._propertyBindings;
  29896. // decrement reference counts / sort out state
  29897. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29898. const binding = bindings[ i ];
  29899. if ( -- binding.useCount === 0 ) {
  29900. binding.restoreOriginalState();
  29901. this._takeBackBinding( binding );
  29902. }
  29903. }
  29904. this._takeBackAction( action );
  29905. }
  29906. }
  29907. // Memory manager
  29908. _initMemoryManager() {
  29909. this._actions = []; // 'nActiveActions' followed by inactive ones
  29910. this._nActiveActions = 0;
  29911. this._actionsByClip = {};
  29912. // inside:
  29913. // {
  29914. // knownActions: Array< AnimationAction > - used as prototypes
  29915. // actionByRoot: AnimationAction - lookup
  29916. // }
  29917. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  29918. this._nActiveBindings = 0;
  29919. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  29920. this._controlInterpolants = []; // same game as above
  29921. this._nActiveControlInterpolants = 0;
  29922. const scope = this;
  29923. this.stats = {
  29924. actions: {
  29925. get total() {
  29926. return scope._actions.length;
  29927. },
  29928. get inUse() {
  29929. return scope._nActiveActions;
  29930. }
  29931. },
  29932. bindings: {
  29933. get total() {
  29934. return scope._bindings.length;
  29935. },
  29936. get inUse() {
  29937. return scope._nActiveBindings;
  29938. }
  29939. },
  29940. controlInterpolants: {
  29941. get total() {
  29942. return scope._controlInterpolants.length;
  29943. },
  29944. get inUse() {
  29945. return scope._nActiveControlInterpolants;
  29946. }
  29947. }
  29948. };
  29949. }
  29950. // Memory management for AnimationAction objects
  29951. _isActiveAction( action ) {
  29952. const index = action._cacheIndex;
  29953. return index !== null && index < this._nActiveActions;
  29954. }
  29955. _addInactiveAction( action, clipUuid, rootUuid ) {
  29956. const actions = this._actions,
  29957. actionsByClip = this._actionsByClip;
  29958. let actionsForClip = actionsByClip[ clipUuid ];
  29959. if ( actionsForClip === undefined ) {
  29960. actionsForClip = {
  29961. knownActions: [ action ],
  29962. actionByRoot: {}
  29963. };
  29964. action._byClipCacheIndex = 0;
  29965. actionsByClip[ clipUuid ] = actionsForClip;
  29966. } else {
  29967. const knownActions = actionsForClip.knownActions;
  29968. action._byClipCacheIndex = knownActions.length;
  29969. knownActions.push( action );
  29970. }
  29971. action._cacheIndex = actions.length;
  29972. actions.push( action );
  29973. actionsForClip.actionByRoot[ rootUuid ] = action;
  29974. }
  29975. _removeInactiveAction( action ) {
  29976. const actions = this._actions,
  29977. lastInactiveAction = actions[ actions.length - 1 ],
  29978. cacheIndex = action._cacheIndex;
  29979. lastInactiveAction._cacheIndex = cacheIndex;
  29980. actions[ cacheIndex ] = lastInactiveAction;
  29981. actions.pop();
  29982. action._cacheIndex = null;
  29983. const clipUuid = action._clip.uuid,
  29984. actionsByClip = this._actionsByClip,
  29985. actionsForClip = actionsByClip[ clipUuid ],
  29986. knownActionsForClip = actionsForClip.knownActions,
  29987. lastKnownAction =
  29988. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29989. byClipCacheIndex = action._byClipCacheIndex;
  29990. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29991. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29992. knownActionsForClip.pop();
  29993. action._byClipCacheIndex = null;
  29994. const actionByRoot = actionsForClip.actionByRoot,
  29995. rootUuid = ( action._localRoot || this._root ).uuid;
  29996. delete actionByRoot[ rootUuid ];
  29997. if ( knownActionsForClip.length === 0 ) {
  29998. delete actionsByClip[ clipUuid ];
  29999. }
  30000. this._removeInactiveBindingsForAction( action );
  30001. }
  30002. _removeInactiveBindingsForAction( action ) {
  30003. const bindings = action._propertyBindings;
  30004. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  30005. const binding = bindings[ i ];
  30006. if ( -- binding.referenceCount === 0 ) {
  30007. this._removeInactiveBinding( binding );
  30008. }
  30009. }
  30010. }
  30011. _lendAction( action ) {
  30012. // [ active actions | inactive actions ]
  30013. // [ active actions >| inactive actions ]
  30014. // s a
  30015. // <-swap->
  30016. // a s
  30017. const actions = this._actions,
  30018. prevIndex = action._cacheIndex,
  30019. lastActiveIndex = this._nActiveActions ++,
  30020. firstInactiveAction = actions[ lastActiveIndex ];
  30021. action._cacheIndex = lastActiveIndex;
  30022. actions[ lastActiveIndex ] = action;
  30023. firstInactiveAction._cacheIndex = prevIndex;
  30024. actions[ prevIndex ] = firstInactiveAction;
  30025. }
  30026. _takeBackAction( action ) {
  30027. // [ active actions | inactive actions ]
  30028. // [ active actions |< inactive actions ]
  30029. // a s
  30030. // <-swap->
  30031. // s a
  30032. const actions = this._actions,
  30033. prevIndex = action._cacheIndex,
  30034. firstInactiveIndex = -- this._nActiveActions,
  30035. lastActiveAction = actions[ firstInactiveIndex ];
  30036. action._cacheIndex = firstInactiveIndex;
  30037. actions[ firstInactiveIndex ] = action;
  30038. lastActiveAction._cacheIndex = prevIndex;
  30039. actions[ prevIndex ] = lastActiveAction;
  30040. }
  30041. // Memory management for PropertyMixer objects
  30042. _addInactiveBinding( binding, rootUuid, trackName ) {
  30043. const bindingsByRoot = this._bindingsByRootAndName,
  30044. bindings = this._bindings;
  30045. let bindingByName = bindingsByRoot[ rootUuid ];
  30046. if ( bindingByName === undefined ) {
  30047. bindingByName = {};
  30048. bindingsByRoot[ rootUuid ] = bindingByName;
  30049. }
  30050. bindingByName[ trackName ] = binding;
  30051. binding._cacheIndex = bindings.length;
  30052. bindings.push( binding );
  30053. }
  30054. _removeInactiveBinding( binding ) {
  30055. const bindings = this._bindings,
  30056. propBinding = binding.binding,
  30057. rootUuid = propBinding.rootNode.uuid,
  30058. trackName = propBinding.path,
  30059. bindingsByRoot = this._bindingsByRootAndName,
  30060. bindingByName = bindingsByRoot[ rootUuid ],
  30061. lastInactiveBinding = bindings[ bindings.length - 1 ],
  30062. cacheIndex = binding._cacheIndex;
  30063. lastInactiveBinding._cacheIndex = cacheIndex;
  30064. bindings[ cacheIndex ] = lastInactiveBinding;
  30065. bindings.pop();
  30066. delete bindingByName[ trackName ];
  30067. if ( Object.keys( bindingByName ).length === 0 ) {
  30068. delete bindingsByRoot[ rootUuid ];
  30069. }
  30070. }
  30071. _lendBinding( binding ) {
  30072. const bindings = this._bindings,
  30073. prevIndex = binding._cacheIndex,
  30074. lastActiveIndex = this._nActiveBindings ++,
  30075. firstInactiveBinding = bindings[ lastActiveIndex ];
  30076. binding._cacheIndex = lastActiveIndex;
  30077. bindings[ lastActiveIndex ] = binding;
  30078. firstInactiveBinding._cacheIndex = prevIndex;
  30079. bindings[ prevIndex ] = firstInactiveBinding;
  30080. }
  30081. _takeBackBinding( binding ) {
  30082. const bindings = this._bindings,
  30083. prevIndex = binding._cacheIndex,
  30084. firstInactiveIndex = -- this._nActiveBindings,
  30085. lastActiveBinding = bindings[ firstInactiveIndex ];
  30086. binding._cacheIndex = firstInactiveIndex;
  30087. bindings[ firstInactiveIndex ] = binding;
  30088. lastActiveBinding._cacheIndex = prevIndex;
  30089. bindings[ prevIndex ] = lastActiveBinding;
  30090. }
  30091. // Memory management of Interpolants for weight and time scale
  30092. _lendControlInterpolant() {
  30093. const interpolants = this._controlInterpolants,
  30094. lastActiveIndex = this._nActiveControlInterpolants ++;
  30095. let interpolant = interpolants[ lastActiveIndex ];
  30096. if ( interpolant === undefined ) {
  30097. interpolant = new LinearInterpolant(
  30098. new Float32Array( 2 ), new Float32Array( 2 ),
  30099. 1, _controlInterpolantsResultBuffer );
  30100. interpolant.__cacheIndex = lastActiveIndex;
  30101. interpolants[ lastActiveIndex ] = interpolant;
  30102. }
  30103. return interpolant;
  30104. }
  30105. _takeBackControlInterpolant( interpolant ) {
  30106. const interpolants = this._controlInterpolants,
  30107. prevIndex = interpolant.__cacheIndex,
  30108. firstInactiveIndex = -- this._nActiveControlInterpolants,
  30109. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  30110. interpolant.__cacheIndex = firstInactiveIndex;
  30111. interpolants[ firstInactiveIndex ] = interpolant;
  30112. lastActiveInterpolant.__cacheIndex = prevIndex;
  30113. interpolants[ prevIndex ] = lastActiveInterpolant;
  30114. }
  30115. // return an action for a clip optionally using a custom root target
  30116. // object (this method allocates a lot of dynamic memory in case a
  30117. // previously unknown clip/root combination is specified)
  30118. clipAction( clip, optionalRoot, blendMode ) {
  30119. const root = optionalRoot || this._root,
  30120. rootUuid = root.uuid;
  30121. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  30122. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  30123. const actionsForClip = this._actionsByClip[ clipUuid ];
  30124. let prototypeAction = null;
  30125. if ( blendMode === undefined ) {
  30126. if ( clipObject !== null ) {
  30127. blendMode = clipObject.blendMode;
  30128. } else {
  30129. blendMode = NormalAnimationBlendMode;
  30130. }
  30131. }
  30132. if ( actionsForClip !== undefined ) {
  30133. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  30134. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  30135. return existingAction;
  30136. }
  30137. // we know the clip, so we don't have to parse all
  30138. // the bindings again but can just copy
  30139. prototypeAction = actionsForClip.knownActions[ 0 ];
  30140. // also, take the clip from the prototype action
  30141. if ( clipObject === null )
  30142. clipObject = prototypeAction._clip;
  30143. }
  30144. // clip must be known when specified via string
  30145. if ( clipObject === null ) return null;
  30146. // allocate all resources required to run it
  30147. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  30148. this._bindAction( newAction, prototypeAction );
  30149. // and make the action known to the memory manager
  30150. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30151. return newAction;
  30152. }
  30153. // get an existing action
  30154. existingAction( clip, optionalRoot ) {
  30155. const root = optionalRoot || this._root,
  30156. rootUuid = root.uuid,
  30157. clipObject = typeof clip === 'string' ?
  30158. AnimationClip.findByName( root, clip ) : clip,
  30159. clipUuid = clipObject ? clipObject.uuid : clip,
  30160. actionsForClip = this._actionsByClip[ clipUuid ];
  30161. if ( actionsForClip !== undefined ) {
  30162. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30163. }
  30164. return null;
  30165. }
  30166. // deactivates all previously scheduled actions
  30167. stopAllAction() {
  30168. const actions = this._actions,
  30169. nActions = this._nActiveActions;
  30170. for ( let i = nActions - 1; i >= 0; -- i ) {
  30171. actions[ i ].stop();
  30172. }
  30173. return this;
  30174. }
  30175. // advance the time and update apply the animation
  30176. update( deltaTime ) {
  30177. deltaTime *= this.timeScale;
  30178. const actions = this._actions,
  30179. nActions = this._nActiveActions,
  30180. time = this.time += deltaTime,
  30181. timeDirection = Math.sign( deltaTime ),
  30182. accuIndex = this._accuIndex ^= 1;
  30183. // run active actions
  30184. for ( let i = 0; i !== nActions; ++ i ) {
  30185. const action = actions[ i ];
  30186. action._update( time, deltaTime, timeDirection, accuIndex );
  30187. }
  30188. // update scene graph
  30189. const bindings = this._bindings,
  30190. nBindings = this._nActiveBindings;
  30191. for ( let i = 0; i !== nBindings; ++ i ) {
  30192. bindings[ i ].apply( accuIndex );
  30193. }
  30194. return this;
  30195. }
  30196. // Allows you to seek to a specific time in an animation.
  30197. setTime( timeInSeconds ) {
  30198. this.time = 0; // Zero out time attribute for AnimationMixer object;
  30199. for ( let i = 0; i < this._actions.length; i ++ ) {
  30200. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  30201. }
  30202. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  30203. }
  30204. // return this mixer's root target object
  30205. getRoot() {
  30206. return this._root;
  30207. }
  30208. // free all resources specific to a particular clip
  30209. uncacheClip( clip ) {
  30210. const actions = this._actions,
  30211. clipUuid = clip.uuid,
  30212. actionsByClip = this._actionsByClip,
  30213. actionsForClip = actionsByClip[ clipUuid ];
  30214. if ( actionsForClip !== undefined ) {
  30215. // note: just calling _removeInactiveAction would mess up the
  30216. // iteration state and also require updating the state we can
  30217. // just throw away
  30218. const actionsToRemove = actionsForClip.knownActions;
  30219. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30220. const action = actionsToRemove[ i ];
  30221. this._deactivateAction( action );
  30222. const cacheIndex = action._cacheIndex,
  30223. lastInactiveAction = actions[ actions.length - 1 ];
  30224. action._cacheIndex = null;
  30225. action._byClipCacheIndex = null;
  30226. lastInactiveAction._cacheIndex = cacheIndex;
  30227. actions[ cacheIndex ] = lastInactiveAction;
  30228. actions.pop();
  30229. this._removeInactiveBindingsForAction( action );
  30230. }
  30231. delete actionsByClip[ clipUuid ];
  30232. }
  30233. }
  30234. // free all resources specific to a particular root target object
  30235. uncacheRoot( root ) {
  30236. const rootUuid = root.uuid,
  30237. actionsByClip = this._actionsByClip;
  30238. for ( const clipUuid in actionsByClip ) {
  30239. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30240. action = actionByRoot[ rootUuid ];
  30241. if ( action !== undefined ) {
  30242. this._deactivateAction( action );
  30243. this._removeInactiveAction( action );
  30244. }
  30245. }
  30246. const bindingsByRoot = this._bindingsByRootAndName,
  30247. bindingByName = bindingsByRoot[ rootUuid ];
  30248. if ( bindingByName !== undefined ) {
  30249. for ( const trackName in bindingByName ) {
  30250. const binding = bindingByName[ trackName ];
  30251. binding.restoreOriginalState();
  30252. this._removeInactiveBinding( binding );
  30253. }
  30254. }
  30255. }
  30256. // remove a targeted clip from the cache
  30257. uncacheAction( clip, optionalRoot ) {
  30258. const action = this.existingAction( clip, optionalRoot );
  30259. if ( action !== null ) {
  30260. this._deactivateAction( action );
  30261. this._removeInactiveAction( action );
  30262. }
  30263. }
  30264. }
  30265. class Uniform {
  30266. constructor( value ) {
  30267. this.value = value;
  30268. }
  30269. clone() {
  30270. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30271. }
  30272. }
  30273. let _id = 0;
  30274. class UniformsGroup extends EventDispatcher {
  30275. constructor() {
  30276. super();
  30277. this.isUniformsGroup = true;
  30278. Object.defineProperty( this, 'id', { value: _id ++ } );
  30279. this.name = '';
  30280. this.usage = StaticDrawUsage;
  30281. this.uniforms = [];
  30282. }
  30283. add( uniform ) {
  30284. this.uniforms.push( uniform );
  30285. return this;
  30286. }
  30287. remove( uniform ) {
  30288. const index = this.uniforms.indexOf( uniform );
  30289. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  30290. return this;
  30291. }
  30292. setName( name ) {
  30293. this.name = name;
  30294. return this;
  30295. }
  30296. setUsage( value ) {
  30297. this.usage = value;
  30298. return this;
  30299. }
  30300. dispose() {
  30301. this.dispatchEvent( { type: 'dispose' } );
  30302. return this;
  30303. }
  30304. copy( source ) {
  30305. this.name = source.name;
  30306. this.usage = source.usage;
  30307. const uniformsSource = source.uniforms;
  30308. this.uniforms.length = 0;
  30309. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  30310. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  30311. for ( let j = 0; j < uniforms.length; j ++ ) {
  30312. this.uniforms.push( uniforms[ j ].clone() );
  30313. }
  30314. }
  30315. return this;
  30316. }
  30317. clone() {
  30318. return new this.constructor().copy( this );
  30319. }
  30320. }
  30321. class InstancedInterleavedBuffer extends InterleavedBuffer {
  30322. constructor( array, stride, meshPerAttribute = 1 ) {
  30323. super( array, stride );
  30324. this.isInstancedInterleavedBuffer = true;
  30325. this.meshPerAttribute = meshPerAttribute;
  30326. }
  30327. copy( source ) {
  30328. super.copy( source );
  30329. this.meshPerAttribute = source.meshPerAttribute;
  30330. return this;
  30331. }
  30332. clone( data ) {
  30333. const ib = super.clone( data );
  30334. ib.meshPerAttribute = this.meshPerAttribute;
  30335. return ib;
  30336. }
  30337. toJSON( data ) {
  30338. const json = super.toJSON( data );
  30339. json.isInstancedInterleavedBuffer = true;
  30340. json.meshPerAttribute = this.meshPerAttribute;
  30341. return json;
  30342. }
  30343. }
  30344. class GLBufferAttribute {
  30345. constructor( buffer, type, itemSize, elementSize, count ) {
  30346. this.isGLBufferAttribute = true;
  30347. this.name = '';
  30348. this.buffer = buffer;
  30349. this.type = type;
  30350. this.itemSize = itemSize;
  30351. this.elementSize = elementSize;
  30352. this.count = count;
  30353. this.version = 0;
  30354. }
  30355. set needsUpdate( value ) {
  30356. if ( value === true ) this.version ++;
  30357. }
  30358. setBuffer( buffer ) {
  30359. this.buffer = buffer;
  30360. return this;
  30361. }
  30362. setType( type, elementSize ) {
  30363. this.type = type;
  30364. this.elementSize = elementSize;
  30365. return this;
  30366. }
  30367. setItemSize( itemSize ) {
  30368. this.itemSize = itemSize;
  30369. return this;
  30370. }
  30371. setCount( count ) {
  30372. this.count = count;
  30373. return this;
  30374. }
  30375. }
  30376. const _matrix = /*@__PURE__*/ new Matrix4();
  30377. class Raycaster {
  30378. constructor( origin, direction, near = 0, far = Infinity ) {
  30379. this.ray = new Ray( origin, direction );
  30380. // direction is assumed to be normalized (for accurate distance calculations)
  30381. this.near = near;
  30382. this.far = far;
  30383. this.camera = null;
  30384. this.layers = new Layers();
  30385. this.params = {
  30386. Mesh: {},
  30387. Line: { threshold: 1 },
  30388. LOD: {},
  30389. Points: { threshold: 1 },
  30390. Sprite: {}
  30391. };
  30392. }
  30393. set( origin, direction ) {
  30394. // direction is assumed to be normalized (for accurate distance calculations)
  30395. this.ray.set( origin, direction );
  30396. }
  30397. setFromCamera( coords, camera ) {
  30398. if ( camera.isPerspectiveCamera ) {
  30399. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30400. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30401. this.camera = camera;
  30402. } else if ( camera.isOrthographicCamera ) {
  30403. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30404. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30405. this.camera = camera;
  30406. } else {
  30407. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30408. }
  30409. }
  30410. setFromXRController( controller ) {
  30411. _matrix.identity().extractRotation( controller.matrixWorld );
  30412. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  30413. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  30414. return this;
  30415. }
  30416. intersectObject( object, recursive = true, intersects = [] ) {
  30417. intersect( object, this, intersects, recursive );
  30418. intersects.sort( ascSort );
  30419. return intersects;
  30420. }
  30421. intersectObjects( objects, recursive = true, intersects = [] ) {
  30422. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30423. intersect( objects[ i ], this, intersects, recursive );
  30424. }
  30425. intersects.sort( ascSort );
  30426. return intersects;
  30427. }
  30428. }
  30429. function ascSort( a, b ) {
  30430. return a.distance - b.distance;
  30431. }
  30432. function intersect( object, raycaster, intersects, recursive ) {
  30433. let propagate = true;
  30434. if ( object.layers.test( raycaster.layers ) ) {
  30435. const result = object.raycast( raycaster, intersects );
  30436. if ( result === false ) propagate = false;
  30437. }
  30438. if ( propagate === true && recursive === true ) {
  30439. const children = object.children;
  30440. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30441. intersect( children[ i ], raycaster, intersects, true );
  30442. }
  30443. }
  30444. }
  30445. /**
  30446. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30447. *
  30448. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  30449. * theta (the azimuthal angle) is measured from the positive z-axis.
  30450. */
  30451. class Spherical {
  30452. constructor( radius = 1, phi = 0, theta = 0 ) {
  30453. this.radius = radius;
  30454. this.phi = phi; // polar angle
  30455. this.theta = theta; // azimuthal angle
  30456. return this;
  30457. }
  30458. set( radius, phi, theta ) {
  30459. this.radius = radius;
  30460. this.phi = phi;
  30461. this.theta = theta;
  30462. return this;
  30463. }
  30464. copy( other ) {
  30465. this.radius = other.radius;
  30466. this.phi = other.phi;
  30467. this.theta = other.theta;
  30468. return this;
  30469. }
  30470. // restrict phi to be between EPS and PI-EPS
  30471. makeSafe() {
  30472. const EPS = 0.000001;
  30473. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30474. return this;
  30475. }
  30476. setFromVector3( v ) {
  30477. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30478. }
  30479. setFromCartesianCoords( x, y, z ) {
  30480. this.radius = Math.sqrt( x * x + y * y + z * z );
  30481. if ( this.radius === 0 ) {
  30482. this.theta = 0;
  30483. this.phi = 0;
  30484. } else {
  30485. this.theta = Math.atan2( x, z );
  30486. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  30487. }
  30488. return this;
  30489. }
  30490. clone() {
  30491. return new this.constructor().copy( this );
  30492. }
  30493. }
  30494. /**
  30495. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30496. */
  30497. class Cylindrical {
  30498. constructor( radius = 1, theta = 0, y = 0 ) {
  30499. this.radius = radius; // distance from the origin to a point in the x-z plane
  30500. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30501. this.y = y; // height above the x-z plane
  30502. return this;
  30503. }
  30504. set( radius, theta, y ) {
  30505. this.radius = radius;
  30506. this.theta = theta;
  30507. this.y = y;
  30508. return this;
  30509. }
  30510. copy( other ) {
  30511. this.radius = other.radius;
  30512. this.theta = other.theta;
  30513. this.y = other.y;
  30514. return this;
  30515. }
  30516. setFromVector3( v ) {
  30517. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30518. }
  30519. setFromCartesianCoords( x, y, z ) {
  30520. this.radius = Math.sqrt( x * x + z * z );
  30521. this.theta = Math.atan2( x, z );
  30522. this.y = y;
  30523. return this;
  30524. }
  30525. clone() {
  30526. return new this.constructor().copy( this );
  30527. }
  30528. }
  30529. const _vector$4 = /*@__PURE__*/ new Vector2();
  30530. class Box2 {
  30531. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  30532. this.isBox2 = true;
  30533. this.min = min;
  30534. this.max = max;
  30535. }
  30536. set( min, max ) {
  30537. this.min.copy( min );
  30538. this.max.copy( max );
  30539. return this;
  30540. }
  30541. setFromPoints( points ) {
  30542. this.makeEmpty();
  30543. for ( let i = 0, il = points.length; i < il; i ++ ) {
  30544. this.expandByPoint( points[ i ] );
  30545. }
  30546. return this;
  30547. }
  30548. setFromCenterAndSize( center, size ) {
  30549. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  30550. this.min.copy( center ).sub( halfSize );
  30551. this.max.copy( center ).add( halfSize );
  30552. return this;
  30553. }
  30554. clone() {
  30555. return new this.constructor().copy( this );
  30556. }
  30557. copy( box ) {
  30558. this.min.copy( box.min );
  30559. this.max.copy( box.max );
  30560. return this;
  30561. }
  30562. makeEmpty() {
  30563. this.min.x = this.min.y = + Infinity;
  30564. this.max.x = this.max.y = - Infinity;
  30565. return this;
  30566. }
  30567. isEmpty() {
  30568. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30569. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30570. }
  30571. getCenter( target ) {
  30572. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30573. }
  30574. getSize( target ) {
  30575. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30576. }
  30577. expandByPoint( point ) {
  30578. this.min.min( point );
  30579. this.max.max( point );
  30580. return this;
  30581. }
  30582. expandByVector( vector ) {
  30583. this.min.sub( vector );
  30584. this.max.add( vector );
  30585. return this;
  30586. }
  30587. expandByScalar( scalar ) {
  30588. this.min.addScalar( - scalar );
  30589. this.max.addScalar( scalar );
  30590. return this;
  30591. }
  30592. containsPoint( point ) {
  30593. return point.x < this.min.x || point.x > this.max.x ||
  30594. point.y < this.min.y || point.y > this.max.y ? false : true;
  30595. }
  30596. containsBox( box ) {
  30597. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30598. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30599. }
  30600. getParameter( point, target ) {
  30601. // This can potentially have a divide by zero if the box
  30602. // has a size dimension of 0.
  30603. return target.set(
  30604. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30605. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30606. );
  30607. }
  30608. intersectsBox( box ) {
  30609. // using 4 splitting planes to rule out intersections
  30610. return box.max.x < this.min.x || box.min.x > this.max.x ||
  30611. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  30612. }
  30613. clampPoint( point, target ) {
  30614. return target.copy( point ).clamp( this.min, this.max );
  30615. }
  30616. distanceToPoint( point ) {
  30617. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  30618. }
  30619. intersect( box ) {
  30620. this.min.max( box.min );
  30621. this.max.min( box.max );
  30622. if ( this.isEmpty() ) this.makeEmpty();
  30623. return this;
  30624. }
  30625. union( box ) {
  30626. this.min.min( box.min );
  30627. this.max.max( box.max );
  30628. return this;
  30629. }
  30630. translate( offset ) {
  30631. this.min.add( offset );
  30632. this.max.add( offset );
  30633. return this;
  30634. }
  30635. equals( box ) {
  30636. return box.min.equals( this.min ) && box.max.equals( this.max );
  30637. }
  30638. }
  30639. const _startP = /*@__PURE__*/ new Vector3();
  30640. const _startEnd = /*@__PURE__*/ new Vector3();
  30641. class Line3 {
  30642. constructor( start = new Vector3(), end = new Vector3() ) {
  30643. this.start = start;
  30644. this.end = end;
  30645. }
  30646. set( start, end ) {
  30647. this.start.copy( start );
  30648. this.end.copy( end );
  30649. return this;
  30650. }
  30651. copy( line ) {
  30652. this.start.copy( line.start );
  30653. this.end.copy( line.end );
  30654. return this;
  30655. }
  30656. getCenter( target ) {
  30657. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30658. }
  30659. delta( target ) {
  30660. return target.subVectors( this.end, this.start );
  30661. }
  30662. distanceSq() {
  30663. return this.start.distanceToSquared( this.end );
  30664. }
  30665. distance() {
  30666. return this.start.distanceTo( this.end );
  30667. }
  30668. at( t, target ) {
  30669. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30670. }
  30671. closestPointToPointParameter( point, clampToLine ) {
  30672. _startP.subVectors( point, this.start );
  30673. _startEnd.subVectors( this.end, this.start );
  30674. const startEnd2 = _startEnd.dot( _startEnd );
  30675. const startEnd_startP = _startEnd.dot( _startP );
  30676. let t = startEnd_startP / startEnd2;
  30677. if ( clampToLine ) {
  30678. t = clamp( t, 0, 1 );
  30679. }
  30680. return t;
  30681. }
  30682. closestPointToPoint( point, clampToLine, target ) {
  30683. const t = this.closestPointToPointParameter( point, clampToLine );
  30684. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30685. }
  30686. applyMatrix4( matrix ) {
  30687. this.start.applyMatrix4( matrix );
  30688. this.end.applyMatrix4( matrix );
  30689. return this;
  30690. }
  30691. equals( line ) {
  30692. return line.start.equals( this.start ) && line.end.equals( this.end );
  30693. }
  30694. clone() {
  30695. return new this.constructor().copy( this );
  30696. }
  30697. }
  30698. const _vector$3 = /*@__PURE__*/ new Vector3();
  30699. class SpotLightHelper extends Object3D {
  30700. constructor( light, color ) {
  30701. super();
  30702. this.light = light;
  30703. this.matrixAutoUpdate = false;
  30704. this.color = color;
  30705. this.type = 'SpotLightHelper';
  30706. const geometry = new BufferGeometry();
  30707. const positions = [
  30708. 0, 0, 0, 0, 0, 1,
  30709. 0, 0, 0, 1, 0, 1,
  30710. 0, 0, 0, - 1, 0, 1,
  30711. 0, 0, 0, 0, 1, 1,
  30712. 0, 0, 0, 0, - 1, 1
  30713. ];
  30714. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30715. const p1 = ( i / l ) * Math.PI * 2;
  30716. const p2 = ( j / l ) * Math.PI * 2;
  30717. positions.push(
  30718. Math.cos( p1 ), Math.sin( p1 ), 1,
  30719. Math.cos( p2 ), Math.sin( p2 ), 1
  30720. );
  30721. }
  30722. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30723. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30724. this.cone = new LineSegments( geometry, material );
  30725. this.add( this.cone );
  30726. this.update();
  30727. }
  30728. dispose() {
  30729. this.cone.geometry.dispose();
  30730. this.cone.material.dispose();
  30731. }
  30732. update() {
  30733. this.light.updateWorldMatrix( true, false );
  30734. this.light.target.updateWorldMatrix( true, false );
  30735. // update the local matrix based on the parent and light target transforms
  30736. if ( this.parent ) {
  30737. this.parent.updateWorldMatrix( true );
  30738. this.matrix
  30739. .copy( this.parent.matrixWorld )
  30740. .invert()
  30741. .multiply( this.light.matrixWorld );
  30742. } else {
  30743. this.matrix.copy( this.light.matrixWorld );
  30744. }
  30745. this.matrixWorld.copy( this.light.matrixWorld );
  30746. const coneLength = this.light.distance ? this.light.distance : 1000;
  30747. const coneWidth = coneLength * Math.tan( this.light.angle );
  30748. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30749. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  30750. this.cone.lookAt( _vector$3 );
  30751. if ( this.color !== undefined ) {
  30752. this.cone.material.color.set( this.color );
  30753. } else {
  30754. this.cone.material.color.copy( this.light.color );
  30755. }
  30756. }
  30757. }
  30758. const _vector$2 = /*@__PURE__*/ new Vector3();
  30759. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  30760. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  30761. class SkeletonHelper extends LineSegments {
  30762. constructor( object ) {
  30763. const bones = getBoneList( object );
  30764. const geometry = new BufferGeometry();
  30765. const vertices = [];
  30766. const colors = [];
  30767. const color1 = new Color( 0, 0, 1 );
  30768. const color2 = new Color( 0, 1, 0 );
  30769. for ( let i = 0; i < bones.length; i ++ ) {
  30770. const bone = bones[ i ];
  30771. if ( bone.parent && bone.parent.isBone ) {
  30772. vertices.push( 0, 0, 0 );
  30773. vertices.push( 0, 0, 0 );
  30774. colors.push( color1.r, color1.g, color1.b );
  30775. colors.push( color2.r, color2.g, color2.b );
  30776. }
  30777. }
  30778. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30779. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30780. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  30781. super( geometry, material );
  30782. this.isSkeletonHelper = true;
  30783. this.type = 'SkeletonHelper';
  30784. this.root = object;
  30785. this.bones = bones;
  30786. this.matrix = object.matrixWorld;
  30787. this.matrixAutoUpdate = false;
  30788. }
  30789. updateMatrixWorld( force ) {
  30790. const bones = this.bones;
  30791. const geometry = this.geometry;
  30792. const position = geometry.getAttribute( 'position' );
  30793. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  30794. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  30795. const bone = bones[ i ];
  30796. if ( bone.parent && bone.parent.isBone ) {
  30797. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  30798. _vector$2.setFromMatrixPosition( _boneMatrix );
  30799. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  30800. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  30801. _vector$2.setFromMatrixPosition( _boneMatrix );
  30802. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  30803. j += 2;
  30804. }
  30805. }
  30806. geometry.getAttribute( 'position' ).needsUpdate = true;
  30807. super.updateMatrixWorld( force );
  30808. }
  30809. dispose() {
  30810. this.geometry.dispose();
  30811. this.material.dispose();
  30812. }
  30813. }
  30814. function getBoneList( object ) {
  30815. const boneList = [];
  30816. if ( object.isBone === true ) {
  30817. boneList.push( object );
  30818. }
  30819. for ( let i = 0; i < object.children.length; i ++ ) {
  30820. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  30821. }
  30822. return boneList;
  30823. }
  30824. class PointLightHelper extends Mesh {
  30825. constructor( light, sphereSize, color ) {
  30826. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  30827. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30828. super( geometry, material );
  30829. this.light = light;
  30830. this.color = color;
  30831. this.type = 'PointLightHelper';
  30832. this.matrix = this.light.matrixWorld;
  30833. this.matrixAutoUpdate = false;
  30834. this.update();
  30835. /*
  30836. // TODO: delete this comment?
  30837. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  30838. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30839. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30840. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30841. const d = light.distance;
  30842. if ( d === 0.0 ) {
  30843. this.lightDistance.visible = false;
  30844. } else {
  30845. this.lightDistance.scale.set( d, d, d );
  30846. }
  30847. this.add( this.lightDistance );
  30848. */
  30849. }
  30850. dispose() {
  30851. this.geometry.dispose();
  30852. this.material.dispose();
  30853. }
  30854. update() {
  30855. this.light.updateWorldMatrix( true, false );
  30856. if ( this.color !== undefined ) {
  30857. this.material.color.set( this.color );
  30858. } else {
  30859. this.material.color.copy( this.light.color );
  30860. }
  30861. /*
  30862. const d = this.light.distance;
  30863. if ( d === 0.0 ) {
  30864. this.lightDistance.visible = false;
  30865. } else {
  30866. this.lightDistance.visible = true;
  30867. this.lightDistance.scale.set( d, d, d );
  30868. }
  30869. */
  30870. }
  30871. }
  30872. const _vector$1 = /*@__PURE__*/ new Vector3();
  30873. const _color1 = /*@__PURE__*/ new Color();
  30874. const _color2 = /*@__PURE__*/ new Color();
  30875. class HemisphereLightHelper extends Object3D {
  30876. constructor( light, size, color ) {
  30877. super();
  30878. this.light = light;
  30879. this.matrix = light.matrixWorld;
  30880. this.matrixAutoUpdate = false;
  30881. this.color = color;
  30882. this.type = 'HemisphereLightHelper';
  30883. const geometry = new OctahedronGeometry( size );
  30884. geometry.rotateY( Math.PI * 0.5 );
  30885. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30886. if ( this.color === undefined ) this.material.vertexColors = true;
  30887. const position = geometry.getAttribute( 'position' );
  30888. const colors = new Float32Array( position.count * 3 );
  30889. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30890. this.add( new Mesh( geometry, this.material ) );
  30891. this.update();
  30892. }
  30893. dispose() {
  30894. this.children[ 0 ].geometry.dispose();
  30895. this.children[ 0 ].material.dispose();
  30896. }
  30897. update() {
  30898. const mesh = this.children[ 0 ];
  30899. if ( this.color !== undefined ) {
  30900. this.material.color.set( this.color );
  30901. } else {
  30902. const colors = mesh.geometry.getAttribute( 'color' );
  30903. _color1.copy( this.light.color );
  30904. _color2.copy( this.light.groundColor );
  30905. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  30906. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  30907. colors.setXYZ( i, color.r, color.g, color.b );
  30908. }
  30909. colors.needsUpdate = true;
  30910. }
  30911. this.light.updateWorldMatrix( true, false );
  30912. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30913. }
  30914. }
  30915. class GridHelper extends LineSegments {
  30916. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  30917. color1 = new Color( color1 );
  30918. color2 = new Color( color2 );
  30919. const center = divisions / 2;
  30920. const step = size / divisions;
  30921. const halfSize = size / 2;
  30922. const vertices = [], colors = [];
  30923. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30924. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30925. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30926. const color = i === center ? color1 : color2;
  30927. color.toArray( colors, j ); j += 3;
  30928. color.toArray( colors, j ); j += 3;
  30929. color.toArray( colors, j ); j += 3;
  30930. color.toArray( colors, j ); j += 3;
  30931. }
  30932. const geometry = new BufferGeometry();
  30933. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30934. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30935. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30936. super( geometry, material );
  30937. this.type = 'GridHelper';
  30938. }
  30939. dispose() {
  30940. this.geometry.dispose();
  30941. this.material.dispose();
  30942. }
  30943. }
  30944. class PolarGridHelper extends LineSegments {
  30945. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  30946. color1 = new Color( color1 );
  30947. color2 = new Color( color2 );
  30948. const vertices = [];
  30949. const colors = [];
  30950. // create the sectors
  30951. if ( sectors > 1 ) {
  30952. for ( let i = 0; i < sectors; i ++ ) {
  30953. const v = ( i / sectors ) * ( Math.PI * 2 );
  30954. const x = Math.sin( v ) * radius;
  30955. const z = Math.cos( v ) * radius;
  30956. vertices.push( 0, 0, 0 );
  30957. vertices.push( x, 0, z );
  30958. const color = ( i & 1 ) ? color1 : color2;
  30959. colors.push( color.r, color.g, color.b );
  30960. colors.push( color.r, color.g, color.b );
  30961. }
  30962. }
  30963. // create the rings
  30964. for ( let i = 0; i < rings; i ++ ) {
  30965. const color = ( i & 1 ) ? color1 : color2;
  30966. const r = radius - ( radius / rings * i );
  30967. for ( let j = 0; j < divisions; j ++ ) {
  30968. // first vertex
  30969. let v = ( j / divisions ) * ( Math.PI * 2 );
  30970. let x = Math.sin( v ) * r;
  30971. let z = Math.cos( v ) * r;
  30972. vertices.push( x, 0, z );
  30973. colors.push( color.r, color.g, color.b );
  30974. // second vertex
  30975. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30976. x = Math.sin( v ) * r;
  30977. z = Math.cos( v ) * r;
  30978. vertices.push( x, 0, z );
  30979. colors.push( color.r, color.g, color.b );
  30980. }
  30981. }
  30982. const geometry = new BufferGeometry();
  30983. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30984. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30985. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30986. super( geometry, material );
  30987. this.type = 'PolarGridHelper';
  30988. }
  30989. dispose() {
  30990. this.geometry.dispose();
  30991. this.material.dispose();
  30992. }
  30993. }
  30994. const _v1 = /*@__PURE__*/ new Vector3();
  30995. const _v2 = /*@__PURE__*/ new Vector3();
  30996. const _v3 = /*@__PURE__*/ new Vector3();
  30997. class DirectionalLightHelper extends Object3D {
  30998. constructor( light, size, color ) {
  30999. super();
  31000. this.light = light;
  31001. this.matrix = light.matrixWorld;
  31002. this.matrixAutoUpdate = false;
  31003. this.color = color;
  31004. this.type = 'DirectionalLightHelper';
  31005. if ( size === undefined ) size = 1;
  31006. let geometry = new BufferGeometry();
  31007. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  31008. - size, size, 0,
  31009. size, size, 0,
  31010. size, - size, 0,
  31011. - size, - size, 0,
  31012. - size, size, 0
  31013. ], 3 ) );
  31014. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  31015. this.lightPlane = new Line( geometry, material );
  31016. this.add( this.lightPlane );
  31017. geometry = new BufferGeometry();
  31018. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  31019. this.targetLine = new Line( geometry, material );
  31020. this.add( this.targetLine );
  31021. this.update();
  31022. }
  31023. dispose() {
  31024. this.lightPlane.geometry.dispose();
  31025. this.lightPlane.material.dispose();
  31026. this.targetLine.geometry.dispose();
  31027. this.targetLine.material.dispose();
  31028. }
  31029. update() {
  31030. this.light.updateWorldMatrix( true, false );
  31031. this.light.target.updateWorldMatrix( true, false );
  31032. _v1.setFromMatrixPosition( this.light.matrixWorld );
  31033. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  31034. _v3.subVectors( _v2, _v1 );
  31035. this.lightPlane.lookAt( _v2 );
  31036. if ( this.color !== undefined ) {
  31037. this.lightPlane.material.color.set( this.color );
  31038. this.targetLine.material.color.set( this.color );
  31039. } else {
  31040. this.lightPlane.material.color.copy( this.light.color );
  31041. this.targetLine.material.color.copy( this.light.color );
  31042. }
  31043. this.targetLine.lookAt( _v2 );
  31044. this.targetLine.scale.z = _v3.length();
  31045. }
  31046. }
  31047. const _vector = /*@__PURE__*/ new Vector3();
  31048. const _camera = /*@__PURE__*/ new Camera();
  31049. /**
  31050. * - shows frustum, line of sight and up of the camera
  31051. * - suitable for fast updates
  31052. * - based on frustum visualization in lightgl.js shadowmap example
  31053. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  31054. */
  31055. class CameraHelper extends LineSegments {
  31056. constructor( camera ) {
  31057. const geometry = new BufferGeometry();
  31058. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  31059. const vertices = [];
  31060. const colors = [];
  31061. const pointMap = {};
  31062. // near
  31063. addLine( 'n1', 'n2' );
  31064. addLine( 'n2', 'n4' );
  31065. addLine( 'n4', 'n3' );
  31066. addLine( 'n3', 'n1' );
  31067. // far
  31068. addLine( 'f1', 'f2' );
  31069. addLine( 'f2', 'f4' );
  31070. addLine( 'f4', 'f3' );
  31071. addLine( 'f3', 'f1' );
  31072. // sides
  31073. addLine( 'n1', 'f1' );
  31074. addLine( 'n2', 'f2' );
  31075. addLine( 'n3', 'f3' );
  31076. addLine( 'n4', 'f4' );
  31077. // cone
  31078. addLine( 'p', 'n1' );
  31079. addLine( 'p', 'n2' );
  31080. addLine( 'p', 'n3' );
  31081. addLine( 'p', 'n4' );
  31082. // up
  31083. addLine( 'u1', 'u2' );
  31084. addLine( 'u2', 'u3' );
  31085. addLine( 'u3', 'u1' );
  31086. // target
  31087. addLine( 'c', 't' );
  31088. addLine( 'p', 'c' );
  31089. // cross
  31090. addLine( 'cn1', 'cn2' );
  31091. addLine( 'cn3', 'cn4' );
  31092. addLine( 'cf1', 'cf2' );
  31093. addLine( 'cf3', 'cf4' );
  31094. function addLine( a, b ) {
  31095. addPoint( a );
  31096. addPoint( b );
  31097. }
  31098. function addPoint( id ) {
  31099. vertices.push( 0, 0, 0 );
  31100. colors.push( 0, 0, 0 );
  31101. if ( pointMap[ id ] === undefined ) {
  31102. pointMap[ id ] = [];
  31103. }
  31104. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  31105. }
  31106. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31107. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31108. super( geometry, material );
  31109. this.type = 'CameraHelper';
  31110. this.camera = camera;
  31111. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  31112. this.matrix = camera.matrixWorld;
  31113. this.matrixAutoUpdate = false;
  31114. this.pointMap = pointMap;
  31115. this.update();
  31116. // colors
  31117. const colorFrustum = new Color( 0xffaa00 );
  31118. const colorCone = new Color( 0xff0000 );
  31119. const colorUp = new Color( 0x00aaff );
  31120. const colorTarget = new Color( 0xffffff );
  31121. const colorCross = new Color( 0x333333 );
  31122. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  31123. }
  31124. setColors( frustum, cone, up, target, cross ) {
  31125. const geometry = this.geometry;
  31126. const colorAttribute = geometry.getAttribute( 'color' );
  31127. // near
  31128. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  31129. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  31130. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  31131. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  31132. // far
  31133. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  31134. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  31135. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  31136. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  31137. // sides
  31138. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  31139. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  31140. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  31141. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  31142. // cone
  31143. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  31144. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  31145. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  31146. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  31147. // up
  31148. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  31149. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  31150. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  31151. // target
  31152. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  31153. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  31154. // cross
  31155. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  31156. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  31157. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  31158. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  31159. colorAttribute.needsUpdate = true;
  31160. }
  31161. update() {
  31162. const geometry = this.geometry;
  31163. const pointMap = this.pointMap;
  31164. const w = 1, h = 1;
  31165. // we need just camera projection matrix inverse
  31166. // world matrix must be identity
  31167. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  31168. // center / target
  31169. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  31170. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  31171. // near
  31172. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  31173. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  31174. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  31175. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  31176. // far
  31177. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  31178. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  31179. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  31180. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  31181. // up
  31182. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  31183. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  31184. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  31185. // cross
  31186. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  31187. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  31188. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  31189. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  31190. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  31191. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  31192. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  31193. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  31194. geometry.getAttribute( 'position' ).needsUpdate = true;
  31195. }
  31196. dispose() {
  31197. this.geometry.dispose();
  31198. this.material.dispose();
  31199. }
  31200. }
  31201. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  31202. _vector.set( x, y, z ).unproject( camera );
  31203. const points = pointMap[ point ];
  31204. if ( points !== undefined ) {
  31205. const position = geometry.getAttribute( 'position' );
  31206. for ( let i = 0, l = points.length; i < l; i ++ ) {
  31207. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  31208. }
  31209. }
  31210. }
  31211. const _box = /*@__PURE__*/ new Box3();
  31212. class BoxHelper extends LineSegments {
  31213. constructor( object, color = 0xffff00 ) {
  31214. 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 ] );
  31215. const positions = new Float32Array( 8 * 3 );
  31216. const geometry = new BufferGeometry();
  31217. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31218. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  31219. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31220. this.object = object;
  31221. this.type = 'BoxHelper';
  31222. this.matrixAutoUpdate = false;
  31223. this.update();
  31224. }
  31225. update( object ) {
  31226. if ( object !== undefined ) {
  31227. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  31228. }
  31229. if ( this.object !== undefined ) {
  31230. _box.setFromObject( this.object );
  31231. }
  31232. if ( _box.isEmpty() ) return;
  31233. const min = _box.min;
  31234. const max = _box.max;
  31235. /*
  31236. 5____4
  31237. 1/___0/|
  31238. | 6__|_7
  31239. 2/___3/
  31240. 0: max.x, max.y, max.z
  31241. 1: min.x, max.y, max.z
  31242. 2: min.x, min.y, max.z
  31243. 3: max.x, min.y, max.z
  31244. 4: max.x, max.y, min.z
  31245. 5: min.x, max.y, min.z
  31246. 6: min.x, min.y, min.z
  31247. 7: max.x, min.y, min.z
  31248. */
  31249. const position = this.geometry.attributes.position;
  31250. const array = position.array;
  31251. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  31252. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  31253. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  31254. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  31255. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  31256. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  31257. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  31258. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  31259. position.needsUpdate = true;
  31260. this.geometry.computeBoundingSphere();
  31261. }
  31262. setFromObject( object ) {
  31263. this.object = object;
  31264. this.update();
  31265. return this;
  31266. }
  31267. copy( source, recursive ) {
  31268. super.copy( source, recursive );
  31269. this.object = source.object;
  31270. return this;
  31271. }
  31272. dispose() {
  31273. this.geometry.dispose();
  31274. this.material.dispose();
  31275. }
  31276. }
  31277. class Box3Helper extends LineSegments {
  31278. constructor( box, color = 0xffff00 ) {
  31279. 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 ] );
  31280. 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 ];
  31281. const geometry = new BufferGeometry();
  31282. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31283. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31284. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31285. this.box = box;
  31286. this.type = 'Box3Helper';
  31287. this.geometry.computeBoundingSphere();
  31288. }
  31289. updateMatrixWorld( force ) {
  31290. const box = this.box;
  31291. if ( box.isEmpty() ) return;
  31292. box.getCenter( this.position );
  31293. box.getSize( this.scale );
  31294. this.scale.multiplyScalar( 0.5 );
  31295. super.updateMatrixWorld( force );
  31296. }
  31297. dispose() {
  31298. this.geometry.dispose();
  31299. this.material.dispose();
  31300. }
  31301. }
  31302. class PlaneHelper extends Line {
  31303. constructor( plane, size = 1, hex = 0xffff00 ) {
  31304. const color = hex;
  31305. 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 ];
  31306. const geometry = new BufferGeometry();
  31307. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31308. geometry.computeBoundingSphere();
  31309. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31310. this.type = 'PlaneHelper';
  31311. this.plane = plane;
  31312. this.size = size;
  31313. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  31314. const geometry2 = new BufferGeometry();
  31315. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31316. geometry2.computeBoundingSphere();
  31317. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  31318. }
  31319. updateMatrixWorld( force ) {
  31320. this.position.set( 0, 0, 0 );
  31321. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  31322. this.lookAt( this.plane.normal );
  31323. this.translateZ( - this.plane.constant );
  31324. super.updateMatrixWorld( force );
  31325. }
  31326. dispose() {
  31327. this.geometry.dispose();
  31328. this.material.dispose();
  31329. this.children[ 0 ].geometry.dispose();
  31330. this.children[ 0 ].material.dispose();
  31331. }
  31332. }
  31333. const _axis = /*@__PURE__*/ new Vector3();
  31334. let _lineGeometry, _coneGeometry;
  31335. class ArrowHelper extends Object3D {
  31336. // dir is assumed to be normalized
  31337. 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 ) {
  31338. super();
  31339. this.type = 'ArrowHelper';
  31340. if ( _lineGeometry === undefined ) {
  31341. _lineGeometry = new BufferGeometry();
  31342. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  31343. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  31344. _coneGeometry.translate( 0, - 0.5, 0 );
  31345. }
  31346. this.position.copy( origin );
  31347. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31348. this.line.matrixAutoUpdate = false;
  31349. this.add( this.line );
  31350. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  31351. this.cone.matrixAutoUpdate = false;
  31352. this.add( this.cone );
  31353. this.setDirection( dir );
  31354. this.setLength( length, headLength, headWidth );
  31355. }
  31356. setDirection( dir ) {
  31357. // dir is assumed to be normalized
  31358. if ( dir.y > 0.99999 ) {
  31359. this.quaternion.set( 0, 0, 0, 1 );
  31360. } else if ( dir.y < - 0.99999 ) {
  31361. this.quaternion.set( 1, 0, 0, 0 );
  31362. } else {
  31363. _axis.set( dir.z, 0, - dir.x ).normalize();
  31364. const radians = Math.acos( dir.y );
  31365. this.quaternion.setFromAxisAngle( _axis, radians );
  31366. }
  31367. }
  31368. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  31369. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  31370. this.line.updateMatrix();
  31371. this.cone.scale.set( headWidth, headLength, headWidth );
  31372. this.cone.position.y = length;
  31373. this.cone.updateMatrix();
  31374. }
  31375. setColor( color ) {
  31376. this.line.material.color.set( color );
  31377. this.cone.material.color.set( color );
  31378. }
  31379. copy( source ) {
  31380. super.copy( source, false );
  31381. this.line.copy( source.line );
  31382. this.cone.copy( source.cone );
  31383. return this;
  31384. }
  31385. dispose() {
  31386. this.line.geometry.dispose();
  31387. this.line.material.dispose();
  31388. this.cone.geometry.dispose();
  31389. this.cone.material.dispose();
  31390. }
  31391. }
  31392. class AxesHelper extends LineSegments {
  31393. constructor( size = 1 ) {
  31394. const vertices = [
  31395. 0, 0, 0, size, 0, 0,
  31396. 0, 0, 0, 0, size, 0,
  31397. 0, 0, 0, 0, 0, size
  31398. ];
  31399. const colors = [
  31400. 1, 0, 0, 1, 0.6, 0,
  31401. 0, 1, 0, 0.6, 1, 0,
  31402. 0, 0, 1, 0, 0.6, 1
  31403. ];
  31404. const geometry = new BufferGeometry();
  31405. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31406. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31407. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31408. super( geometry, material );
  31409. this.type = 'AxesHelper';
  31410. }
  31411. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  31412. const color = new Color();
  31413. const array = this.geometry.attributes.color.array;
  31414. color.set( xAxisColor );
  31415. color.toArray( array, 0 );
  31416. color.toArray( array, 3 );
  31417. color.set( yAxisColor );
  31418. color.toArray( array, 6 );
  31419. color.toArray( array, 9 );
  31420. color.set( zAxisColor );
  31421. color.toArray( array, 12 );
  31422. color.toArray( array, 15 );
  31423. this.geometry.attributes.color.needsUpdate = true;
  31424. return this;
  31425. }
  31426. dispose() {
  31427. this.geometry.dispose();
  31428. this.material.dispose();
  31429. }
  31430. }
  31431. class ShapePath {
  31432. constructor() {
  31433. this.type = 'ShapePath';
  31434. this.color = new Color();
  31435. this.subPaths = [];
  31436. this.currentPath = null;
  31437. }
  31438. moveTo( x, y ) {
  31439. this.currentPath = new Path();
  31440. this.subPaths.push( this.currentPath );
  31441. this.currentPath.moveTo( x, y );
  31442. return this;
  31443. }
  31444. lineTo( x, y ) {
  31445. this.currentPath.lineTo( x, y );
  31446. return this;
  31447. }
  31448. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  31449. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  31450. return this;
  31451. }
  31452. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  31453. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  31454. return this;
  31455. }
  31456. splineThru( pts ) {
  31457. this.currentPath.splineThru( pts );
  31458. return this;
  31459. }
  31460. toShapes( isCCW ) {
  31461. function toShapesNoHoles( inSubpaths ) {
  31462. const shapes = [];
  31463. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  31464. const tmpPath = inSubpaths[ i ];
  31465. const tmpShape = new Shape();
  31466. tmpShape.curves = tmpPath.curves;
  31467. shapes.push( tmpShape );
  31468. }
  31469. return shapes;
  31470. }
  31471. function isPointInsidePolygon( inPt, inPolygon ) {
  31472. const polyLen = inPolygon.length;
  31473. // inPt on polygon contour => immediate success or
  31474. // toggling of inside/outside at every single! intersection point of an edge
  31475. // with the horizontal line through inPt, left of inPt
  31476. // not counting lowerY endpoints of edges and whole edges on that line
  31477. let inside = false;
  31478. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  31479. let edgeLowPt = inPolygon[ p ];
  31480. let edgeHighPt = inPolygon[ q ];
  31481. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  31482. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  31483. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  31484. // not parallel
  31485. if ( edgeDy < 0 ) {
  31486. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  31487. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  31488. }
  31489. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  31490. if ( inPt.y === edgeLowPt.y ) {
  31491. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  31492. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31493. } else {
  31494. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  31495. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  31496. if ( perpEdge < 0 ) continue;
  31497. inside = ! inside; // true intersection left of inPt
  31498. }
  31499. } else {
  31500. // parallel or collinear
  31501. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  31502. // edge lies on the same horizontal line as inPt
  31503. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  31504. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  31505. // continue;
  31506. }
  31507. }
  31508. return inside;
  31509. }
  31510. const isClockWise = ShapeUtils.isClockWise;
  31511. const subPaths = this.subPaths;
  31512. if ( subPaths.length === 0 ) return [];
  31513. let solid, tmpPath, tmpShape;
  31514. const shapes = [];
  31515. if ( subPaths.length === 1 ) {
  31516. tmpPath = subPaths[ 0 ];
  31517. tmpShape = new Shape();
  31518. tmpShape.curves = tmpPath.curves;
  31519. shapes.push( tmpShape );
  31520. return shapes;
  31521. }
  31522. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  31523. holesFirst = isCCW ? ! holesFirst : holesFirst;
  31524. // console.log("Holes first", holesFirst);
  31525. const betterShapeHoles = [];
  31526. const newShapes = [];
  31527. let newShapeHoles = [];
  31528. let mainIdx = 0;
  31529. let tmpPoints;
  31530. newShapes[ mainIdx ] = undefined;
  31531. newShapeHoles[ mainIdx ] = [];
  31532. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  31533. tmpPath = subPaths[ i ];
  31534. tmpPoints = tmpPath.getPoints();
  31535. solid = isClockWise( tmpPoints );
  31536. solid = isCCW ? ! solid : solid;
  31537. if ( solid ) {
  31538. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  31539. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  31540. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  31541. if ( holesFirst ) mainIdx ++;
  31542. newShapeHoles[ mainIdx ] = [];
  31543. //console.log('cw', i);
  31544. } else {
  31545. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  31546. //console.log('ccw', i);
  31547. }
  31548. }
  31549. // only Holes? -> probably all Shapes with wrong orientation
  31550. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  31551. if ( newShapes.length > 1 ) {
  31552. let ambiguous = false;
  31553. let toChange = 0;
  31554. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31555. betterShapeHoles[ sIdx ] = [];
  31556. }
  31557. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31558. const sho = newShapeHoles[ sIdx ];
  31559. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  31560. const ho = sho[ hIdx ];
  31561. let hole_unassigned = true;
  31562. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  31563. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  31564. if ( sIdx !== s2Idx ) toChange ++;
  31565. if ( hole_unassigned ) {
  31566. hole_unassigned = false;
  31567. betterShapeHoles[ s2Idx ].push( ho );
  31568. } else {
  31569. ambiguous = true;
  31570. }
  31571. }
  31572. }
  31573. if ( hole_unassigned ) {
  31574. betterShapeHoles[ sIdx ].push( ho );
  31575. }
  31576. }
  31577. }
  31578. if ( toChange > 0 && ambiguous === false ) {
  31579. newShapeHoles = betterShapeHoles;
  31580. }
  31581. }
  31582. let tmpHoles;
  31583. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  31584. tmpShape = newShapes[ i ].s;
  31585. shapes.push( tmpShape );
  31586. tmpHoles = newShapeHoles[ i ];
  31587. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  31588. tmpShape.holes.push( tmpHoles[ j ].h );
  31589. }
  31590. }
  31591. //console.log("shape", shapes);
  31592. return shapes;
  31593. }
  31594. }
  31595. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  31596. constructor( width = 1, height = 1, count = 1, options = {} ) {
  31597. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  31598. super( width, height, { ...options, count } );
  31599. this.isWebGLMultipleRenderTargets = true;
  31600. }
  31601. get texture() {
  31602. return this.textures;
  31603. }
  31604. }
  31605. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31606. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31607. revision: REVISION,
  31608. } } ) );
  31609. }
  31610. if ( typeof window !== 'undefined' ) {
  31611. if ( window.__THREE__ ) {
  31612. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  31613. } else {
  31614. window.__THREE__ = REVISION;
  31615. }
  31616. }
  31617. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, createCanvasElement };