three.module.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '160';
  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 TwoPassDoubleSide = 2; // r149
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const ConstantColorFactor = 211;
  44. const OneMinusConstantColorFactor = 212;
  45. const ConstantAlphaFactor = 213;
  46. const OneMinusConstantAlphaFactor = 214;
  47. const NeverDepth = 0;
  48. const AlwaysDepth = 1;
  49. const LessDepth = 2;
  50. const LessEqualDepth = 3;
  51. const EqualDepth = 4;
  52. const GreaterEqualDepth = 5;
  53. const GreaterDepth = 6;
  54. const NotEqualDepth = 7;
  55. const MultiplyOperation = 0;
  56. const MixOperation = 1;
  57. const AddOperation = 2;
  58. const NoToneMapping = 0;
  59. const LinearToneMapping = 1;
  60. const ReinhardToneMapping = 2;
  61. const CineonToneMapping = 3;
  62. const ACESFilmicToneMapping = 4;
  63. const CustomToneMapping = 5;
  64. const AgXToneMapping = 6;
  65. const 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 AlphaFormat = 1021;
  98. const RGBAFormat = 1023;
  99. const LuminanceFormat = 1024;
  100. const LuminanceAlphaFormat = 1025;
  101. const DepthFormat = 1026;
  102. const DepthStencilFormat = 1027;
  103. const RedFormat = 1028;
  104. const RedIntegerFormat = 1029;
  105. const RGFormat = 1030;
  106. const RGIntegerFormat = 1031;
  107. const RGBAIntegerFormat = 1033;
  108. const RGB_S3TC_DXT1_Format = 33776;
  109. const RGBA_S3TC_DXT1_Format = 33777;
  110. const RGBA_S3TC_DXT3_Format = 33778;
  111. const RGBA_S3TC_DXT5_Format = 33779;
  112. const RGB_PVRTC_4BPPV1_Format = 35840;
  113. const RGB_PVRTC_2BPPV1_Format = 35841;
  114. const RGBA_PVRTC_4BPPV1_Format = 35842;
  115. const RGBA_PVRTC_2BPPV1_Format = 35843;
  116. const RGB_ETC1_Format = 36196;
  117. const RGB_ETC2_Format = 37492;
  118. const RGBA_ETC2_EAC_Format = 37496;
  119. const RGBA_ASTC_4x4_Format = 37808;
  120. const RGBA_ASTC_5x4_Format = 37809;
  121. const RGBA_ASTC_5x5_Format = 37810;
  122. const RGBA_ASTC_6x5_Format = 37811;
  123. const RGBA_ASTC_6x6_Format = 37812;
  124. const RGBA_ASTC_8x5_Format = 37813;
  125. const RGBA_ASTC_8x6_Format = 37814;
  126. const RGBA_ASTC_8x8_Format = 37815;
  127. const RGBA_ASTC_10x5_Format = 37816;
  128. const RGBA_ASTC_10x6_Format = 37817;
  129. const RGBA_ASTC_10x8_Format = 37818;
  130. const RGBA_ASTC_10x10_Format = 37819;
  131. const RGBA_ASTC_12x10_Format = 37820;
  132. const RGBA_ASTC_12x12_Format = 37821;
  133. const RGBA_BPTC_Format = 36492;
  134. const RGB_BPTC_SIGNED_Format = 36494;
  135. const RGB_BPTC_UNSIGNED_Format = 36495;
  136. const RED_RGTC1_Format = 36283;
  137. const SIGNED_RED_RGTC1_Format = 36284;
  138. const RED_GREEN_RGTC2_Format = 36285;
  139. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  140. const LoopOnce = 2200;
  141. const LoopRepeat = 2201;
  142. const LoopPingPong = 2202;
  143. const InterpolateDiscrete = 2300;
  144. const InterpolateLinear = 2301;
  145. const InterpolateSmooth = 2302;
  146. const ZeroCurvatureEnding = 2400;
  147. const ZeroSlopeEnding = 2401;
  148. const WrapAroundEnding = 2402;
  149. const NormalAnimationBlendMode = 2500;
  150. const AdditiveAnimationBlendMode = 2501;
  151. const TrianglesDrawMode = 0;
  152. const TriangleStripDrawMode = 1;
  153. const TriangleFanDrawMode = 2;
  154. /** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */
  155. const LinearEncoding = 3000;
  156. /** @deprecated Use SRGBColorSpace in three.js r152+. */
  157. const sRGBEncoding = 3001;
  158. const BasicDepthPacking = 3200;
  159. const RGBADepthPacking = 3201;
  160. const TangentSpaceNormalMap = 0;
  161. const ObjectSpaceNormalMap = 1;
  162. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  163. const NoColorSpace = '';
  164. const SRGBColorSpace = 'srgb';
  165. const LinearSRGBColorSpace = 'srgb-linear';
  166. const DisplayP3ColorSpace = 'display-p3';
  167. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  168. const LinearTransfer = 'linear';
  169. const SRGBTransfer = 'srgb';
  170. const Rec709Primaries = 'rec709';
  171. const P3Primaries = 'p3';
  172. const ZeroStencilOp = 0;
  173. const KeepStencilOp = 7680;
  174. const ReplaceStencilOp = 7681;
  175. const IncrementStencilOp = 7682;
  176. const DecrementStencilOp = 7683;
  177. const IncrementWrapStencilOp = 34055;
  178. const DecrementWrapStencilOp = 34056;
  179. const InvertStencilOp = 5386;
  180. const NeverStencilFunc = 512;
  181. const LessStencilFunc = 513;
  182. const EqualStencilFunc = 514;
  183. const LessEqualStencilFunc = 515;
  184. const GreaterStencilFunc = 516;
  185. const NotEqualStencilFunc = 517;
  186. const GreaterEqualStencilFunc = 518;
  187. const AlwaysStencilFunc = 519;
  188. const NeverCompare = 512;
  189. const LessCompare = 513;
  190. const EqualCompare = 514;
  191. const LessEqualCompare = 515;
  192. const GreaterCompare = 516;
  193. const NotEqualCompare = 517;
  194. const GreaterEqualCompare = 518;
  195. const AlwaysCompare = 519;
  196. const StaticDrawUsage = 35044;
  197. const DynamicDrawUsage = 35048;
  198. const StreamDrawUsage = 35040;
  199. const StaticReadUsage = 35045;
  200. const DynamicReadUsage = 35049;
  201. const StreamReadUsage = 35041;
  202. const StaticCopyUsage = 35046;
  203. const DynamicCopyUsage = 35050;
  204. const StreamCopyUsage = 35042;
  205. const GLSL1 = '100';
  206. const GLSL3 = '300 es';
  207. const _SRGBAFormat = 1035; // fallback for WebGL 1
  208. const WebGLCoordinateSystem = 2000;
  209. const WebGPUCoordinateSystem = 2001;
  210. /**
  211. * https://github.com/mrdoob/eventdispatcher.js/
  212. */
  213. class EventDispatcher {
  214. addEventListener( type, listener ) {
  215. if ( this._listeners === undefined ) this._listeners = {};
  216. const listeners = this._listeners;
  217. if ( listeners[ type ] === undefined ) {
  218. listeners[ type ] = [];
  219. }
  220. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  221. listeners[ type ].push( listener );
  222. }
  223. }
  224. hasEventListener( type, listener ) {
  225. if ( this._listeners === undefined ) return false;
  226. const listeners = this._listeners;
  227. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  228. }
  229. removeEventListener( type, listener ) {
  230. if ( this._listeners === undefined ) return;
  231. const listeners = this._listeners;
  232. const listenerArray = listeners[ type ];
  233. if ( listenerArray !== undefined ) {
  234. const index = listenerArray.indexOf( listener );
  235. if ( index !== - 1 ) {
  236. listenerArray.splice( index, 1 );
  237. }
  238. }
  239. }
  240. dispatchEvent( event ) {
  241. if ( this._listeners === undefined ) return;
  242. const listeners = this._listeners;
  243. const listenerArray = listeners[ event.type ];
  244. if ( listenerArray !== undefined ) {
  245. event.target = this;
  246. // Make a copy, in case listeners are removed while iterating.
  247. const array = listenerArray.slice( 0 );
  248. for ( let i = 0, l = array.length; i < l; i ++ ) {
  249. array[ i ].call( this, event );
  250. }
  251. event.target = null;
  252. }
  253. }
  254. }
  255. 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' ];
  256. let _seed = 1234567;
  257. const DEG2RAD = Math.PI / 180;
  258. const RAD2DEG = 180 / Math.PI;
  259. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  260. function generateUUID() {
  261. const d0 = Math.random() * 0xffffffff | 0;
  262. const d1 = Math.random() * 0xffffffff | 0;
  263. const d2 = Math.random() * 0xffffffff | 0;
  264. const d3 = Math.random() * 0xffffffff | 0;
  265. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  266. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  267. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  268. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  269. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  270. return uuid.toLowerCase();
  271. }
  272. function clamp( value, min, max ) {
  273. return Math.max( min, Math.min( max, value ) );
  274. }
  275. // compute euclidean modulo of m % n
  276. // https://en.wikipedia.org/wiki/Modulo_operation
  277. function euclideanModulo( n, m ) {
  278. return ( ( n % m ) + m ) % m;
  279. }
  280. // Linear mapping from range <a1, a2> to range <b1, b2>
  281. function mapLinear( x, a1, a2, b1, b2 ) {
  282. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  283. }
  284. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  285. function inverseLerp( x, y, value ) {
  286. if ( x !== y ) {
  287. return ( value - x ) / ( y - x );
  288. } else {
  289. return 0;
  290. }
  291. }
  292. // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp( x, y, t ) {
  294. return ( 1 - t ) * x + t * y;
  295. }
  296. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  297. function damp( x, y, lambda, dt ) {
  298. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  299. }
  300. // https://www.desmos.com/calculator/vcsjnyz7x4
  301. function pingpong( x, length = 1 ) {
  302. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  303. }
  304. // http://en.wikipedia.org/wiki/Smoothstep
  305. function smoothstep( x, min, max ) {
  306. if ( x <= min ) return 0;
  307. if ( x >= max ) return 1;
  308. x = ( x - min ) / ( max - min );
  309. return x * x * ( 3 - 2 * x );
  310. }
  311. function smootherstep( x, min, max ) {
  312. if ( x <= min ) return 0;
  313. if ( x >= max ) return 1;
  314. x = ( x - min ) / ( max - min );
  315. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  316. }
  317. // Random integer from <low, high> interval
  318. function randInt( low, high ) {
  319. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  320. }
  321. // Random float from <low, high> interval
  322. function randFloat( low, high ) {
  323. return low + Math.random() * ( high - low );
  324. }
  325. // Random float from <-range/2, range/2> interval
  326. function randFloatSpread( range ) {
  327. return range * ( 0.5 - Math.random() );
  328. }
  329. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  330. function seededRandom( s ) {
  331. if ( s !== undefined ) _seed = s;
  332. // Mulberry32 generator
  333. let t = _seed += 0x6D2B79F5;
  334. t = Math.imul( t ^ t >>> 15, t | 1 );
  335. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  336. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  337. }
  338. function degToRad( degrees ) {
  339. return degrees * DEG2RAD;
  340. }
  341. function radToDeg( radians ) {
  342. return radians * RAD2DEG;
  343. }
  344. function isPowerOfTwo( value ) {
  345. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  346. }
  347. function ceilPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function floorPowerOfTwo( value ) {
  351. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  352. }
  353. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  354. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  355. // rotations are applied to the axes in the order specified by 'order'
  356. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  357. // angles are in radians
  358. const cos = Math.cos;
  359. const sin = Math.sin;
  360. const c2 = cos( b / 2 );
  361. const s2 = sin( b / 2 );
  362. const c13 = cos( ( a + c ) / 2 );
  363. const s13 = sin( ( a + c ) / 2 );
  364. const c1_3 = cos( ( a - c ) / 2 );
  365. const s1_3 = sin( ( a - c ) / 2 );
  366. const c3_1 = cos( ( c - a ) / 2 );
  367. const s3_1 = sin( ( c - a ) / 2 );
  368. switch ( order ) {
  369. case 'XYX':
  370. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  371. break;
  372. case 'YZY':
  373. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  374. break;
  375. case 'ZXZ':
  376. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  377. break;
  378. case 'XZX':
  379. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  380. break;
  381. case 'YXY':
  382. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  383. break;
  384. case 'ZYZ':
  385. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  386. break;
  387. default:
  388. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  389. }
  390. }
  391. function denormalize( value, array ) {
  392. switch ( array.constructor ) {
  393. case Float32Array:
  394. return value;
  395. case Uint32Array:
  396. return value / 4294967295.0;
  397. case Uint16Array:
  398. return value / 65535.0;
  399. case Uint8Array:
  400. return value / 255.0;
  401. case Int32Array:
  402. return Math.max( value / 2147483647.0, - 1.0 );
  403. case Int16Array:
  404. return Math.max( value / 32767.0, - 1.0 );
  405. case Int8Array:
  406. return Math.max( value / 127.0, - 1.0 );
  407. default:
  408. throw new Error( 'Invalid component type.' );
  409. }
  410. }
  411. function normalize( value, array ) {
  412. switch ( array.constructor ) {
  413. case Float32Array:
  414. return value;
  415. case Uint32Array:
  416. return Math.round( value * 4294967295.0 );
  417. case Uint16Array:
  418. return Math.round( value * 65535.0 );
  419. case Uint8Array:
  420. return Math.round( value * 255.0 );
  421. case Int32Array:
  422. return Math.round( value * 2147483647.0 );
  423. case Int16Array:
  424. return Math.round( value * 32767.0 );
  425. case Int8Array:
  426. return Math.round( value * 127.0 );
  427. default:
  428. throw new Error( 'Invalid component type.' );
  429. }
  430. }
  431. const MathUtils = {
  432. DEG2RAD: DEG2RAD,
  433. RAD2DEG: RAD2DEG,
  434. generateUUID: generateUUID,
  435. clamp: clamp,
  436. euclideanModulo: euclideanModulo,
  437. mapLinear: mapLinear,
  438. inverseLerp: inverseLerp,
  439. lerp: lerp,
  440. damp: damp,
  441. pingpong: pingpong,
  442. smoothstep: smoothstep,
  443. smootherstep: smootherstep,
  444. randInt: randInt,
  445. randFloat: randFloat,
  446. randFloatSpread: randFloatSpread,
  447. seededRandom: seededRandom,
  448. degToRad: degToRad,
  449. radToDeg: radToDeg,
  450. isPowerOfTwo: isPowerOfTwo,
  451. ceilPowerOfTwo: ceilPowerOfTwo,
  452. floorPowerOfTwo: floorPowerOfTwo,
  453. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  454. normalize: normalize,
  455. denormalize: denormalize
  456. };
  457. class Vector2 {
  458. constructor( x = 0, y = 0 ) {
  459. Vector2.prototype.isVector2 = true;
  460. this.x = x;
  461. this.y = y;
  462. }
  463. get width() {
  464. return this.x;
  465. }
  466. set width( value ) {
  467. this.x = value;
  468. }
  469. get height() {
  470. return this.y;
  471. }
  472. set height( value ) {
  473. this.y = value;
  474. }
  475. set( x, y ) {
  476. this.x = x;
  477. this.y = y;
  478. return this;
  479. }
  480. setScalar( scalar ) {
  481. this.x = scalar;
  482. this.y = scalar;
  483. return this;
  484. }
  485. setX( x ) {
  486. this.x = x;
  487. return this;
  488. }
  489. setY( y ) {
  490. this.y = y;
  491. return this;
  492. }
  493. setComponent( index, value ) {
  494. switch ( index ) {
  495. case 0: this.x = value; break;
  496. case 1: this.y = value; break;
  497. default: throw new Error( 'index is out of range: ' + index );
  498. }
  499. return this;
  500. }
  501. getComponent( index ) {
  502. switch ( index ) {
  503. case 0: return this.x;
  504. case 1: return this.y;
  505. default: throw new Error( 'index is out of range: ' + index );
  506. }
  507. }
  508. clone() {
  509. return new this.constructor( this.x, this.y );
  510. }
  511. copy( v ) {
  512. this.x = v.x;
  513. this.y = v.y;
  514. return this;
  515. }
  516. add( v ) {
  517. this.x += v.x;
  518. this.y += v.y;
  519. return this;
  520. }
  521. addScalar( s ) {
  522. this.x += s;
  523. this.y += s;
  524. return this;
  525. }
  526. addVectors( a, b ) {
  527. this.x = a.x + b.x;
  528. this.y = a.y + b.y;
  529. return this;
  530. }
  531. addScaledVector( v, s ) {
  532. this.x += v.x * s;
  533. this.y += v.y * s;
  534. return this;
  535. }
  536. sub( v ) {
  537. this.x -= v.x;
  538. this.y -= v.y;
  539. return this;
  540. }
  541. subScalar( s ) {
  542. this.x -= s;
  543. this.y -= s;
  544. return this;
  545. }
  546. subVectors( a, b ) {
  547. this.x = a.x - b.x;
  548. this.y = a.y - b.y;
  549. return this;
  550. }
  551. multiply( v ) {
  552. this.x *= v.x;
  553. this.y *= v.y;
  554. return this;
  555. }
  556. multiplyScalar( scalar ) {
  557. this.x *= scalar;
  558. this.y *= scalar;
  559. return this;
  560. }
  561. divide( v ) {
  562. this.x /= v.x;
  563. this.y /= v.y;
  564. return this;
  565. }
  566. divideScalar( scalar ) {
  567. return this.multiplyScalar( 1 / scalar );
  568. }
  569. applyMatrix3( m ) {
  570. const x = this.x, y = this.y;
  571. const e = m.elements;
  572. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  573. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  574. return this;
  575. }
  576. min( v ) {
  577. this.x = Math.min( this.x, v.x );
  578. this.y = Math.min( this.y, v.y );
  579. return this;
  580. }
  581. max( v ) {
  582. this.x = Math.max( this.x, v.x );
  583. this.y = Math.max( this.y, v.y );
  584. return this;
  585. }
  586. clamp( min, max ) {
  587. // assumes min < max, componentwise
  588. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  589. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  590. return this;
  591. }
  592. clampScalar( minVal, maxVal ) {
  593. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  594. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  595. return this;
  596. }
  597. clampLength( min, max ) {
  598. const length = this.length();
  599. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  600. }
  601. floor() {
  602. this.x = Math.floor( this.x );
  603. this.y = Math.floor( this.y );
  604. return this;
  605. }
  606. ceil() {
  607. this.x = Math.ceil( this.x );
  608. this.y = Math.ceil( this.y );
  609. return this;
  610. }
  611. round() {
  612. this.x = Math.round( this.x );
  613. this.y = Math.round( this.y );
  614. return this;
  615. }
  616. roundToZero() {
  617. this.x = Math.trunc( this.x );
  618. this.y = Math.trunc( this.y );
  619. return this;
  620. }
  621. negate() {
  622. this.x = - this.x;
  623. this.y = - this.y;
  624. return this;
  625. }
  626. dot( v ) {
  627. return this.x * v.x + this.y * v.y;
  628. }
  629. cross( v ) {
  630. return this.x * v.y - this.y * v.x;
  631. }
  632. lengthSq() {
  633. return this.x * this.x + this.y * this.y;
  634. }
  635. length() {
  636. return Math.sqrt( this.x * this.x + this.y * this.y );
  637. }
  638. manhattanLength() {
  639. return Math.abs( this.x ) + Math.abs( this.y );
  640. }
  641. normalize() {
  642. return this.divideScalar( this.length() || 1 );
  643. }
  644. angle() {
  645. // computes the angle in radians with respect to the positive x-axis
  646. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  647. return angle;
  648. }
  649. angleTo( v ) {
  650. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  651. if ( denominator === 0 ) return Math.PI / 2;
  652. const theta = this.dot( v ) / denominator;
  653. // clamp, to handle numerical problems
  654. return Math.acos( clamp( theta, - 1, 1 ) );
  655. }
  656. distanceTo( v ) {
  657. return Math.sqrt( this.distanceToSquared( v ) );
  658. }
  659. distanceToSquared( v ) {
  660. const dx = this.x - v.x, dy = this.y - v.y;
  661. return dx * dx + dy * dy;
  662. }
  663. manhattanDistanceTo( v ) {
  664. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  665. }
  666. setLength( length ) {
  667. return this.normalize().multiplyScalar( length );
  668. }
  669. lerp( v, alpha ) {
  670. this.x += ( v.x - this.x ) * alpha;
  671. this.y += ( v.y - this.y ) * alpha;
  672. return this;
  673. }
  674. lerpVectors( v1, v2, alpha ) {
  675. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  676. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  677. return this;
  678. }
  679. equals( v ) {
  680. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  681. }
  682. fromArray( array, offset = 0 ) {
  683. this.x = array[ offset ];
  684. this.y = array[ offset + 1 ];
  685. return this;
  686. }
  687. toArray( array = [], offset = 0 ) {
  688. array[ offset ] = this.x;
  689. array[ offset + 1 ] = this.y;
  690. return array;
  691. }
  692. fromBufferAttribute( attribute, index ) {
  693. this.x = attribute.getX( index );
  694. this.y = attribute.getY( index );
  695. return this;
  696. }
  697. rotateAround( center, angle ) {
  698. const c = Math.cos( angle ), s = Math.sin( angle );
  699. const x = this.x - center.x;
  700. const y = this.y - center.y;
  701. this.x = x * c - y * s + center.x;
  702. this.y = x * s + y * c + center.y;
  703. return this;
  704. }
  705. random() {
  706. this.x = Math.random();
  707. this.y = Math.random();
  708. return this;
  709. }
  710. *[ Symbol.iterator ]() {
  711. yield this.x;
  712. yield this.y;
  713. }
  714. }
  715. class Matrix3 {
  716. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  717. Matrix3.prototype.isMatrix3 = true;
  718. this.elements = [
  719. 1, 0, 0,
  720. 0, 1, 0,
  721. 0, 0, 1
  722. ];
  723. if ( n11 !== undefined ) {
  724. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  725. }
  726. }
  727. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  728. const te = this.elements;
  729. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  730. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  731. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  732. return this;
  733. }
  734. identity() {
  735. this.set(
  736. 1, 0, 0,
  737. 0, 1, 0,
  738. 0, 0, 1
  739. );
  740. return this;
  741. }
  742. copy( m ) {
  743. const te = this.elements;
  744. const me = m.elements;
  745. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  746. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  747. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  748. return this;
  749. }
  750. extractBasis( xAxis, yAxis, zAxis ) {
  751. xAxis.setFromMatrix3Column( this, 0 );
  752. yAxis.setFromMatrix3Column( this, 1 );
  753. zAxis.setFromMatrix3Column( this, 2 );
  754. return this;
  755. }
  756. setFromMatrix4( m ) {
  757. const me = m.elements;
  758. this.set(
  759. me[ 0 ], me[ 4 ], me[ 8 ],
  760. me[ 1 ], me[ 5 ], me[ 9 ],
  761. me[ 2 ], me[ 6 ], me[ 10 ]
  762. );
  763. return this;
  764. }
  765. multiply( m ) {
  766. return this.multiplyMatrices( this, m );
  767. }
  768. premultiply( m ) {
  769. return this.multiplyMatrices( m, this );
  770. }
  771. multiplyMatrices( a, b ) {
  772. const ae = a.elements;
  773. const be = b.elements;
  774. const te = this.elements;
  775. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  776. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  777. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  778. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  779. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  780. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  781. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  782. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  783. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  784. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  785. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  786. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  787. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  788. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  789. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  790. return this;
  791. }
  792. multiplyScalar( s ) {
  793. const te = this.elements;
  794. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  795. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  796. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  797. return this;
  798. }
  799. determinant() {
  800. const te = this.elements;
  801. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  802. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  803. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  804. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  805. }
  806. invert() {
  807. const te = this.elements,
  808. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  809. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  810. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  811. t11 = n33 * n22 - n32 * n23,
  812. t12 = n32 * n13 - n33 * n12,
  813. t13 = n23 * n12 - n22 * n13,
  814. det = n11 * t11 + n21 * t12 + n31 * t13;
  815. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  816. const detInv = 1 / det;
  817. te[ 0 ] = t11 * detInv;
  818. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  819. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  820. te[ 3 ] = t12 * detInv;
  821. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  822. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  823. te[ 6 ] = t13 * detInv;
  824. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  825. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  826. return this;
  827. }
  828. transpose() {
  829. let tmp;
  830. const m = this.elements;
  831. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  832. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  833. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  834. return this;
  835. }
  836. getNormalMatrix( matrix4 ) {
  837. return this.setFromMatrix4( matrix4 ).invert().transpose();
  838. }
  839. transposeIntoArray( r ) {
  840. const m = this.elements;
  841. r[ 0 ] = m[ 0 ];
  842. r[ 1 ] = m[ 3 ];
  843. r[ 2 ] = m[ 6 ];
  844. r[ 3 ] = m[ 1 ];
  845. r[ 4 ] = m[ 4 ];
  846. r[ 5 ] = m[ 7 ];
  847. r[ 6 ] = m[ 2 ];
  848. r[ 7 ] = m[ 5 ];
  849. r[ 8 ] = m[ 8 ];
  850. return this;
  851. }
  852. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  853. const c = Math.cos( rotation );
  854. const s = Math.sin( rotation );
  855. this.set(
  856. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  857. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  858. 0, 0, 1
  859. );
  860. return this;
  861. }
  862. //
  863. scale( sx, sy ) {
  864. this.premultiply( _m3.makeScale( sx, sy ) );
  865. return this;
  866. }
  867. rotate( theta ) {
  868. this.premultiply( _m3.makeRotation( - theta ) );
  869. return this;
  870. }
  871. translate( tx, ty ) {
  872. this.premultiply( _m3.makeTranslation( tx, ty ) );
  873. return this;
  874. }
  875. // for 2D Transforms
  876. makeTranslation( x, y ) {
  877. if ( x.isVector2 ) {
  878. this.set(
  879. 1, 0, x.x,
  880. 0, 1, x.y,
  881. 0, 0, 1
  882. );
  883. } else {
  884. this.set(
  885. 1, 0, x,
  886. 0, 1, y,
  887. 0, 0, 1
  888. );
  889. }
  890. return this;
  891. }
  892. makeRotation( theta ) {
  893. // counterclockwise
  894. const c = Math.cos( theta );
  895. const s = Math.sin( theta );
  896. this.set(
  897. c, - s, 0,
  898. s, c, 0,
  899. 0, 0, 1
  900. );
  901. return this;
  902. }
  903. makeScale( x, y ) {
  904. this.set(
  905. x, 0, 0,
  906. 0, y, 0,
  907. 0, 0, 1
  908. );
  909. return this;
  910. }
  911. //
  912. equals( matrix ) {
  913. const te = this.elements;
  914. const me = matrix.elements;
  915. for ( let i = 0; i < 9; i ++ ) {
  916. if ( te[ i ] !== me[ i ] ) return false;
  917. }
  918. return true;
  919. }
  920. fromArray( array, offset = 0 ) {
  921. for ( let i = 0; i < 9; i ++ ) {
  922. this.elements[ i ] = array[ i + offset ];
  923. }
  924. return this;
  925. }
  926. toArray( array = [], offset = 0 ) {
  927. const te = this.elements;
  928. array[ offset ] = te[ 0 ];
  929. array[ offset + 1 ] = te[ 1 ];
  930. array[ offset + 2 ] = te[ 2 ];
  931. array[ offset + 3 ] = te[ 3 ];
  932. array[ offset + 4 ] = te[ 4 ];
  933. array[ offset + 5 ] = te[ 5 ];
  934. array[ offset + 6 ] = te[ 6 ];
  935. array[ offset + 7 ] = te[ 7 ];
  936. array[ offset + 8 ] = te[ 8 ];
  937. return array;
  938. }
  939. clone() {
  940. return new this.constructor().fromArray( this.elements );
  941. }
  942. }
  943. const _m3 = /*@__PURE__*/ new Matrix3();
  944. function arrayNeedsUint32( array ) {
  945. // assumes larger values usually on last
  946. for ( let i = array.length - 1; i >= 0; -- i ) {
  947. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  948. }
  949. return false;
  950. }
  951. const TYPED_ARRAYS = {
  952. Int8Array: Int8Array,
  953. Uint8Array: Uint8Array,
  954. Uint8ClampedArray: Uint8ClampedArray,
  955. Int16Array: Int16Array,
  956. Uint16Array: Uint16Array,
  957. Int32Array: Int32Array,
  958. Uint32Array: Uint32Array,
  959. Float32Array: Float32Array,
  960. Float64Array: Float64Array
  961. };
  962. function getTypedArray( type, buffer ) {
  963. return new TYPED_ARRAYS[ type ]( buffer );
  964. }
  965. function createElementNS( name ) {
  966. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  967. }
  968. function createCanvasElement() {
  969. const canvas = createElementNS( 'canvas' );
  970. canvas.style.display = 'block';
  971. return canvas;
  972. }
  973. const _cache = {};
  974. function warnOnce( message ) {
  975. if ( message in _cache ) return;
  976. _cache[ message ] = true;
  977. console.warn( message );
  978. }
  979. /**
  980. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  981. * or clipping. Based on W3C specifications for sRGB and Display P3,
  982. * and ICC specifications for the D50 connection space. Values in/out
  983. * are _linear_ sRGB and _linear_ Display P3.
  984. *
  985. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  986. *
  987. * Reference:
  988. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  989. */
  990. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  991. 0.8224621, 0.177538, 0.0,
  992. 0.0331941, 0.9668058, 0.0,
  993. 0.0170827, 0.0723974, 0.9105199,
  994. );
  995. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  996. 1.2249401, - 0.2249404, 0.0,
  997. - 0.0420569, 1.0420571, 0.0,
  998. - 0.0196376, - 0.0786361, 1.0982735
  999. );
  1000. /**
  1001. * Defines supported color spaces by transfer function and primaries,
  1002. * and provides conversions to/from the Linear-sRGB reference space.
  1003. */
  1004. const COLOR_SPACES = {
  1005. [ LinearSRGBColorSpace ]: {
  1006. transfer: LinearTransfer,
  1007. primaries: Rec709Primaries,
  1008. toReference: ( color ) => color,
  1009. fromReference: ( color ) => color,
  1010. },
  1011. [ SRGBColorSpace ]: {
  1012. transfer: SRGBTransfer,
  1013. primaries: Rec709Primaries,
  1014. toReference: ( color ) => color.convertSRGBToLinear(),
  1015. fromReference: ( color ) => color.convertLinearToSRGB(),
  1016. },
  1017. [ LinearDisplayP3ColorSpace ]: {
  1018. transfer: LinearTransfer,
  1019. primaries: P3Primaries,
  1020. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1021. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1022. },
  1023. [ DisplayP3ColorSpace ]: {
  1024. transfer: SRGBTransfer,
  1025. primaries: P3Primaries,
  1026. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1027. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1028. },
  1029. };
  1030. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1031. const ColorManagement = {
  1032. enabled: true,
  1033. _workingColorSpace: LinearSRGBColorSpace,
  1034. get workingColorSpace() {
  1035. return this._workingColorSpace;
  1036. },
  1037. set workingColorSpace( colorSpace ) {
  1038. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1039. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1040. }
  1041. this._workingColorSpace = colorSpace;
  1042. },
  1043. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1044. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1045. return color;
  1046. }
  1047. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1048. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1049. return targetFromReference( sourceToReference( color ) );
  1050. },
  1051. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1052. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1053. },
  1054. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1055. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1056. },
  1057. getPrimaries: function ( colorSpace ) {
  1058. return COLOR_SPACES[ colorSpace ].primaries;
  1059. },
  1060. getTransfer: function ( colorSpace ) {
  1061. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1062. return COLOR_SPACES[ colorSpace ].transfer;
  1063. },
  1064. };
  1065. function SRGBToLinear( c ) {
  1066. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1067. }
  1068. function LinearToSRGB( c ) {
  1069. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1070. }
  1071. let _canvas;
  1072. class ImageUtils {
  1073. static getDataURL( image ) {
  1074. if ( /^data:/i.test( image.src ) ) {
  1075. return image.src;
  1076. }
  1077. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1078. return image.src;
  1079. }
  1080. let canvas;
  1081. if ( image instanceof HTMLCanvasElement ) {
  1082. canvas = image;
  1083. } else {
  1084. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1085. _canvas.width = image.width;
  1086. _canvas.height = image.height;
  1087. const context = _canvas.getContext( '2d' );
  1088. if ( image instanceof ImageData ) {
  1089. context.putImageData( image, 0, 0 );
  1090. } else {
  1091. context.drawImage( image, 0, 0, image.width, image.height );
  1092. }
  1093. canvas = _canvas;
  1094. }
  1095. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1096. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1097. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1098. } else {
  1099. return canvas.toDataURL( 'image/png' );
  1100. }
  1101. }
  1102. static sRGBToLinear( image ) {
  1103. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1104. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1105. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1106. const canvas = createElementNS( 'canvas' );
  1107. canvas.width = image.width;
  1108. canvas.height = image.height;
  1109. const context = canvas.getContext( '2d' );
  1110. context.drawImage( image, 0, 0, image.width, image.height );
  1111. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1112. const data = imageData.data;
  1113. for ( let i = 0; i < data.length; i ++ ) {
  1114. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1115. }
  1116. context.putImageData( imageData, 0, 0 );
  1117. return canvas;
  1118. } else if ( image.data ) {
  1119. const data = image.data.slice( 0 );
  1120. for ( let i = 0; i < data.length; i ++ ) {
  1121. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1122. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1123. } else {
  1124. // assuming float
  1125. data[ i ] = SRGBToLinear( data[ i ] );
  1126. }
  1127. }
  1128. return {
  1129. data: data,
  1130. width: image.width,
  1131. height: image.height
  1132. };
  1133. } else {
  1134. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1135. return image;
  1136. }
  1137. }
  1138. }
  1139. let _sourceId = 0;
  1140. class Source {
  1141. constructor( data = null ) {
  1142. this.isSource = true;
  1143. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1144. this.uuid = generateUUID();
  1145. this.data = data;
  1146. this.version = 0;
  1147. }
  1148. set needsUpdate( value ) {
  1149. if ( value === true ) this.version ++;
  1150. }
  1151. toJSON( meta ) {
  1152. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1153. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1154. return meta.images[ this.uuid ];
  1155. }
  1156. const output = {
  1157. uuid: this.uuid,
  1158. url: ''
  1159. };
  1160. const data = this.data;
  1161. if ( data !== null ) {
  1162. let url;
  1163. if ( Array.isArray( data ) ) {
  1164. // cube texture
  1165. url = [];
  1166. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1167. if ( data[ i ].isDataTexture ) {
  1168. url.push( serializeImage( data[ i ].image ) );
  1169. } else {
  1170. url.push( serializeImage( data[ i ] ) );
  1171. }
  1172. }
  1173. } else {
  1174. // texture
  1175. url = serializeImage( data );
  1176. }
  1177. output.url = url;
  1178. }
  1179. if ( ! isRootObject ) {
  1180. meta.images[ this.uuid ] = output;
  1181. }
  1182. return output;
  1183. }
  1184. }
  1185. function serializeImage( image ) {
  1186. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1187. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1188. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1189. // default images
  1190. return ImageUtils.getDataURL( image );
  1191. } else {
  1192. if ( image.data ) {
  1193. // images of DataTexture
  1194. return {
  1195. data: Array.from( image.data ),
  1196. width: image.width,
  1197. height: image.height,
  1198. type: image.data.constructor.name
  1199. };
  1200. } else {
  1201. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1202. return {};
  1203. }
  1204. }
  1205. }
  1206. let _textureId = 0;
  1207. class Texture extends EventDispatcher {
  1208. 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 ) {
  1209. super();
  1210. this.isTexture = true;
  1211. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1212. this.uuid = generateUUID();
  1213. this.name = '';
  1214. this.source = new Source( image );
  1215. this.mipmaps = [];
  1216. this.mapping = mapping;
  1217. this.channel = 0;
  1218. this.wrapS = wrapS;
  1219. this.wrapT = wrapT;
  1220. this.magFilter = magFilter;
  1221. this.minFilter = minFilter;
  1222. this.anisotropy = anisotropy;
  1223. this.format = format;
  1224. this.internalFormat = null;
  1225. this.type = type;
  1226. this.offset = new Vector2( 0, 0 );
  1227. this.repeat = new Vector2( 1, 1 );
  1228. this.center = new Vector2( 0, 0 );
  1229. this.rotation = 0;
  1230. this.matrixAutoUpdate = true;
  1231. this.matrix = new Matrix3();
  1232. this.generateMipmaps = true;
  1233. this.premultiplyAlpha = false;
  1234. this.flipY = true;
  1235. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1236. if ( typeof colorSpace === 'string' ) {
  1237. this.colorSpace = colorSpace;
  1238. } else { // @deprecated, r152
  1239. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1240. this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1241. }
  1242. this.userData = {};
  1243. this.version = 0;
  1244. this.onUpdate = null;
  1245. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1246. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1247. }
  1248. get image() {
  1249. return this.source.data;
  1250. }
  1251. set image( value = null ) {
  1252. this.source.data = value;
  1253. }
  1254. updateMatrix() {
  1255. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1256. }
  1257. clone() {
  1258. return new this.constructor().copy( this );
  1259. }
  1260. copy( source ) {
  1261. this.name = source.name;
  1262. this.source = source.source;
  1263. this.mipmaps = source.mipmaps.slice( 0 );
  1264. this.mapping = source.mapping;
  1265. this.channel = source.channel;
  1266. this.wrapS = source.wrapS;
  1267. this.wrapT = source.wrapT;
  1268. this.magFilter = source.magFilter;
  1269. this.minFilter = source.minFilter;
  1270. this.anisotropy = source.anisotropy;
  1271. this.format = source.format;
  1272. this.internalFormat = source.internalFormat;
  1273. this.type = source.type;
  1274. this.offset.copy( source.offset );
  1275. this.repeat.copy( source.repeat );
  1276. this.center.copy( source.center );
  1277. this.rotation = source.rotation;
  1278. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1279. this.matrix.copy( source.matrix );
  1280. this.generateMipmaps = source.generateMipmaps;
  1281. this.premultiplyAlpha = source.premultiplyAlpha;
  1282. this.flipY = source.flipY;
  1283. this.unpackAlignment = source.unpackAlignment;
  1284. this.colorSpace = source.colorSpace;
  1285. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1286. this.needsUpdate = true;
  1287. return this;
  1288. }
  1289. toJSON( meta ) {
  1290. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1291. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1292. return meta.textures[ this.uuid ];
  1293. }
  1294. const output = {
  1295. metadata: {
  1296. version: 4.6,
  1297. type: 'Texture',
  1298. generator: 'Texture.toJSON'
  1299. },
  1300. uuid: this.uuid,
  1301. name: this.name,
  1302. image: this.source.toJSON( meta ).uuid,
  1303. mapping: this.mapping,
  1304. channel: this.channel,
  1305. repeat: [ this.repeat.x, this.repeat.y ],
  1306. offset: [ this.offset.x, this.offset.y ],
  1307. center: [ this.center.x, this.center.y ],
  1308. rotation: this.rotation,
  1309. wrap: [ this.wrapS, this.wrapT ],
  1310. format: this.format,
  1311. internalFormat: this.internalFormat,
  1312. type: this.type,
  1313. colorSpace: this.colorSpace,
  1314. minFilter: this.minFilter,
  1315. magFilter: this.magFilter,
  1316. anisotropy: this.anisotropy,
  1317. flipY: this.flipY,
  1318. generateMipmaps: this.generateMipmaps,
  1319. premultiplyAlpha: this.premultiplyAlpha,
  1320. unpackAlignment: this.unpackAlignment
  1321. };
  1322. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1323. if ( ! isRootObject ) {
  1324. meta.textures[ this.uuid ] = output;
  1325. }
  1326. return output;
  1327. }
  1328. dispose() {
  1329. this.dispatchEvent( { type: 'dispose' } );
  1330. }
  1331. transformUv( uv ) {
  1332. if ( this.mapping !== UVMapping ) return uv;
  1333. uv.applyMatrix3( this.matrix );
  1334. if ( uv.x < 0 || uv.x > 1 ) {
  1335. switch ( this.wrapS ) {
  1336. case RepeatWrapping:
  1337. uv.x = uv.x - Math.floor( uv.x );
  1338. break;
  1339. case ClampToEdgeWrapping:
  1340. uv.x = uv.x < 0 ? 0 : 1;
  1341. break;
  1342. case MirroredRepeatWrapping:
  1343. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1344. uv.x = Math.ceil( uv.x ) - uv.x;
  1345. } else {
  1346. uv.x = uv.x - Math.floor( uv.x );
  1347. }
  1348. break;
  1349. }
  1350. }
  1351. if ( uv.y < 0 || uv.y > 1 ) {
  1352. switch ( this.wrapT ) {
  1353. case RepeatWrapping:
  1354. uv.y = uv.y - Math.floor( uv.y );
  1355. break;
  1356. case ClampToEdgeWrapping:
  1357. uv.y = uv.y < 0 ? 0 : 1;
  1358. break;
  1359. case MirroredRepeatWrapping:
  1360. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1361. uv.y = Math.ceil( uv.y ) - uv.y;
  1362. } else {
  1363. uv.y = uv.y - Math.floor( uv.y );
  1364. }
  1365. break;
  1366. }
  1367. }
  1368. if ( this.flipY ) {
  1369. uv.y = 1 - uv.y;
  1370. }
  1371. return uv;
  1372. }
  1373. set needsUpdate( value ) {
  1374. if ( value === true ) {
  1375. this.version ++;
  1376. this.source.needsUpdate = true;
  1377. }
  1378. }
  1379. get encoding() { // @deprecated, r152
  1380. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1381. return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  1382. }
  1383. set encoding( encoding ) { // @deprecated, r152
  1384. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1385. this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1386. }
  1387. }
  1388. Texture.DEFAULT_IMAGE = null;
  1389. Texture.DEFAULT_MAPPING = UVMapping;
  1390. Texture.DEFAULT_ANISOTROPY = 1;
  1391. class Vector4 {
  1392. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1393. Vector4.prototype.isVector4 = true;
  1394. this.x = x;
  1395. this.y = y;
  1396. this.z = z;
  1397. this.w = w;
  1398. }
  1399. get width() {
  1400. return this.z;
  1401. }
  1402. set width( value ) {
  1403. this.z = value;
  1404. }
  1405. get height() {
  1406. return this.w;
  1407. }
  1408. set height( value ) {
  1409. this.w = value;
  1410. }
  1411. set( x, y, z, w ) {
  1412. this.x = x;
  1413. this.y = y;
  1414. this.z = z;
  1415. this.w = w;
  1416. return this;
  1417. }
  1418. setScalar( scalar ) {
  1419. this.x = scalar;
  1420. this.y = scalar;
  1421. this.z = scalar;
  1422. this.w = scalar;
  1423. return this;
  1424. }
  1425. setX( x ) {
  1426. this.x = x;
  1427. return this;
  1428. }
  1429. setY( y ) {
  1430. this.y = y;
  1431. return this;
  1432. }
  1433. setZ( z ) {
  1434. this.z = z;
  1435. return this;
  1436. }
  1437. setW( w ) {
  1438. this.w = w;
  1439. return this;
  1440. }
  1441. setComponent( index, value ) {
  1442. switch ( index ) {
  1443. case 0: this.x = value; break;
  1444. case 1: this.y = value; break;
  1445. case 2: this.z = value; break;
  1446. case 3: this.w = value; break;
  1447. default: throw new Error( 'index is out of range: ' + index );
  1448. }
  1449. return this;
  1450. }
  1451. getComponent( index ) {
  1452. switch ( index ) {
  1453. case 0: return this.x;
  1454. case 1: return this.y;
  1455. case 2: return this.z;
  1456. case 3: return this.w;
  1457. default: throw new Error( 'index is out of range: ' + index );
  1458. }
  1459. }
  1460. clone() {
  1461. return new this.constructor( this.x, this.y, this.z, this.w );
  1462. }
  1463. copy( v ) {
  1464. this.x = v.x;
  1465. this.y = v.y;
  1466. this.z = v.z;
  1467. this.w = ( v.w !== undefined ) ? v.w : 1;
  1468. return this;
  1469. }
  1470. add( v ) {
  1471. this.x += v.x;
  1472. this.y += v.y;
  1473. this.z += v.z;
  1474. this.w += v.w;
  1475. return this;
  1476. }
  1477. addScalar( s ) {
  1478. this.x += s;
  1479. this.y += s;
  1480. this.z += s;
  1481. this.w += s;
  1482. return this;
  1483. }
  1484. addVectors( a, b ) {
  1485. this.x = a.x + b.x;
  1486. this.y = a.y + b.y;
  1487. this.z = a.z + b.z;
  1488. this.w = a.w + b.w;
  1489. return this;
  1490. }
  1491. addScaledVector( v, s ) {
  1492. this.x += v.x * s;
  1493. this.y += v.y * s;
  1494. this.z += v.z * s;
  1495. this.w += v.w * s;
  1496. return this;
  1497. }
  1498. sub( v ) {
  1499. this.x -= v.x;
  1500. this.y -= v.y;
  1501. this.z -= v.z;
  1502. this.w -= v.w;
  1503. return this;
  1504. }
  1505. subScalar( s ) {
  1506. this.x -= s;
  1507. this.y -= s;
  1508. this.z -= s;
  1509. this.w -= s;
  1510. return this;
  1511. }
  1512. subVectors( a, b ) {
  1513. this.x = a.x - b.x;
  1514. this.y = a.y - b.y;
  1515. this.z = a.z - b.z;
  1516. this.w = a.w - b.w;
  1517. return this;
  1518. }
  1519. multiply( v ) {
  1520. this.x *= v.x;
  1521. this.y *= v.y;
  1522. this.z *= v.z;
  1523. this.w *= v.w;
  1524. return this;
  1525. }
  1526. multiplyScalar( scalar ) {
  1527. this.x *= scalar;
  1528. this.y *= scalar;
  1529. this.z *= scalar;
  1530. this.w *= scalar;
  1531. return this;
  1532. }
  1533. applyMatrix4( m ) {
  1534. const x = this.x, y = this.y, z = this.z, w = this.w;
  1535. const e = m.elements;
  1536. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1537. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1538. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1539. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1540. return this;
  1541. }
  1542. divideScalar( scalar ) {
  1543. return this.multiplyScalar( 1 / scalar );
  1544. }
  1545. setAxisAngleFromQuaternion( q ) {
  1546. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1547. // q is assumed to be normalized
  1548. this.w = 2 * Math.acos( q.w );
  1549. const s = Math.sqrt( 1 - q.w * q.w );
  1550. if ( s < 0.0001 ) {
  1551. this.x = 1;
  1552. this.y = 0;
  1553. this.z = 0;
  1554. } else {
  1555. this.x = q.x / s;
  1556. this.y = q.y / s;
  1557. this.z = q.z / s;
  1558. }
  1559. return this;
  1560. }
  1561. setAxisAngleFromRotationMatrix( m ) {
  1562. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1563. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1564. let angle, x, y, z; // variables for result
  1565. const epsilon = 0.01, // margin to allow for rounding errors
  1566. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1567. te = m.elements,
  1568. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1569. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1570. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1571. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1572. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1573. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1574. // singularity found
  1575. // first check for identity matrix which must have +1 for all terms
  1576. // in leading diagonal and zero in other terms
  1577. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1578. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1579. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1580. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1581. // this singularity is identity matrix so angle = 0
  1582. this.set( 1, 0, 0, 0 );
  1583. return this; // zero angle, arbitrary axis
  1584. }
  1585. // otherwise this singularity is angle = 180
  1586. angle = Math.PI;
  1587. const xx = ( m11 + 1 ) / 2;
  1588. const yy = ( m22 + 1 ) / 2;
  1589. const zz = ( m33 + 1 ) / 2;
  1590. const xy = ( m12 + m21 ) / 4;
  1591. const xz = ( m13 + m31 ) / 4;
  1592. const yz = ( m23 + m32 ) / 4;
  1593. if ( ( xx > yy ) && ( xx > zz ) ) {
  1594. // m11 is the largest diagonal term
  1595. if ( xx < epsilon ) {
  1596. x = 0;
  1597. y = 0.707106781;
  1598. z = 0.707106781;
  1599. } else {
  1600. x = Math.sqrt( xx );
  1601. y = xy / x;
  1602. z = xz / x;
  1603. }
  1604. } else if ( yy > zz ) {
  1605. // m22 is the largest diagonal term
  1606. if ( yy < epsilon ) {
  1607. x = 0.707106781;
  1608. y = 0;
  1609. z = 0.707106781;
  1610. } else {
  1611. y = Math.sqrt( yy );
  1612. x = xy / y;
  1613. z = yz / y;
  1614. }
  1615. } else {
  1616. // m33 is the largest diagonal term so base result on this
  1617. if ( zz < epsilon ) {
  1618. x = 0.707106781;
  1619. y = 0.707106781;
  1620. z = 0;
  1621. } else {
  1622. z = Math.sqrt( zz );
  1623. x = xz / z;
  1624. y = yz / z;
  1625. }
  1626. }
  1627. this.set( x, y, z, angle );
  1628. return this; // return 180 deg rotation
  1629. }
  1630. // as we have reached here there are no singularities so we can handle normally
  1631. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1632. ( m13 - m31 ) * ( m13 - m31 ) +
  1633. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1634. if ( Math.abs( s ) < 0.001 ) s = 1;
  1635. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1636. // caught by singularity test above, but I've left it in just in case
  1637. this.x = ( m32 - m23 ) / s;
  1638. this.y = ( m13 - m31 ) / s;
  1639. this.z = ( m21 - m12 ) / s;
  1640. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1641. return this;
  1642. }
  1643. min( v ) {
  1644. this.x = Math.min( this.x, v.x );
  1645. this.y = Math.min( this.y, v.y );
  1646. this.z = Math.min( this.z, v.z );
  1647. this.w = Math.min( this.w, v.w );
  1648. return this;
  1649. }
  1650. max( v ) {
  1651. this.x = Math.max( this.x, v.x );
  1652. this.y = Math.max( this.y, v.y );
  1653. this.z = Math.max( this.z, v.z );
  1654. this.w = Math.max( this.w, v.w );
  1655. return this;
  1656. }
  1657. clamp( min, max ) {
  1658. // assumes min < max, componentwise
  1659. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1660. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1661. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1662. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1663. return this;
  1664. }
  1665. clampScalar( minVal, maxVal ) {
  1666. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1667. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1668. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1669. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1670. return this;
  1671. }
  1672. clampLength( min, max ) {
  1673. const length = this.length();
  1674. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1675. }
  1676. floor() {
  1677. this.x = Math.floor( this.x );
  1678. this.y = Math.floor( this.y );
  1679. this.z = Math.floor( this.z );
  1680. this.w = Math.floor( this.w );
  1681. return this;
  1682. }
  1683. ceil() {
  1684. this.x = Math.ceil( this.x );
  1685. this.y = Math.ceil( this.y );
  1686. this.z = Math.ceil( this.z );
  1687. this.w = Math.ceil( this.w );
  1688. return this;
  1689. }
  1690. round() {
  1691. this.x = Math.round( this.x );
  1692. this.y = Math.round( this.y );
  1693. this.z = Math.round( this.z );
  1694. this.w = Math.round( this.w );
  1695. return this;
  1696. }
  1697. roundToZero() {
  1698. this.x = Math.trunc( this.x );
  1699. this.y = Math.trunc( this.y );
  1700. this.z = Math.trunc( this.z );
  1701. this.w = Math.trunc( this.w );
  1702. return this;
  1703. }
  1704. negate() {
  1705. this.x = - this.x;
  1706. this.y = - this.y;
  1707. this.z = - this.z;
  1708. this.w = - this.w;
  1709. return this;
  1710. }
  1711. dot( v ) {
  1712. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1713. }
  1714. lengthSq() {
  1715. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1716. }
  1717. length() {
  1718. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1719. }
  1720. manhattanLength() {
  1721. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1722. }
  1723. normalize() {
  1724. return this.divideScalar( this.length() || 1 );
  1725. }
  1726. setLength( length ) {
  1727. return this.normalize().multiplyScalar( length );
  1728. }
  1729. lerp( v, alpha ) {
  1730. this.x += ( v.x - this.x ) * alpha;
  1731. this.y += ( v.y - this.y ) * alpha;
  1732. this.z += ( v.z - this.z ) * alpha;
  1733. this.w += ( v.w - this.w ) * alpha;
  1734. return this;
  1735. }
  1736. lerpVectors( v1, v2, alpha ) {
  1737. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1738. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1739. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1740. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1741. return this;
  1742. }
  1743. equals( v ) {
  1744. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1745. }
  1746. fromArray( array, offset = 0 ) {
  1747. this.x = array[ offset ];
  1748. this.y = array[ offset + 1 ];
  1749. this.z = array[ offset + 2 ];
  1750. this.w = array[ offset + 3 ];
  1751. return this;
  1752. }
  1753. toArray( array = [], offset = 0 ) {
  1754. array[ offset ] = this.x;
  1755. array[ offset + 1 ] = this.y;
  1756. array[ offset + 2 ] = this.z;
  1757. array[ offset + 3 ] = this.w;
  1758. return array;
  1759. }
  1760. fromBufferAttribute( attribute, index ) {
  1761. this.x = attribute.getX( index );
  1762. this.y = attribute.getY( index );
  1763. this.z = attribute.getZ( index );
  1764. this.w = attribute.getW( index );
  1765. return this;
  1766. }
  1767. random() {
  1768. this.x = Math.random();
  1769. this.y = Math.random();
  1770. this.z = Math.random();
  1771. this.w = Math.random();
  1772. return this;
  1773. }
  1774. *[ Symbol.iterator ]() {
  1775. yield this.x;
  1776. yield this.y;
  1777. yield this.z;
  1778. yield this.w;
  1779. }
  1780. }
  1781. /*
  1782. In options, we can specify:
  1783. * Texture parameters for an auto-generated target texture
  1784. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1785. */
  1786. class RenderTarget extends EventDispatcher {
  1787. constructor( width = 1, height = 1, options = {} ) {
  1788. super();
  1789. this.isRenderTarget = true;
  1790. this.width = width;
  1791. this.height = height;
  1792. this.depth = 1;
  1793. this.scissor = new Vector4( 0, 0, width, height );
  1794. this.scissorTest = false;
  1795. this.viewport = new Vector4( 0, 0, width, height );
  1796. const image = { width: width, height: height, depth: 1 };
  1797. if ( options.encoding !== undefined ) {
  1798. // @deprecated, r152
  1799. warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  1800. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1801. }
  1802. options = Object.assign( {
  1803. generateMipmaps: false,
  1804. internalFormat: null,
  1805. minFilter: LinearFilter,
  1806. depthBuffer: true,
  1807. stencilBuffer: false,
  1808. depthTexture: null,
  1809. samples: 0
  1810. }, options );
  1811. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1812. this.texture.isRenderTargetTexture = true;
  1813. this.texture.flipY = false;
  1814. this.texture.generateMipmaps = options.generateMipmaps;
  1815. this.texture.internalFormat = options.internalFormat;
  1816. this.depthBuffer = options.depthBuffer;
  1817. this.stencilBuffer = options.stencilBuffer;
  1818. this.depthTexture = options.depthTexture;
  1819. this.samples = options.samples;
  1820. }
  1821. setSize( width, height, depth = 1 ) {
  1822. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1823. this.width = width;
  1824. this.height = height;
  1825. this.depth = depth;
  1826. this.texture.image.width = width;
  1827. this.texture.image.height = height;
  1828. this.texture.image.depth = depth;
  1829. this.dispose();
  1830. }
  1831. this.viewport.set( 0, 0, width, height );
  1832. this.scissor.set( 0, 0, width, height );
  1833. }
  1834. clone() {
  1835. return new this.constructor().copy( this );
  1836. }
  1837. copy( source ) {
  1838. this.width = source.width;
  1839. this.height = source.height;
  1840. this.depth = source.depth;
  1841. this.scissor.copy( source.scissor );
  1842. this.scissorTest = source.scissorTest;
  1843. this.viewport.copy( source.viewport );
  1844. this.texture = source.texture.clone();
  1845. this.texture.isRenderTargetTexture = true;
  1846. // ensure image object is not shared, see #20328
  1847. const image = Object.assign( {}, source.texture.image );
  1848. this.texture.source = new Source( image );
  1849. this.depthBuffer = source.depthBuffer;
  1850. this.stencilBuffer = source.stencilBuffer;
  1851. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1852. this.samples = source.samples;
  1853. return this;
  1854. }
  1855. dispose() {
  1856. this.dispatchEvent( { type: 'dispose' } );
  1857. }
  1858. }
  1859. class WebGLRenderTarget extends RenderTarget {
  1860. constructor( width = 1, height = 1, options = {} ) {
  1861. super( width, height, options );
  1862. this.isWebGLRenderTarget = true;
  1863. }
  1864. }
  1865. class DataArrayTexture extends Texture {
  1866. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1867. super( null );
  1868. this.isDataArrayTexture = true;
  1869. this.image = { data, width, height, depth };
  1870. this.magFilter = NearestFilter;
  1871. this.minFilter = NearestFilter;
  1872. this.wrapR = ClampToEdgeWrapping;
  1873. this.generateMipmaps = false;
  1874. this.flipY = false;
  1875. this.unpackAlignment = 1;
  1876. }
  1877. }
  1878. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1879. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1880. super( width, height, options );
  1881. this.isWebGLArrayRenderTarget = true;
  1882. this.depth = depth;
  1883. this.texture = new DataArrayTexture( null, width, height, depth );
  1884. this.texture.isRenderTargetTexture = true;
  1885. }
  1886. }
  1887. class Data3DTexture extends Texture {
  1888. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1889. // We're going to add .setXXX() methods for setting properties later.
  1890. // Users can still set in DataTexture3D directly.
  1891. //
  1892. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1893. // texture.anisotropy = 16;
  1894. //
  1895. // See #14839
  1896. super( null );
  1897. this.isData3DTexture = true;
  1898. this.image = { data, width, height, depth };
  1899. this.magFilter = NearestFilter;
  1900. this.minFilter = NearestFilter;
  1901. this.wrapR = ClampToEdgeWrapping;
  1902. this.generateMipmaps = false;
  1903. this.flipY = false;
  1904. this.unpackAlignment = 1;
  1905. }
  1906. }
  1907. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1908. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1909. super( width, height, options );
  1910. this.isWebGL3DRenderTarget = true;
  1911. this.depth = depth;
  1912. this.texture = new Data3DTexture( null, width, height, depth );
  1913. this.texture.isRenderTargetTexture = true;
  1914. }
  1915. }
  1916. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1917. constructor( width = 1, height = 1, count = 1, options = {} ) {
  1918. super( width, height, options );
  1919. this.isWebGLMultipleRenderTargets = true;
  1920. const texture = this.texture;
  1921. this.texture = [];
  1922. for ( let i = 0; i < count; i ++ ) {
  1923. this.texture[ i ] = texture.clone();
  1924. this.texture[ i ].isRenderTargetTexture = true;
  1925. }
  1926. }
  1927. setSize( width, height, depth = 1 ) {
  1928. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1929. this.width = width;
  1930. this.height = height;
  1931. this.depth = depth;
  1932. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1933. this.texture[ i ].image.width = width;
  1934. this.texture[ i ].image.height = height;
  1935. this.texture[ i ].image.depth = depth;
  1936. }
  1937. this.dispose();
  1938. }
  1939. this.viewport.set( 0, 0, width, height );
  1940. this.scissor.set( 0, 0, width, height );
  1941. }
  1942. copy( source ) {
  1943. this.dispose();
  1944. this.width = source.width;
  1945. this.height = source.height;
  1946. this.depth = source.depth;
  1947. this.scissor.copy( source.scissor );
  1948. this.scissorTest = source.scissorTest;
  1949. this.viewport.copy( source.viewport );
  1950. this.depthBuffer = source.depthBuffer;
  1951. this.stencilBuffer = source.stencilBuffer;
  1952. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1953. this.texture.length = 0;
  1954. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1955. this.texture[ i ] = source.texture[ i ].clone();
  1956. this.texture[ i ].isRenderTargetTexture = true;
  1957. }
  1958. return this;
  1959. }
  1960. }
  1961. class Quaternion {
  1962. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1963. this.isQuaternion = true;
  1964. this._x = x;
  1965. this._y = y;
  1966. this._z = z;
  1967. this._w = w;
  1968. }
  1969. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1970. // fuzz-free, array-based Quaternion SLERP operation
  1971. let x0 = src0[ srcOffset0 + 0 ],
  1972. y0 = src0[ srcOffset0 + 1 ],
  1973. z0 = src0[ srcOffset0 + 2 ],
  1974. w0 = src0[ srcOffset0 + 3 ];
  1975. const x1 = src1[ srcOffset1 + 0 ],
  1976. y1 = src1[ srcOffset1 + 1 ],
  1977. z1 = src1[ srcOffset1 + 2 ],
  1978. w1 = src1[ srcOffset1 + 3 ];
  1979. if ( t === 0 ) {
  1980. dst[ dstOffset + 0 ] = x0;
  1981. dst[ dstOffset + 1 ] = y0;
  1982. dst[ dstOffset + 2 ] = z0;
  1983. dst[ dstOffset + 3 ] = w0;
  1984. return;
  1985. }
  1986. if ( t === 1 ) {
  1987. dst[ dstOffset + 0 ] = x1;
  1988. dst[ dstOffset + 1 ] = y1;
  1989. dst[ dstOffset + 2 ] = z1;
  1990. dst[ dstOffset + 3 ] = w1;
  1991. return;
  1992. }
  1993. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1994. let s = 1 - t;
  1995. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1996. dir = ( cos >= 0 ? 1 : - 1 ),
  1997. sqrSin = 1 - cos * cos;
  1998. // Skip the Slerp for tiny steps to avoid numeric problems:
  1999. if ( sqrSin > Number.EPSILON ) {
  2000. const sin = Math.sqrt( sqrSin ),
  2001. len = Math.atan2( sin, cos * dir );
  2002. s = Math.sin( s * len ) / sin;
  2003. t = Math.sin( t * len ) / sin;
  2004. }
  2005. const tDir = t * dir;
  2006. x0 = x0 * s + x1 * tDir;
  2007. y0 = y0 * s + y1 * tDir;
  2008. z0 = z0 * s + z1 * tDir;
  2009. w0 = w0 * s + w1 * tDir;
  2010. // Normalize in case we just did a lerp:
  2011. if ( s === 1 - t ) {
  2012. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2013. x0 *= f;
  2014. y0 *= f;
  2015. z0 *= f;
  2016. w0 *= f;
  2017. }
  2018. }
  2019. dst[ dstOffset ] = x0;
  2020. dst[ dstOffset + 1 ] = y0;
  2021. dst[ dstOffset + 2 ] = z0;
  2022. dst[ dstOffset + 3 ] = w0;
  2023. }
  2024. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2025. const x0 = src0[ srcOffset0 ];
  2026. const y0 = src0[ srcOffset0 + 1 ];
  2027. const z0 = src0[ srcOffset0 + 2 ];
  2028. const w0 = src0[ srcOffset0 + 3 ];
  2029. const x1 = src1[ srcOffset1 ];
  2030. const y1 = src1[ srcOffset1 + 1 ];
  2031. const z1 = src1[ srcOffset1 + 2 ];
  2032. const w1 = src1[ srcOffset1 + 3 ];
  2033. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2034. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2035. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2036. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2037. return dst;
  2038. }
  2039. get x() {
  2040. return this._x;
  2041. }
  2042. set x( value ) {
  2043. this._x = value;
  2044. this._onChangeCallback();
  2045. }
  2046. get y() {
  2047. return this._y;
  2048. }
  2049. set y( value ) {
  2050. this._y = value;
  2051. this._onChangeCallback();
  2052. }
  2053. get z() {
  2054. return this._z;
  2055. }
  2056. set z( value ) {
  2057. this._z = value;
  2058. this._onChangeCallback();
  2059. }
  2060. get w() {
  2061. return this._w;
  2062. }
  2063. set w( value ) {
  2064. this._w = value;
  2065. this._onChangeCallback();
  2066. }
  2067. set( x, y, z, w ) {
  2068. this._x = x;
  2069. this._y = y;
  2070. this._z = z;
  2071. this._w = w;
  2072. this._onChangeCallback();
  2073. return this;
  2074. }
  2075. clone() {
  2076. return new this.constructor( this._x, this._y, this._z, this._w );
  2077. }
  2078. copy( quaternion ) {
  2079. this._x = quaternion.x;
  2080. this._y = quaternion.y;
  2081. this._z = quaternion.z;
  2082. this._w = quaternion.w;
  2083. this._onChangeCallback();
  2084. return this;
  2085. }
  2086. setFromEuler( euler, update = true ) {
  2087. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2088. // http://www.mathworks.com/matlabcentral/fileexchange/
  2089. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2090. // content/SpinCalc.m
  2091. const cos = Math.cos;
  2092. const sin = Math.sin;
  2093. const c1 = cos( x / 2 );
  2094. const c2 = cos( y / 2 );
  2095. const c3 = cos( z / 2 );
  2096. const s1 = sin( x / 2 );
  2097. const s2 = sin( y / 2 );
  2098. const s3 = sin( z / 2 );
  2099. switch ( order ) {
  2100. case 'XYZ':
  2101. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2102. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2103. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2104. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2105. break;
  2106. case 'YXZ':
  2107. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2108. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2109. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2110. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2111. break;
  2112. case 'ZXY':
  2113. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2114. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2115. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2116. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2117. break;
  2118. case 'ZYX':
  2119. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2120. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2121. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2122. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2123. break;
  2124. case 'YZX':
  2125. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2126. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2127. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2128. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2129. break;
  2130. case 'XZY':
  2131. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2132. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2133. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2134. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2135. break;
  2136. default:
  2137. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2138. }
  2139. if ( update === true ) this._onChangeCallback();
  2140. return this;
  2141. }
  2142. setFromAxisAngle( axis, angle ) {
  2143. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2144. // assumes axis is normalized
  2145. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2146. this._x = axis.x * s;
  2147. this._y = axis.y * s;
  2148. this._z = axis.z * s;
  2149. this._w = Math.cos( halfAngle );
  2150. this._onChangeCallback();
  2151. return this;
  2152. }
  2153. setFromRotationMatrix( m ) {
  2154. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2155. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2156. const te = m.elements,
  2157. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2158. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2159. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2160. trace = m11 + m22 + m33;
  2161. if ( trace > 0 ) {
  2162. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2163. this._w = 0.25 / s;
  2164. this._x = ( m32 - m23 ) * s;
  2165. this._y = ( m13 - m31 ) * s;
  2166. this._z = ( m21 - m12 ) * s;
  2167. } else if ( m11 > m22 && m11 > m33 ) {
  2168. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2169. this._w = ( m32 - m23 ) / s;
  2170. this._x = 0.25 * s;
  2171. this._y = ( m12 + m21 ) / s;
  2172. this._z = ( m13 + m31 ) / s;
  2173. } else if ( m22 > m33 ) {
  2174. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2175. this._w = ( m13 - m31 ) / s;
  2176. this._x = ( m12 + m21 ) / s;
  2177. this._y = 0.25 * s;
  2178. this._z = ( m23 + m32 ) / s;
  2179. } else {
  2180. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2181. this._w = ( m21 - m12 ) / s;
  2182. this._x = ( m13 + m31 ) / s;
  2183. this._y = ( m23 + m32 ) / s;
  2184. this._z = 0.25 * s;
  2185. }
  2186. this._onChangeCallback();
  2187. return this;
  2188. }
  2189. setFromUnitVectors( vFrom, vTo ) {
  2190. // assumes direction vectors vFrom and vTo are normalized
  2191. let r = vFrom.dot( vTo ) + 1;
  2192. if ( r < Number.EPSILON ) {
  2193. // vFrom and vTo point in opposite directions
  2194. r = 0;
  2195. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2196. this._x = - vFrom.y;
  2197. this._y = vFrom.x;
  2198. this._z = 0;
  2199. this._w = r;
  2200. } else {
  2201. this._x = 0;
  2202. this._y = - vFrom.z;
  2203. this._z = vFrom.y;
  2204. this._w = r;
  2205. }
  2206. } else {
  2207. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2208. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2209. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2210. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2211. this._w = r;
  2212. }
  2213. return this.normalize();
  2214. }
  2215. angleTo( q ) {
  2216. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2217. }
  2218. rotateTowards( q, step ) {
  2219. const angle = this.angleTo( q );
  2220. if ( angle === 0 ) return this;
  2221. const t = Math.min( 1, step / angle );
  2222. this.slerp( q, t );
  2223. return this;
  2224. }
  2225. identity() {
  2226. return this.set( 0, 0, 0, 1 );
  2227. }
  2228. invert() {
  2229. // quaternion is assumed to have unit length
  2230. return this.conjugate();
  2231. }
  2232. conjugate() {
  2233. this._x *= - 1;
  2234. this._y *= - 1;
  2235. this._z *= - 1;
  2236. this._onChangeCallback();
  2237. return this;
  2238. }
  2239. dot( v ) {
  2240. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2241. }
  2242. lengthSq() {
  2243. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2244. }
  2245. length() {
  2246. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2247. }
  2248. normalize() {
  2249. let l = this.length();
  2250. if ( l === 0 ) {
  2251. this._x = 0;
  2252. this._y = 0;
  2253. this._z = 0;
  2254. this._w = 1;
  2255. } else {
  2256. l = 1 / l;
  2257. this._x = this._x * l;
  2258. this._y = this._y * l;
  2259. this._z = this._z * l;
  2260. this._w = this._w * l;
  2261. }
  2262. this._onChangeCallback();
  2263. return this;
  2264. }
  2265. multiply( q ) {
  2266. return this.multiplyQuaternions( this, q );
  2267. }
  2268. premultiply( q ) {
  2269. return this.multiplyQuaternions( q, this );
  2270. }
  2271. multiplyQuaternions( a, b ) {
  2272. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2273. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2274. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2275. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2276. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2277. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2278. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2279. this._onChangeCallback();
  2280. return this;
  2281. }
  2282. slerp( qb, t ) {
  2283. if ( t === 0 ) return this;
  2284. if ( t === 1 ) return this.copy( qb );
  2285. const x = this._x, y = this._y, z = this._z, w = this._w;
  2286. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2287. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2288. if ( cosHalfTheta < 0 ) {
  2289. this._w = - qb._w;
  2290. this._x = - qb._x;
  2291. this._y = - qb._y;
  2292. this._z = - qb._z;
  2293. cosHalfTheta = - cosHalfTheta;
  2294. } else {
  2295. this.copy( qb );
  2296. }
  2297. if ( cosHalfTheta >= 1.0 ) {
  2298. this._w = w;
  2299. this._x = x;
  2300. this._y = y;
  2301. this._z = z;
  2302. return this;
  2303. }
  2304. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2305. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2306. const s = 1 - t;
  2307. this._w = s * w + t * this._w;
  2308. this._x = s * x + t * this._x;
  2309. this._y = s * y + t * this._y;
  2310. this._z = s * z + t * this._z;
  2311. this.normalize(); // normalize calls _onChangeCallback()
  2312. return this;
  2313. }
  2314. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2315. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2316. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2317. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2318. this._w = ( w * ratioA + this._w * ratioB );
  2319. this._x = ( x * ratioA + this._x * ratioB );
  2320. this._y = ( y * ratioA + this._y * ratioB );
  2321. this._z = ( z * ratioA + this._z * ratioB );
  2322. this._onChangeCallback();
  2323. return this;
  2324. }
  2325. slerpQuaternions( qa, qb, t ) {
  2326. return this.copy( qa ).slerp( qb, t );
  2327. }
  2328. random() {
  2329. // Derived from http://planning.cs.uiuc.edu/node198.html
  2330. // Note, this source uses w, x, y, z ordering,
  2331. // so we swap the order below.
  2332. const u1 = Math.random();
  2333. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2334. const sqrtu1 = Math.sqrt( u1 );
  2335. const u2 = 2 * Math.PI * Math.random();
  2336. const u3 = 2 * Math.PI * Math.random();
  2337. return this.set(
  2338. sqrt1u1 * Math.cos( u2 ),
  2339. sqrtu1 * Math.sin( u3 ),
  2340. sqrtu1 * Math.cos( u3 ),
  2341. sqrt1u1 * Math.sin( u2 ),
  2342. );
  2343. }
  2344. equals( quaternion ) {
  2345. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2346. }
  2347. fromArray( array, offset = 0 ) {
  2348. this._x = array[ offset ];
  2349. this._y = array[ offset + 1 ];
  2350. this._z = array[ offset + 2 ];
  2351. this._w = array[ offset + 3 ];
  2352. this._onChangeCallback();
  2353. return this;
  2354. }
  2355. toArray( array = [], offset = 0 ) {
  2356. array[ offset ] = this._x;
  2357. array[ offset + 1 ] = this._y;
  2358. array[ offset + 2 ] = this._z;
  2359. array[ offset + 3 ] = this._w;
  2360. return array;
  2361. }
  2362. fromBufferAttribute( attribute, index ) {
  2363. this._x = attribute.getX( index );
  2364. this._y = attribute.getY( index );
  2365. this._z = attribute.getZ( index );
  2366. this._w = attribute.getW( index );
  2367. this._onChangeCallback();
  2368. return this;
  2369. }
  2370. toJSON() {
  2371. return this.toArray();
  2372. }
  2373. _onChange( callback ) {
  2374. this._onChangeCallback = callback;
  2375. return this;
  2376. }
  2377. _onChangeCallback() {}
  2378. *[ Symbol.iterator ]() {
  2379. yield this._x;
  2380. yield this._y;
  2381. yield this._z;
  2382. yield this._w;
  2383. }
  2384. }
  2385. class Vector3 {
  2386. constructor( x = 0, y = 0, z = 0 ) {
  2387. Vector3.prototype.isVector3 = true;
  2388. this.x = x;
  2389. this.y = y;
  2390. this.z = z;
  2391. }
  2392. set( x, y, z ) {
  2393. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2394. this.x = x;
  2395. this.y = y;
  2396. this.z = z;
  2397. return this;
  2398. }
  2399. setScalar( scalar ) {
  2400. this.x = scalar;
  2401. this.y = scalar;
  2402. this.z = scalar;
  2403. return this;
  2404. }
  2405. setX( x ) {
  2406. this.x = x;
  2407. return this;
  2408. }
  2409. setY( y ) {
  2410. this.y = y;
  2411. return this;
  2412. }
  2413. setZ( z ) {
  2414. this.z = z;
  2415. return this;
  2416. }
  2417. setComponent( index, value ) {
  2418. switch ( index ) {
  2419. case 0: this.x = value; break;
  2420. case 1: this.y = value; break;
  2421. case 2: this.z = value; break;
  2422. default: throw new Error( 'index is out of range: ' + index );
  2423. }
  2424. return this;
  2425. }
  2426. getComponent( index ) {
  2427. switch ( index ) {
  2428. case 0: return this.x;
  2429. case 1: return this.y;
  2430. case 2: return this.z;
  2431. default: throw new Error( 'index is out of range: ' + index );
  2432. }
  2433. }
  2434. clone() {
  2435. return new this.constructor( this.x, this.y, this.z );
  2436. }
  2437. copy( v ) {
  2438. this.x = v.x;
  2439. this.y = v.y;
  2440. this.z = v.z;
  2441. return this;
  2442. }
  2443. add( v ) {
  2444. this.x += v.x;
  2445. this.y += v.y;
  2446. this.z += v.z;
  2447. return this;
  2448. }
  2449. addScalar( s ) {
  2450. this.x += s;
  2451. this.y += s;
  2452. this.z += s;
  2453. return this;
  2454. }
  2455. addVectors( a, b ) {
  2456. this.x = a.x + b.x;
  2457. this.y = a.y + b.y;
  2458. this.z = a.z + b.z;
  2459. return this;
  2460. }
  2461. addScaledVector( v, s ) {
  2462. this.x += v.x * s;
  2463. this.y += v.y * s;
  2464. this.z += v.z * s;
  2465. return this;
  2466. }
  2467. sub( v ) {
  2468. this.x -= v.x;
  2469. this.y -= v.y;
  2470. this.z -= v.z;
  2471. return this;
  2472. }
  2473. subScalar( s ) {
  2474. this.x -= s;
  2475. this.y -= s;
  2476. this.z -= s;
  2477. return this;
  2478. }
  2479. subVectors( a, b ) {
  2480. this.x = a.x - b.x;
  2481. this.y = a.y - b.y;
  2482. this.z = a.z - b.z;
  2483. return this;
  2484. }
  2485. multiply( v ) {
  2486. this.x *= v.x;
  2487. this.y *= v.y;
  2488. this.z *= v.z;
  2489. return this;
  2490. }
  2491. multiplyScalar( scalar ) {
  2492. this.x *= scalar;
  2493. this.y *= scalar;
  2494. this.z *= scalar;
  2495. return this;
  2496. }
  2497. multiplyVectors( a, b ) {
  2498. this.x = a.x * b.x;
  2499. this.y = a.y * b.y;
  2500. this.z = a.z * b.z;
  2501. return this;
  2502. }
  2503. applyEuler( euler ) {
  2504. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2505. }
  2506. applyAxisAngle( axis, angle ) {
  2507. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2508. }
  2509. applyMatrix3( m ) {
  2510. const x = this.x, y = this.y, z = this.z;
  2511. const e = m.elements;
  2512. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2513. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2514. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2515. return this;
  2516. }
  2517. applyNormalMatrix( m ) {
  2518. return this.applyMatrix3( m ).normalize();
  2519. }
  2520. applyMatrix4( m ) {
  2521. const x = this.x, y = this.y, z = this.z;
  2522. const e = m.elements;
  2523. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2524. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2525. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2526. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2527. return this;
  2528. }
  2529. applyQuaternion( q ) {
  2530. // quaternion q is assumed to have unit length
  2531. const vx = this.x, vy = this.y, vz = this.z;
  2532. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2533. // t = 2 * cross( q.xyz, v );
  2534. const tx = 2 * ( qy * vz - qz * vy );
  2535. const ty = 2 * ( qz * vx - qx * vz );
  2536. const tz = 2 * ( qx * vy - qy * vx );
  2537. // v + q.w * t + cross( q.xyz, t );
  2538. this.x = vx + qw * tx + qy * tz - qz * ty;
  2539. this.y = vy + qw * ty + qz * tx - qx * tz;
  2540. this.z = vz + qw * tz + qx * ty - qy * tx;
  2541. return this;
  2542. }
  2543. project( camera ) {
  2544. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2545. }
  2546. unproject( camera ) {
  2547. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2548. }
  2549. transformDirection( m ) {
  2550. // input: THREE.Matrix4 affine matrix
  2551. // vector interpreted as a direction
  2552. const x = this.x, y = this.y, z = this.z;
  2553. const e = m.elements;
  2554. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2555. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2556. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2557. return this.normalize();
  2558. }
  2559. divide( v ) {
  2560. this.x /= v.x;
  2561. this.y /= v.y;
  2562. this.z /= v.z;
  2563. return this;
  2564. }
  2565. divideScalar( scalar ) {
  2566. return this.multiplyScalar( 1 / scalar );
  2567. }
  2568. min( v ) {
  2569. this.x = Math.min( this.x, v.x );
  2570. this.y = Math.min( this.y, v.y );
  2571. this.z = Math.min( this.z, v.z );
  2572. return this;
  2573. }
  2574. max( v ) {
  2575. this.x = Math.max( this.x, v.x );
  2576. this.y = Math.max( this.y, v.y );
  2577. this.z = Math.max( this.z, v.z );
  2578. return this;
  2579. }
  2580. clamp( min, max ) {
  2581. // assumes min < max, componentwise
  2582. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2583. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2584. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2585. return this;
  2586. }
  2587. clampScalar( minVal, maxVal ) {
  2588. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2589. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2590. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2591. return this;
  2592. }
  2593. clampLength( min, max ) {
  2594. const length = this.length();
  2595. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2596. }
  2597. floor() {
  2598. this.x = Math.floor( this.x );
  2599. this.y = Math.floor( this.y );
  2600. this.z = Math.floor( this.z );
  2601. return this;
  2602. }
  2603. ceil() {
  2604. this.x = Math.ceil( this.x );
  2605. this.y = Math.ceil( this.y );
  2606. this.z = Math.ceil( this.z );
  2607. return this;
  2608. }
  2609. round() {
  2610. this.x = Math.round( this.x );
  2611. this.y = Math.round( this.y );
  2612. this.z = Math.round( this.z );
  2613. return this;
  2614. }
  2615. roundToZero() {
  2616. this.x = Math.trunc( this.x );
  2617. this.y = Math.trunc( this.y );
  2618. this.z = Math.trunc( this.z );
  2619. return this;
  2620. }
  2621. negate() {
  2622. this.x = - this.x;
  2623. this.y = - this.y;
  2624. this.z = - this.z;
  2625. return this;
  2626. }
  2627. dot( v ) {
  2628. return this.x * v.x + this.y * v.y + this.z * v.z;
  2629. }
  2630. // TODO lengthSquared?
  2631. lengthSq() {
  2632. return this.x * this.x + this.y * this.y + this.z * this.z;
  2633. }
  2634. length() {
  2635. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2636. }
  2637. manhattanLength() {
  2638. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2639. }
  2640. normalize() {
  2641. return this.divideScalar( this.length() || 1 );
  2642. }
  2643. setLength( length ) {
  2644. return this.normalize().multiplyScalar( length );
  2645. }
  2646. lerp( v, alpha ) {
  2647. this.x += ( v.x - this.x ) * alpha;
  2648. this.y += ( v.y - this.y ) * alpha;
  2649. this.z += ( v.z - this.z ) * alpha;
  2650. return this;
  2651. }
  2652. lerpVectors( v1, v2, alpha ) {
  2653. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2654. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2655. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2656. return this;
  2657. }
  2658. cross( v ) {
  2659. return this.crossVectors( this, v );
  2660. }
  2661. crossVectors( a, b ) {
  2662. const ax = a.x, ay = a.y, az = a.z;
  2663. const bx = b.x, by = b.y, bz = b.z;
  2664. this.x = ay * bz - az * by;
  2665. this.y = az * bx - ax * bz;
  2666. this.z = ax * by - ay * bx;
  2667. return this;
  2668. }
  2669. projectOnVector( v ) {
  2670. const denominator = v.lengthSq();
  2671. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2672. const scalar = v.dot( this ) / denominator;
  2673. return this.copy( v ).multiplyScalar( scalar );
  2674. }
  2675. projectOnPlane( planeNormal ) {
  2676. _vector$c.copy( this ).projectOnVector( planeNormal );
  2677. return this.sub( _vector$c );
  2678. }
  2679. reflect( normal ) {
  2680. // reflect incident vector off plane orthogonal to normal
  2681. // normal is assumed to have unit length
  2682. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2683. }
  2684. angleTo( v ) {
  2685. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2686. if ( denominator === 0 ) return Math.PI / 2;
  2687. const theta = this.dot( v ) / denominator;
  2688. // clamp, to handle numerical problems
  2689. return Math.acos( clamp( theta, - 1, 1 ) );
  2690. }
  2691. distanceTo( v ) {
  2692. return Math.sqrt( this.distanceToSquared( v ) );
  2693. }
  2694. distanceToSquared( v ) {
  2695. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2696. return dx * dx + dy * dy + dz * dz;
  2697. }
  2698. manhattanDistanceTo( v ) {
  2699. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2700. }
  2701. setFromSpherical( s ) {
  2702. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2703. }
  2704. setFromSphericalCoords( radius, phi, theta ) {
  2705. const sinPhiRadius = Math.sin( phi ) * radius;
  2706. this.x = sinPhiRadius * Math.sin( theta );
  2707. this.y = Math.cos( phi ) * radius;
  2708. this.z = sinPhiRadius * Math.cos( theta );
  2709. return this;
  2710. }
  2711. setFromCylindrical( c ) {
  2712. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2713. }
  2714. setFromCylindricalCoords( radius, theta, y ) {
  2715. this.x = radius * Math.sin( theta );
  2716. this.y = y;
  2717. this.z = radius * Math.cos( theta );
  2718. return this;
  2719. }
  2720. setFromMatrixPosition( m ) {
  2721. const e = m.elements;
  2722. this.x = e[ 12 ];
  2723. this.y = e[ 13 ];
  2724. this.z = e[ 14 ];
  2725. return this;
  2726. }
  2727. setFromMatrixScale( m ) {
  2728. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2729. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2730. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2731. this.x = sx;
  2732. this.y = sy;
  2733. this.z = sz;
  2734. return this;
  2735. }
  2736. setFromMatrixColumn( m, index ) {
  2737. return this.fromArray( m.elements, index * 4 );
  2738. }
  2739. setFromMatrix3Column( m, index ) {
  2740. return this.fromArray( m.elements, index * 3 );
  2741. }
  2742. setFromEuler( e ) {
  2743. this.x = e._x;
  2744. this.y = e._y;
  2745. this.z = e._z;
  2746. return this;
  2747. }
  2748. setFromColor( c ) {
  2749. this.x = c.r;
  2750. this.y = c.g;
  2751. this.z = c.b;
  2752. return this;
  2753. }
  2754. equals( v ) {
  2755. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2756. }
  2757. fromArray( array, offset = 0 ) {
  2758. this.x = array[ offset ];
  2759. this.y = array[ offset + 1 ];
  2760. this.z = array[ offset + 2 ];
  2761. return this;
  2762. }
  2763. toArray( array = [], offset = 0 ) {
  2764. array[ offset ] = this.x;
  2765. array[ offset + 1 ] = this.y;
  2766. array[ offset + 2 ] = this.z;
  2767. return array;
  2768. }
  2769. fromBufferAttribute( attribute, index ) {
  2770. this.x = attribute.getX( index );
  2771. this.y = attribute.getY( index );
  2772. this.z = attribute.getZ( index );
  2773. return this;
  2774. }
  2775. random() {
  2776. this.x = Math.random();
  2777. this.y = Math.random();
  2778. this.z = Math.random();
  2779. return this;
  2780. }
  2781. randomDirection() {
  2782. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2783. const u = ( Math.random() - 0.5 ) * 2;
  2784. const t = Math.random() * Math.PI * 2;
  2785. const f = Math.sqrt( 1 - u ** 2 );
  2786. this.x = f * Math.cos( t );
  2787. this.y = f * Math.sin( t );
  2788. this.z = u;
  2789. return this;
  2790. }
  2791. *[ Symbol.iterator ]() {
  2792. yield this.x;
  2793. yield this.y;
  2794. yield this.z;
  2795. }
  2796. }
  2797. const _vector$c = /*@__PURE__*/ new Vector3();
  2798. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2799. class Box3 {
  2800. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2801. this.isBox3 = true;
  2802. this.min = min;
  2803. this.max = max;
  2804. }
  2805. set( min, max ) {
  2806. this.min.copy( min );
  2807. this.max.copy( max );
  2808. return this;
  2809. }
  2810. setFromArray( array ) {
  2811. this.makeEmpty();
  2812. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2813. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2814. }
  2815. return this;
  2816. }
  2817. setFromBufferAttribute( attribute ) {
  2818. this.makeEmpty();
  2819. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2820. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2821. }
  2822. return this;
  2823. }
  2824. setFromPoints( points ) {
  2825. this.makeEmpty();
  2826. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2827. this.expandByPoint( points[ i ] );
  2828. }
  2829. return this;
  2830. }
  2831. setFromCenterAndSize( center, size ) {
  2832. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2833. this.min.copy( center ).sub( halfSize );
  2834. this.max.copy( center ).add( halfSize );
  2835. return this;
  2836. }
  2837. setFromObject( object, precise = false ) {
  2838. this.makeEmpty();
  2839. return this.expandByObject( object, precise );
  2840. }
  2841. clone() {
  2842. return new this.constructor().copy( this );
  2843. }
  2844. copy( box ) {
  2845. this.min.copy( box.min );
  2846. this.max.copy( box.max );
  2847. return this;
  2848. }
  2849. makeEmpty() {
  2850. this.min.x = this.min.y = this.min.z = + Infinity;
  2851. this.max.x = this.max.y = this.max.z = - Infinity;
  2852. return this;
  2853. }
  2854. isEmpty() {
  2855. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2856. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2857. }
  2858. getCenter( target ) {
  2859. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2860. }
  2861. getSize( target ) {
  2862. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2863. }
  2864. expandByPoint( point ) {
  2865. this.min.min( point );
  2866. this.max.max( point );
  2867. return this;
  2868. }
  2869. expandByVector( vector ) {
  2870. this.min.sub( vector );
  2871. this.max.add( vector );
  2872. return this;
  2873. }
  2874. expandByScalar( scalar ) {
  2875. this.min.addScalar( - scalar );
  2876. this.max.addScalar( scalar );
  2877. return this;
  2878. }
  2879. expandByObject( object, precise = false ) {
  2880. // Computes the world-axis-aligned bounding box of an object (including its children),
  2881. // accounting for both the object's, and children's, world transforms
  2882. object.updateWorldMatrix( false, false );
  2883. const geometry = object.geometry;
  2884. if ( geometry !== undefined ) {
  2885. const positionAttribute = geometry.getAttribute( 'position' );
  2886. // precise AABB computation based on vertex data requires at least a position attribute.
  2887. // instancing isn't supported so far and uses the normal (conservative) code path.
  2888. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2889. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2890. if ( object.isMesh === true ) {
  2891. object.getVertexPosition( i, _vector$b );
  2892. } else {
  2893. _vector$b.fromBufferAttribute( positionAttribute, i );
  2894. }
  2895. _vector$b.applyMatrix4( object.matrixWorld );
  2896. this.expandByPoint( _vector$b );
  2897. }
  2898. } else {
  2899. if ( object.boundingBox !== undefined ) {
  2900. // object-level bounding box
  2901. if ( object.boundingBox === null ) {
  2902. object.computeBoundingBox();
  2903. }
  2904. _box$4.copy( object.boundingBox );
  2905. } else {
  2906. // geometry-level bounding box
  2907. if ( geometry.boundingBox === null ) {
  2908. geometry.computeBoundingBox();
  2909. }
  2910. _box$4.copy( geometry.boundingBox );
  2911. }
  2912. _box$4.applyMatrix4( object.matrixWorld );
  2913. this.union( _box$4 );
  2914. }
  2915. }
  2916. const children = object.children;
  2917. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2918. this.expandByObject( children[ i ], precise );
  2919. }
  2920. return this;
  2921. }
  2922. containsPoint( point ) {
  2923. return point.x < this.min.x || point.x > this.max.x ||
  2924. point.y < this.min.y || point.y > this.max.y ||
  2925. point.z < this.min.z || point.z > this.max.z ? false : true;
  2926. }
  2927. containsBox( box ) {
  2928. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2929. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2930. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2931. }
  2932. getParameter( point, target ) {
  2933. // This can potentially have a divide by zero if the box
  2934. // has a size dimension of 0.
  2935. return target.set(
  2936. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2937. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2938. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2939. );
  2940. }
  2941. intersectsBox( box ) {
  2942. // using 6 splitting planes to rule out intersections.
  2943. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2944. box.max.y < this.min.y || box.min.y > this.max.y ||
  2945. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2946. }
  2947. intersectsSphere( sphere ) {
  2948. // Find the point on the AABB closest to the sphere center.
  2949. this.clampPoint( sphere.center, _vector$b );
  2950. // If that point is inside the sphere, the AABB and sphere intersect.
  2951. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2952. }
  2953. intersectsPlane( plane ) {
  2954. // We compute the minimum and maximum dot product values. If those values
  2955. // are on the same side (back or front) of the plane, then there is no intersection.
  2956. let min, max;
  2957. if ( plane.normal.x > 0 ) {
  2958. min = plane.normal.x * this.min.x;
  2959. max = plane.normal.x * this.max.x;
  2960. } else {
  2961. min = plane.normal.x * this.max.x;
  2962. max = plane.normal.x * this.min.x;
  2963. }
  2964. if ( plane.normal.y > 0 ) {
  2965. min += plane.normal.y * this.min.y;
  2966. max += plane.normal.y * this.max.y;
  2967. } else {
  2968. min += plane.normal.y * this.max.y;
  2969. max += plane.normal.y * this.min.y;
  2970. }
  2971. if ( plane.normal.z > 0 ) {
  2972. min += plane.normal.z * this.min.z;
  2973. max += plane.normal.z * this.max.z;
  2974. } else {
  2975. min += plane.normal.z * this.max.z;
  2976. max += plane.normal.z * this.min.z;
  2977. }
  2978. return ( min <= - plane.constant && max >= - plane.constant );
  2979. }
  2980. intersectsTriangle( triangle ) {
  2981. if ( this.isEmpty() ) {
  2982. return false;
  2983. }
  2984. // compute box center and extents
  2985. this.getCenter( _center );
  2986. _extents.subVectors( this.max, _center );
  2987. // translate triangle to aabb origin
  2988. _v0$2.subVectors( triangle.a, _center );
  2989. _v1$7.subVectors( triangle.b, _center );
  2990. _v2$4.subVectors( triangle.c, _center );
  2991. // compute edge vectors for triangle
  2992. _f0.subVectors( _v1$7, _v0$2 );
  2993. _f1.subVectors( _v2$4, _v1$7 );
  2994. _f2.subVectors( _v0$2, _v2$4 );
  2995. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2996. // 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
  2997. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2998. let axes = [
  2999. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3000. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3001. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3002. ];
  3003. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3004. return false;
  3005. }
  3006. // test 3 face normals from the aabb
  3007. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3008. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3009. return false;
  3010. }
  3011. // finally testing the face normal of the triangle
  3012. // use already existing triangle edge vectors here
  3013. _triangleNormal.crossVectors( _f0, _f1 );
  3014. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3015. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3016. }
  3017. clampPoint( point, target ) {
  3018. return target.copy( point ).clamp( this.min, this.max );
  3019. }
  3020. distanceToPoint( point ) {
  3021. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3022. }
  3023. getBoundingSphere( target ) {
  3024. if ( this.isEmpty() ) {
  3025. target.makeEmpty();
  3026. } else {
  3027. this.getCenter( target.center );
  3028. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3029. }
  3030. return target;
  3031. }
  3032. intersect( box ) {
  3033. this.min.max( box.min );
  3034. this.max.min( box.max );
  3035. // 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.
  3036. if ( this.isEmpty() ) this.makeEmpty();
  3037. return this;
  3038. }
  3039. union( box ) {
  3040. this.min.min( box.min );
  3041. this.max.max( box.max );
  3042. return this;
  3043. }
  3044. applyMatrix4( matrix ) {
  3045. // transform of empty box is an empty box.
  3046. if ( this.isEmpty() ) return this;
  3047. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3048. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3049. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3050. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3051. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3052. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3053. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3054. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3055. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3056. this.setFromPoints( _points );
  3057. return this;
  3058. }
  3059. translate( offset ) {
  3060. this.min.add( offset );
  3061. this.max.add( offset );
  3062. return this;
  3063. }
  3064. equals( box ) {
  3065. return box.min.equals( this.min ) && box.max.equals( this.max );
  3066. }
  3067. }
  3068. const _points = [
  3069. /*@__PURE__*/ new Vector3(),
  3070. /*@__PURE__*/ new Vector3(),
  3071. /*@__PURE__*/ new Vector3(),
  3072. /*@__PURE__*/ new Vector3(),
  3073. /*@__PURE__*/ new Vector3(),
  3074. /*@__PURE__*/ new Vector3(),
  3075. /*@__PURE__*/ new Vector3(),
  3076. /*@__PURE__*/ new Vector3()
  3077. ];
  3078. const _vector$b = /*@__PURE__*/ new Vector3();
  3079. const _box$4 = /*@__PURE__*/ new Box3();
  3080. // triangle centered vertices
  3081. const _v0$2 = /*@__PURE__*/ new Vector3();
  3082. const _v1$7 = /*@__PURE__*/ new Vector3();
  3083. const _v2$4 = /*@__PURE__*/ new Vector3();
  3084. // triangle edge vectors
  3085. const _f0 = /*@__PURE__*/ new Vector3();
  3086. const _f1 = /*@__PURE__*/ new Vector3();
  3087. const _f2 = /*@__PURE__*/ new Vector3();
  3088. const _center = /*@__PURE__*/ new Vector3();
  3089. const _extents = /*@__PURE__*/ new Vector3();
  3090. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3091. const _testAxis = /*@__PURE__*/ new Vector3();
  3092. function satForAxes( axes, v0, v1, v2, extents ) {
  3093. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3094. _testAxis.fromArray( axes, i );
  3095. // project the aabb onto the separating axis
  3096. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3097. // project all 3 vertices of the triangle onto the separating axis
  3098. const p0 = v0.dot( _testAxis );
  3099. const p1 = v1.dot( _testAxis );
  3100. const p2 = v2.dot( _testAxis );
  3101. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3102. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3103. // points of the projected triangle are outside the projected half-length of the aabb
  3104. // the axis is separating and we can exit
  3105. return false;
  3106. }
  3107. }
  3108. return true;
  3109. }
  3110. const _box$3 = /*@__PURE__*/ new Box3();
  3111. const _v1$6 = /*@__PURE__*/ new Vector3();
  3112. const _v2$3 = /*@__PURE__*/ new Vector3();
  3113. class Sphere {
  3114. constructor( center = new Vector3(), radius = - 1 ) {
  3115. this.isSphere = true;
  3116. this.center = center;
  3117. this.radius = radius;
  3118. }
  3119. set( center, radius ) {
  3120. this.center.copy( center );
  3121. this.radius = radius;
  3122. return this;
  3123. }
  3124. setFromPoints( points, optionalCenter ) {
  3125. const center = this.center;
  3126. if ( optionalCenter !== undefined ) {
  3127. center.copy( optionalCenter );
  3128. } else {
  3129. _box$3.setFromPoints( points ).getCenter( center );
  3130. }
  3131. let maxRadiusSq = 0;
  3132. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3133. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3134. }
  3135. this.radius = Math.sqrt( maxRadiusSq );
  3136. return this;
  3137. }
  3138. copy( sphere ) {
  3139. this.center.copy( sphere.center );
  3140. this.radius = sphere.radius;
  3141. return this;
  3142. }
  3143. isEmpty() {
  3144. return ( this.radius < 0 );
  3145. }
  3146. makeEmpty() {
  3147. this.center.set( 0, 0, 0 );
  3148. this.radius = - 1;
  3149. return this;
  3150. }
  3151. containsPoint( point ) {
  3152. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3153. }
  3154. distanceToPoint( point ) {
  3155. return ( point.distanceTo( this.center ) - this.radius );
  3156. }
  3157. intersectsSphere( sphere ) {
  3158. const radiusSum = this.radius + sphere.radius;
  3159. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3160. }
  3161. intersectsBox( box ) {
  3162. return box.intersectsSphere( this );
  3163. }
  3164. intersectsPlane( plane ) {
  3165. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3166. }
  3167. clampPoint( point, target ) {
  3168. const deltaLengthSq = this.center.distanceToSquared( point );
  3169. target.copy( point );
  3170. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3171. target.sub( this.center ).normalize();
  3172. target.multiplyScalar( this.radius ).add( this.center );
  3173. }
  3174. return target;
  3175. }
  3176. getBoundingBox( target ) {
  3177. if ( this.isEmpty() ) {
  3178. // Empty sphere produces empty bounding box
  3179. target.makeEmpty();
  3180. return target;
  3181. }
  3182. target.set( this.center, this.center );
  3183. target.expandByScalar( this.radius );
  3184. return target;
  3185. }
  3186. applyMatrix4( matrix ) {
  3187. this.center.applyMatrix4( matrix );
  3188. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3189. return this;
  3190. }
  3191. translate( offset ) {
  3192. this.center.add( offset );
  3193. return this;
  3194. }
  3195. expandByPoint( point ) {
  3196. if ( this.isEmpty() ) {
  3197. this.center.copy( point );
  3198. this.radius = 0;
  3199. return this;
  3200. }
  3201. _v1$6.subVectors( point, this.center );
  3202. const lengthSq = _v1$6.lengthSq();
  3203. if ( lengthSq > ( this.radius * this.radius ) ) {
  3204. // calculate the minimal sphere
  3205. const length = Math.sqrt( lengthSq );
  3206. const delta = ( length - this.radius ) * 0.5;
  3207. this.center.addScaledVector( _v1$6, delta / length );
  3208. this.radius += delta;
  3209. }
  3210. return this;
  3211. }
  3212. union( sphere ) {
  3213. if ( sphere.isEmpty() ) {
  3214. return this;
  3215. }
  3216. if ( this.isEmpty() ) {
  3217. this.copy( sphere );
  3218. return this;
  3219. }
  3220. if ( this.center.equals( sphere.center ) === true ) {
  3221. this.radius = Math.max( this.radius, sphere.radius );
  3222. } else {
  3223. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3224. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3225. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3226. }
  3227. return this;
  3228. }
  3229. equals( sphere ) {
  3230. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3231. }
  3232. clone() {
  3233. return new this.constructor().copy( this );
  3234. }
  3235. }
  3236. const _vector$a = /*@__PURE__*/ new Vector3();
  3237. const _segCenter = /*@__PURE__*/ new Vector3();
  3238. const _segDir = /*@__PURE__*/ new Vector3();
  3239. const _diff = /*@__PURE__*/ new Vector3();
  3240. const _edge1 = /*@__PURE__*/ new Vector3();
  3241. const _edge2 = /*@__PURE__*/ new Vector3();
  3242. const _normal$1 = /*@__PURE__*/ new Vector3();
  3243. class Ray {
  3244. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3245. this.origin = origin;
  3246. this.direction = direction;
  3247. }
  3248. set( origin, direction ) {
  3249. this.origin.copy( origin );
  3250. this.direction.copy( direction );
  3251. return this;
  3252. }
  3253. copy( ray ) {
  3254. this.origin.copy( ray.origin );
  3255. this.direction.copy( ray.direction );
  3256. return this;
  3257. }
  3258. at( t, target ) {
  3259. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3260. }
  3261. lookAt( v ) {
  3262. this.direction.copy( v ).sub( this.origin ).normalize();
  3263. return this;
  3264. }
  3265. recast( t ) {
  3266. this.origin.copy( this.at( t, _vector$a ) );
  3267. return this;
  3268. }
  3269. closestPointToPoint( point, target ) {
  3270. target.subVectors( point, this.origin );
  3271. const directionDistance = target.dot( this.direction );
  3272. if ( directionDistance < 0 ) {
  3273. return target.copy( this.origin );
  3274. }
  3275. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3276. }
  3277. distanceToPoint( point ) {
  3278. return Math.sqrt( this.distanceSqToPoint( point ) );
  3279. }
  3280. distanceSqToPoint( point ) {
  3281. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3282. // point behind the ray
  3283. if ( directionDistance < 0 ) {
  3284. return this.origin.distanceToSquared( point );
  3285. }
  3286. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3287. return _vector$a.distanceToSquared( point );
  3288. }
  3289. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3290. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3291. // It returns the min distance between the ray and the segment
  3292. // defined by v0 and v1
  3293. // It can also set two optional targets :
  3294. // - The closest point on the ray
  3295. // - The closest point on the segment
  3296. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3297. _segDir.copy( v1 ).sub( v0 ).normalize();
  3298. _diff.copy( this.origin ).sub( _segCenter );
  3299. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3300. const a01 = - this.direction.dot( _segDir );
  3301. const b0 = _diff.dot( this.direction );
  3302. const b1 = - _diff.dot( _segDir );
  3303. const c = _diff.lengthSq();
  3304. const det = Math.abs( 1 - a01 * a01 );
  3305. let s0, s1, sqrDist, extDet;
  3306. if ( det > 0 ) {
  3307. // The ray and segment are not parallel.
  3308. s0 = a01 * b1 - b0;
  3309. s1 = a01 * b0 - b1;
  3310. extDet = segExtent * det;
  3311. if ( s0 >= 0 ) {
  3312. if ( s1 >= - extDet ) {
  3313. if ( s1 <= extDet ) {
  3314. // region 0
  3315. // Minimum at interior points of ray and segment.
  3316. const invDet = 1 / det;
  3317. s0 *= invDet;
  3318. s1 *= invDet;
  3319. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3320. } else {
  3321. // region 1
  3322. s1 = segExtent;
  3323. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3324. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3325. }
  3326. } else {
  3327. // region 5
  3328. s1 = - segExtent;
  3329. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3330. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3331. }
  3332. } else {
  3333. if ( s1 <= - extDet ) {
  3334. // region 4
  3335. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3336. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3337. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3338. } else if ( s1 <= extDet ) {
  3339. // region 3
  3340. s0 = 0;
  3341. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3342. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3343. } else {
  3344. // region 2
  3345. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3346. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3347. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3348. }
  3349. }
  3350. } else {
  3351. // Ray and segment are parallel.
  3352. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3353. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3354. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3355. }
  3356. if ( optionalPointOnRay ) {
  3357. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3358. }
  3359. if ( optionalPointOnSegment ) {
  3360. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3361. }
  3362. return sqrDist;
  3363. }
  3364. intersectSphere( sphere, target ) {
  3365. _vector$a.subVectors( sphere.center, this.origin );
  3366. const tca = _vector$a.dot( this.direction );
  3367. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3368. const radius2 = sphere.radius * sphere.radius;
  3369. if ( d2 > radius2 ) return null;
  3370. const thc = Math.sqrt( radius2 - d2 );
  3371. // t0 = first intersect point - entrance on front of sphere
  3372. const t0 = tca - thc;
  3373. // t1 = second intersect point - exit point on back of sphere
  3374. const t1 = tca + thc;
  3375. // test to see if t1 is behind the ray - if so, return null
  3376. if ( t1 < 0 ) return null;
  3377. // test to see if t0 is behind the ray:
  3378. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3379. // in order to always return an intersect point that is in front of the ray.
  3380. if ( t0 < 0 ) return this.at( t1, target );
  3381. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3382. return this.at( t0, target );
  3383. }
  3384. intersectsSphere( sphere ) {
  3385. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3386. }
  3387. distanceToPlane( plane ) {
  3388. const denominator = plane.normal.dot( this.direction );
  3389. if ( denominator === 0 ) {
  3390. // line is coplanar, return origin
  3391. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3392. return 0;
  3393. }
  3394. // Null is preferable to undefined since undefined means.... it is undefined
  3395. return null;
  3396. }
  3397. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3398. // Return if the ray never intersects the plane
  3399. return t >= 0 ? t : null;
  3400. }
  3401. intersectPlane( plane, target ) {
  3402. const t = this.distanceToPlane( plane );
  3403. if ( t === null ) {
  3404. return null;
  3405. }
  3406. return this.at( t, target );
  3407. }
  3408. intersectsPlane( plane ) {
  3409. // check if the ray lies on the plane first
  3410. const distToPoint = plane.distanceToPoint( this.origin );
  3411. if ( distToPoint === 0 ) {
  3412. return true;
  3413. }
  3414. const denominator = plane.normal.dot( this.direction );
  3415. if ( denominator * distToPoint < 0 ) {
  3416. return true;
  3417. }
  3418. // ray origin is behind the plane (and is pointing behind it)
  3419. return false;
  3420. }
  3421. intersectBox( box, target ) {
  3422. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3423. const invdirx = 1 / this.direction.x,
  3424. invdiry = 1 / this.direction.y,
  3425. invdirz = 1 / this.direction.z;
  3426. const origin = this.origin;
  3427. if ( invdirx >= 0 ) {
  3428. tmin = ( box.min.x - origin.x ) * invdirx;
  3429. tmax = ( box.max.x - origin.x ) * invdirx;
  3430. } else {
  3431. tmin = ( box.max.x - origin.x ) * invdirx;
  3432. tmax = ( box.min.x - origin.x ) * invdirx;
  3433. }
  3434. if ( invdiry >= 0 ) {
  3435. tymin = ( box.min.y - origin.y ) * invdiry;
  3436. tymax = ( box.max.y - origin.y ) * invdiry;
  3437. } else {
  3438. tymin = ( box.max.y - origin.y ) * invdiry;
  3439. tymax = ( box.min.y - origin.y ) * invdiry;
  3440. }
  3441. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3442. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3443. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3444. if ( invdirz >= 0 ) {
  3445. tzmin = ( box.min.z - origin.z ) * invdirz;
  3446. tzmax = ( box.max.z - origin.z ) * invdirz;
  3447. } else {
  3448. tzmin = ( box.max.z - origin.z ) * invdirz;
  3449. tzmax = ( box.min.z - origin.z ) * invdirz;
  3450. }
  3451. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3452. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3453. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3454. //return point closest to the ray (positive side)
  3455. if ( tmax < 0 ) return null;
  3456. return this.at( tmin >= 0 ? tmin : tmax, target );
  3457. }
  3458. intersectsBox( box ) {
  3459. return this.intersectBox( box, _vector$a ) !== null;
  3460. }
  3461. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3462. // Compute the offset origin, edges, and normal.
  3463. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3464. _edge1.subVectors( b, a );
  3465. _edge2.subVectors( c, a );
  3466. _normal$1.crossVectors( _edge1, _edge2 );
  3467. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3468. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3469. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3470. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3471. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3472. let DdN = this.direction.dot( _normal$1 );
  3473. let sign;
  3474. if ( DdN > 0 ) {
  3475. if ( backfaceCulling ) return null;
  3476. sign = 1;
  3477. } else if ( DdN < 0 ) {
  3478. sign = - 1;
  3479. DdN = - DdN;
  3480. } else {
  3481. return null;
  3482. }
  3483. _diff.subVectors( this.origin, a );
  3484. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3485. // b1 < 0, no intersection
  3486. if ( DdQxE2 < 0 ) {
  3487. return null;
  3488. }
  3489. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3490. // b2 < 0, no intersection
  3491. if ( DdE1xQ < 0 ) {
  3492. return null;
  3493. }
  3494. // b1+b2 > 1, no intersection
  3495. if ( DdQxE2 + DdE1xQ > DdN ) {
  3496. return null;
  3497. }
  3498. // Line intersects triangle, check if ray does.
  3499. const QdN = - sign * _diff.dot( _normal$1 );
  3500. // t < 0, no intersection
  3501. if ( QdN < 0 ) {
  3502. return null;
  3503. }
  3504. // Ray intersects triangle.
  3505. return this.at( QdN / DdN, target );
  3506. }
  3507. applyMatrix4( matrix4 ) {
  3508. this.origin.applyMatrix4( matrix4 );
  3509. this.direction.transformDirection( matrix4 );
  3510. return this;
  3511. }
  3512. equals( ray ) {
  3513. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3514. }
  3515. clone() {
  3516. return new this.constructor().copy( this );
  3517. }
  3518. }
  3519. class Matrix4 {
  3520. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3521. Matrix4.prototype.isMatrix4 = true;
  3522. this.elements = [
  3523. 1, 0, 0, 0,
  3524. 0, 1, 0, 0,
  3525. 0, 0, 1, 0,
  3526. 0, 0, 0, 1
  3527. ];
  3528. if ( n11 !== undefined ) {
  3529. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3530. }
  3531. }
  3532. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3533. const te = this.elements;
  3534. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3535. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3536. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3537. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3538. return this;
  3539. }
  3540. identity() {
  3541. this.set(
  3542. 1, 0, 0, 0,
  3543. 0, 1, 0, 0,
  3544. 0, 0, 1, 0,
  3545. 0, 0, 0, 1
  3546. );
  3547. return this;
  3548. }
  3549. clone() {
  3550. return new Matrix4().fromArray( this.elements );
  3551. }
  3552. copy( m ) {
  3553. const te = this.elements;
  3554. const me = m.elements;
  3555. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3556. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3557. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3558. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3559. return this;
  3560. }
  3561. copyPosition( m ) {
  3562. const te = this.elements, me = m.elements;
  3563. te[ 12 ] = me[ 12 ];
  3564. te[ 13 ] = me[ 13 ];
  3565. te[ 14 ] = me[ 14 ];
  3566. return this;
  3567. }
  3568. setFromMatrix3( m ) {
  3569. const me = m.elements;
  3570. this.set(
  3571. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3572. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3573. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3574. 0, 0, 0, 1
  3575. );
  3576. return this;
  3577. }
  3578. extractBasis( xAxis, yAxis, zAxis ) {
  3579. xAxis.setFromMatrixColumn( this, 0 );
  3580. yAxis.setFromMatrixColumn( this, 1 );
  3581. zAxis.setFromMatrixColumn( this, 2 );
  3582. return this;
  3583. }
  3584. makeBasis( xAxis, yAxis, zAxis ) {
  3585. this.set(
  3586. xAxis.x, yAxis.x, zAxis.x, 0,
  3587. xAxis.y, yAxis.y, zAxis.y, 0,
  3588. xAxis.z, yAxis.z, zAxis.z, 0,
  3589. 0, 0, 0, 1
  3590. );
  3591. return this;
  3592. }
  3593. extractRotation( m ) {
  3594. // this method does not support reflection matrices
  3595. const te = this.elements;
  3596. const me = m.elements;
  3597. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3598. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3599. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3600. te[ 0 ] = me[ 0 ] * scaleX;
  3601. te[ 1 ] = me[ 1 ] * scaleX;
  3602. te[ 2 ] = me[ 2 ] * scaleX;
  3603. te[ 3 ] = 0;
  3604. te[ 4 ] = me[ 4 ] * scaleY;
  3605. te[ 5 ] = me[ 5 ] * scaleY;
  3606. te[ 6 ] = me[ 6 ] * scaleY;
  3607. te[ 7 ] = 0;
  3608. te[ 8 ] = me[ 8 ] * scaleZ;
  3609. te[ 9 ] = me[ 9 ] * scaleZ;
  3610. te[ 10 ] = me[ 10 ] * scaleZ;
  3611. te[ 11 ] = 0;
  3612. te[ 12 ] = 0;
  3613. te[ 13 ] = 0;
  3614. te[ 14 ] = 0;
  3615. te[ 15 ] = 1;
  3616. return this;
  3617. }
  3618. makeRotationFromEuler( euler ) {
  3619. const te = this.elements;
  3620. const x = euler.x, y = euler.y, z = euler.z;
  3621. const a = Math.cos( x ), b = Math.sin( x );
  3622. const c = Math.cos( y ), d = Math.sin( y );
  3623. const e = Math.cos( z ), f = Math.sin( z );
  3624. if ( euler.order === 'XYZ' ) {
  3625. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3626. te[ 0 ] = c * e;
  3627. te[ 4 ] = - c * f;
  3628. te[ 8 ] = d;
  3629. te[ 1 ] = af + be * d;
  3630. te[ 5 ] = ae - bf * d;
  3631. te[ 9 ] = - b * c;
  3632. te[ 2 ] = bf - ae * d;
  3633. te[ 6 ] = be + af * d;
  3634. te[ 10 ] = a * c;
  3635. } else if ( euler.order === 'YXZ' ) {
  3636. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3637. te[ 0 ] = ce + df * b;
  3638. te[ 4 ] = de * b - cf;
  3639. te[ 8 ] = a * d;
  3640. te[ 1 ] = a * f;
  3641. te[ 5 ] = a * e;
  3642. te[ 9 ] = - b;
  3643. te[ 2 ] = cf * b - de;
  3644. te[ 6 ] = df + ce * b;
  3645. te[ 10 ] = a * c;
  3646. } else if ( euler.order === 'ZXY' ) {
  3647. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3648. te[ 0 ] = ce - df * b;
  3649. te[ 4 ] = - a * f;
  3650. te[ 8 ] = de + cf * b;
  3651. te[ 1 ] = cf + de * b;
  3652. te[ 5 ] = a * e;
  3653. te[ 9 ] = df - ce * b;
  3654. te[ 2 ] = - a * d;
  3655. te[ 6 ] = b;
  3656. te[ 10 ] = a * c;
  3657. } else if ( euler.order === 'ZYX' ) {
  3658. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3659. te[ 0 ] = c * e;
  3660. te[ 4 ] = be * d - af;
  3661. te[ 8 ] = ae * d + bf;
  3662. te[ 1 ] = c * f;
  3663. te[ 5 ] = bf * d + ae;
  3664. te[ 9 ] = af * d - be;
  3665. te[ 2 ] = - d;
  3666. te[ 6 ] = b * c;
  3667. te[ 10 ] = a * c;
  3668. } else if ( euler.order === 'YZX' ) {
  3669. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3670. te[ 0 ] = c * e;
  3671. te[ 4 ] = bd - ac * f;
  3672. te[ 8 ] = bc * f + ad;
  3673. te[ 1 ] = f;
  3674. te[ 5 ] = a * e;
  3675. te[ 9 ] = - b * e;
  3676. te[ 2 ] = - d * e;
  3677. te[ 6 ] = ad * f + bc;
  3678. te[ 10 ] = ac - bd * f;
  3679. } else if ( euler.order === 'XZY' ) {
  3680. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3681. te[ 0 ] = c * e;
  3682. te[ 4 ] = - f;
  3683. te[ 8 ] = d * e;
  3684. te[ 1 ] = ac * f + bd;
  3685. te[ 5 ] = a * e;
  3686. te[ 9 ] = ad * f - bc;
  3687. te[ 2 ] = bc * f - ad;
  3688. te[ 6 ] = b * e;
  3689. te[ 10 ] = bd * f + ac;
  3690. }
  3691. // bottom row
  3692. te[ 3 ] = 0;
  3693. te[ 7 ] = 0;
  3694. te[ 11 ] = 0;
  3695. // last column
  3696. te[ 12 ] = 0;
  3697. te[ 13 ] = 0;
  3698. te[ 14 ] = 0;
  3699. te[ 15 ] = 1;
  3700. return this;
  3701. }
  3702. makeRotationFromQuaternion( q ) {
  3703. return this.compose( _zero, q, _one );
  3704. }
  3705. lookAt( eye, target, up ) {
  3706. const te = this.elements;
  3707. _z.subVectors( eye, target );
  3708. if ( _z.lengthSq() === 0 ) {
  3709. // eye and target are in the same position
  3710. _z.z = 1;
  3711. }
  3712. _z.normalize();
  3713. _x.crossVectors( up, _z );
  3714. if ( _x.lengthSq() === 0 ) {
  3715. // up and z are parallel
  3716. if ( Math.abs( up.z ) === 1 ) {
  3717. _z.x += 0.0001;
  3718. } else {
  3719. _z.z += 0.0001;
  3720. }
  3721. _z.normalize();
  3722. _x.crossVectors( up, _z );
  3723. }
  3724. _x.normalize();
  3725. _y.crossVectors( _z, _x );
  3726. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3727. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3728. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3729. return this;
  3730. }
  3731. multiply( m ) {
  3732. return this.multiplyMatrices( this, m );
  3733. }
  3734. premultiply( m ) {
  3735. return this.multiplyMatrices( m, this );
  3736. }
  3737. multiplyMatrices( a, b ) {
  3738. const ae = a.elements;
  3739. const be = b.elements;
  3740. const te = this.elements;
  3741. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3742. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3743. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3744. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3745. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3746. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3747. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3748. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3749. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3750. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3751. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3752. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3753. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3754. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3755. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3756. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3757. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3758. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3759. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3760. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3761. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3762. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3763. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3764. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3765. return this;
  3766. }
  3767. multiplyScalar( s ) {
  3768. const te = this.elements;
  3769. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3770. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3771. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3772. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3773. return this;
  3774. }
  3775. determinant() {
  3776. const te = this.elements;
  3777. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3778. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3779. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3780. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3781. //TODO: make this more efficient
  3782. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3783. return (
  3784. n41 * (
  3785. + n14 * n23 * n32
  3786. - n13 * n24 * n32
  3787. - n14 * n22 * n33
  3788. + n12 * n24 * n33
  3789. + n13 * n22 * n34
  3790. - n12 * n23 * n34
  3791. ) +
  3792. n42 * (
  3793. + n11 * n23 * n34
  3794. - n11 * n24 * n33
  3795. + n14 * n21 * n33
  3796. - n13 * n21 * n34
  3797. + n13 * n24 * n31
  3798. - n14 * n23 * n31
  3799. ) +
  3800. n43 * (
  3801. + n11 * n24 * n32
  3802. - n11 * n22 * n34
  3803. - n14 * n21 * n32
  3804. + n12 * n21 * n34
  3805. + n14 * n22 * n31
  3806. - n12 * n24 * n31
  3807. ) +
  3808. n44 * (
  3809. - n13 * n22 * n31
  3810. - n11 * n23 * n32
  3811. + n11 * n22 * n33
  3812. + n13 * n21 * n32
  3813. - n12 * n21 * n33
  3814. + n12 * n23 * n31
  3815. )
  3816. );
  3817. }
  3818. transpose() {
  3819. const te = this.elements;
  3820. let tmp;
  3821. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3822. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3823. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3824. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3825. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3826. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3827. return this;
  3828. }
  3829. setPosition( x, y, z ) {
  3830. const te = this.elements;
  3831. if ( x.isVector3 ) {
  3832. te[ 12 ] = x.x;
  3833. te[ 13 ] = x.y;
  3834. te[ 14 ] = x.z;
  3835. } else {
  3836. te[ 12 ] = x;
  3837. te[ 13 ] = y;
  3838. te[ 14 ] = z;
  3839. }
  3840. return this;
  3841. }
  3842. invert() {
  3843. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3844. const te = this.elements,
  3845. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3846. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3847. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3848. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3849. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3850. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3851. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3852. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3853. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3854. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3855. const detInv = 1 / det;
  3856. te[ 0 ] = t11 * detInv;
  3857. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3858. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3859. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3860. te[ 4 ] = t12 * detInv;
  3861. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3862. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3863. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3864. te[ 8 ] = t13 * detInv;
  3865. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3866. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3867. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3868. te[ 12 ] = t14 * detInv;
  3869. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3870. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3871. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3872. return this;
  3873. }
  3874. scale( v ) {
  3875. const te = this.elements;
  3876. const x = v.x, y = v.y, z = v.z;
  3877. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3878. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3879. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3880. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3881. return this;
  3882. }
  3883. getMaxScaleOnAxis() {
  3884. const te = this.elements;
  3885. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3886. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3887. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3888. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3889. }
  3890. makeTranslation( x, y, z ) {
  3891. if ( x.isVector3 ) {
  3892. this.set(
  3893. 1, 0, 0, x.x,
  3894. 0, 1, 0, x.y,
  3895. 0, 0, 1, x.z,
  3896. 0, 0, 0, 1
  3897. );
  3898. } else {
  3899. this.set(
  3900. 1, 0, 0, x,
  3901. 0, 1, 0, y,
  3902. 0, 0, 1, z,
  3903. 0, 0, 0, 1
  3904. );
  3905. }
  3906. return this;
  3907. }
  3908. makeRotationX( theta ) {
  3909. const c = Math.cos( theta ), s = Math.sin( theta );
  3910. this.set(
  3911. 1, 0, 0, 0,
  3912. 0, c, - s, 0,
  3913. 0, s, c, 0,
  3914. 0, 0, 0, 1
  3915. );
  3916. return this;
  3917. }
  3918. makeRotationY( theta ) {
  3919. const c = Math.cos( theta ), s = Math.sin( theta );
  3920. this.set(
  3921. c, 0, s, 0,
  3922. 0, 1, 0, 0,
  3923. - s, 0, c, 0,
  3924. 0, 0, 0, 1
  3925. );
  3926. return this;
  3927. }
  3928. makeRotationZ( theta ) {
  3929. const c = Math.cos( theta ), s = Math.sin( theta );
  3930. this.set(
  3931. c, - s, 0, 0,
  3932. s, c, 0, 0,
  3933. 0, 0, 1, 0,
  3934. 0, 0, 0, 1
  3935. );
  3936. return this;
  3937. }
  3938. makeRotationAxis( axis, angle ) {
  3939. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3940. const c = Math.cos( angle );
  3941. const s = Math.sin( angle );
  3942. const t = 1 - c;
  3943. const x = axis.x, y = axis.y, z = axis.z;
  3944. const tx = t * x, ty = t * y;
  3945. this.set(
  3946. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3947. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3948. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3949. 0, 0, 0, 1
  3950. );
  3951. return this;
  3952. }
  3953. makeScale( x, y, z ) {
  3954. this.set(
  3955. x, 0, 0, 0,
  3956. 0, y, 0, 0,
  3957. 0, 0, z, 0,
  3958. 0, 0, 0, 1
  3959. );
  3960. return this;
  3961. }
  3962. makeShear( xy, xz, yx, yz, zx, zy ) {
  3963. this.set(
  3964. 1, yx, zx, 0,
  3965. xy, 1, zy, 0,
  3966. xz, yz, 1, 0,
  3967. 0, 0, 0, 1
  3968. );
  3969. return this;
  3970. }
  3971. compose( position, quaternion, scale ) {
  3972. const te = this.elements;
  3973. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3974. const x2 = x + x, y2 = y + y, z2 = z + z;
  3975. const xx = x * x2, xy = x * y2, xz = x * z2;
  3976. const yy = y * y2, yz = y * z2, zz = z * z2;
  3977. const wx = w * x2, wy = w * y2, wz = w * z2;
  3978. const sx = scale.x, sy = scale.y, sz = scale.z;
  3979. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3980. te[ 1 ] = ( xy + wz ) * sx;
  3981. te[ 2 ] = ( xz - wy ) * sx;
  3982. te[ 3 ] = 0;
  3983. te[ 4 ] = ( xy - wz ) * sy;
  3984. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3985. te[ 6 ] = ( yz + wx ) * sy;
  3986. te[ 7 ] = 0;
  3987. te[ 8 ] = ( xz + wy ) * sz;
  3988. te[ 9 ] = ( yz - wx ) * sz;
  3989. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3990. te[ 11 ] = 0;
  3991. te[ 12 ] = position.x;
  3992. te[ 13 ] = position.y;
  3993. te[ 14 ] = position.z;
  3994. te[ 15 ] = 1;
  3995. return this;
  3996. }
  3997. decompose( position, quaternion, scale ) {
  3998. const te = this.elements;
  3999. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4000. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4001. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4002. // if determine is negative, we need to invert one scale
  4003. const det = this.determinant();
  4004. if ( det < 0 ) sx = - sx;
  4005. position.x = te[ 12 ];
  4006. position.y = te[ 13 ];
  4007. position.z = te[ 14 ];
  4008. // scale the rotation part
  4009. _m1$2.copy( this );
  4010. const invSX = 1 / sx;
  4011. const invSY = 1 / sy;
  4012. const invSZ = 1 / sz;
  4013. _m1$2.elements[ 0 ] *= invSX;
  4014. _m1$2.elements[ 1 ] *= invSX;
  4015. _m1$2.elements[ 2 ] *= invSX;
  4016. _m1$2.elements[ 4 ] *= invSY;
  4017. _m1$2.elements[ 5 ] *= invSY;
  4018. _m1$2.elements[ 6 ] *= invSY;
  4019. _m1$2.elements[ 8 ] *= invSZ;
  4020. _m1$2.elements[ 9 ] *= invSZ;
  4021. _m1$2.elements[ 10 ] *= invSZ;
  4022. quaternion.setFromRotationMatrix( _m1$2 );
  4023. scale.x = sx;
  4024. scale.y = sy;
  4025. scale.z = sz;
  4026. return this;
  4027. }
  4028. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4029. const te = this.elements;
  4030. const x = 2 * near / ( right - left );
  4031. const y = 2 * near / ( top - bottom );
  4032. const a = ( right + left ) / ( right - left );
  4033. const b = ( top + bottom ) / ( top - bottom );
  4034. let c, d;
  4035. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4036. c = - ( far + near ) / ( far - near );
  4037. d = ( - 2 * far * near ) / ( far - near );
  4038. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4039. c = - far / ( far - near );
  4040. d = ( - far * near ) / ( far - near );
  4041. } else {
  4042. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4043. }
  4044. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4045. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4046. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4047. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4048. return this;
  4049. }
  4050. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4051. const te = this.elements;
  4052. const w = 1.0 / ( right - left );
  4053. const h = 1.0 / ( top - bottom );
  4054. const p = 1.0 / ( far - near );
  4055. const x = ( right + left ) * w;
  4056. const y = ( top + bottom ) * h;
  4057. let z, zInv;
  4058. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4059. z = ( far + near ) * p;
  4060. zInv = - 2 * p;
  4061. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4062. z = near * p;
  4063. zInv = - 1 * p;
  4064. } else {
  4065. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4066. }
  4067. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4068. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4069. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4070. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4071. return this;
  4072. }
  4073. equals( matrix ) {
  4074. const te = this.elements;
  4075. const me = matrix.elements;
  4076. for ( let i = 0; i < 16; i ++ ) {
  4077. if ( te[ i ] !== me[ i ] ) return false;
  4078. }
  4079. return true;
  4080. }
  4081. fromArray( array, offset = 0 ) {
  4082. for ( let i = 0; i < 16; i ++ ) {
  4083. this.elements[ i ] = array[ i + offset ];
  4084. }
  4085. return this;
  4086. }
  4087. toArray( array = [], offset = 0 ) {
  4088. const te = this.elements;
  4089. array[ offset ] = te[ 0 ];
  4090. array[ offset + 1 ] = te[ 1 ];
  4091. array[ offset + 2 ] = te[ 2 ];
  4092. array[ offset + 3 ] = te[ 3 ];
  4093. array[ offset + 4 ] = te[ 4 ];
  4094. array[ offset + 5 ] = te[ 5 ];
  4095. array[ offset + 6 ] = te[ 6 ];
  4096. array[ offset + 7 ] = te[ 7 ];
  4097. array[ offset + 8 ] = te[ 8 ];
  4098. array[ offset + 9 ] = te[ 9 ];
  4099. array[ offset + 10 ] = te[ 10 ];
  4100. array[ offset + 11 ] = te[ 11 ];
  4101. array[ offset + 12 ] = te[ 12 ];
  4102. array[ offset + 13 ] = te[ 13 ];
  4103. array[ offset + 14 ] = te[ 14 ];
  4104. array[ offset + 15 ] = te[ 15 ];
  4105. return array;
  4106. }
  4107. }
  4108. const _v1$5 = /*@__PURE__*/ new Vector3();
  4109. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4110. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4111. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4112. const _x = /*@__PURE__*/ new Vector3();
  4113. const _y = /*@__PURE__*/ new Vector3();
  4114. const _z = /*@__PURE__*/ new Vector3();
  4115. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4116. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4117. class Euler {
  4118. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4119. this.isEuler = true;
  4120. this._x = x;
  4121. this._y = y;
  4122. this._z = z;
  4123. this._order = order;
  4124. }
  4125. get x() {
  4126. return this._x;
  4127. }
  4128. set x( value ) {
  4129. this._x = value;
  4130. this._onChangeCallback();
  4131. }
  4132. get y() {
  4133. return this._y;
  4134. }
  4135. set y( value ) {
  4136. this._y = value;
  4137. this._onChangeCallback();
  4138. }
  4139. get z() {
  4140. return this._z;
  4141. }
  4142. set z( value ) {
  4143. this._z = value;
  4144. this._onChangeCallback();
  4145. }
  4146. get order() {
  4147. return this._order;
  4148. }
  4149. set order( value ) {
  4150. this._order = value;
  4151. this._onChangeCallback();
  4152. }
  4153. set( x, y, z, order = this._order ) {
  4154. this._x = x;
  4155. this._y = y;
  4156. this._z = z;
  4157. this._order = order;
  4158. this._onChangeCallback();
  4159. return this;
  4160. }
  4161. clone() {
  4162. return new this.constructor( this._x, this._y, this._z, this._order );
  4163. }
  4164. copy( euler ) {
  4165. this._x = euler._x;
  4166. this._y = euler._y;
  4167. this._z = euler._z;
  4168. this._order = euler._order;
  4169. this._onChangeCallback();
  4170. return this;
  4171. }
  4172. setFromRotationMatrix( m, order = this._order, update = true ) {
  4173. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4174. const te = m.elements;
  4175. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4176. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4177. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4178. switch ( order ) {
  4179. case 'XYZ':
  4180. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4181. if ( Math.abs( m13 ) < 0.9999999 ) {
  4182. this._x = Math.atan2( - m23, m33 );
  4183. this._z = Math.atan2( - m12, m11 );
  4184. } else {
  4185. this._x = Math.atan2( m32, m22 );
  4186. this._z = 0;
  4187. }
  4188. break;
  4189. case 'YXZ':
  4190. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4191. if ( Math.abs( m23 ) < 0.9999999 ) {
  4192. this._y = Math.atan2( m13, m33 );
  4193. this._z = Math.atan2( m21, m22 );
  4194. } else {
  4195. this._y = Math.atan2( - m31, m11 );
  4196. this._z = 0;
  4197. }
  4198. break;
  4199. case 'ZXY':
  4200. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4201. if ( Math.abs( m32 ) < 0.9999999 ) {
  4202. this._y = Math.atan2( - m31, m33 );
  4203. this._z = Math.atan2( - m12, m22 );
  4204. } else {
  4205. this._y = 0;
  4206. this._z = Math.atan2( m21, m11 );
  4207. }
  4208. break;
  4209. case 'ZYX':
  4210. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4211. if ( Math.abs( m31 ) < 0.9999999 ) {
  4212. this._x = Math.atan2( m32, m33 );
  4213. this._z = Math.atan2( m21, m11 );
  4214. } else {
  4215. this._x = 0;
  4216. this._z = Math.atan2( - m12, m22 );
  4217. }
  4218. break;
  4219. case 'YZX':
  4220. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4221. if ( Math.abs( m21 ) < 0.9999999 ) {
  4222. this._x = Math.atan2( - m23, m22 );
  4223. this._y = Math.atan2( - m31, m11 );
  4224. } else {
  4225. this._x = 0;
  4226. this._y = Math.atan2( m13, m33 );
  4227. }
  4228. break;
  4229. case 'XZY':
  4230. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4231. if ( Math.abs( m12 ) < 0.9999999 ) {
  4232. this._x = Math.atan2( m32, m22 );
  4233. this._y = Math.atan2( m13, m11 );
  4234. } else {
  4235. this._x = Math.atan2( - m23, m33 );
  4236. this._y = 0;
  4237. }
  4238. break;
  4239. default:
  4240. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4241. }
  4242. this._order = order;
  4243. if ( update === true ) this._onChangeCallback();
  4244. return this;
  4245. }
  4246. setFromQuaternion( q, order, update ) {
  4247. _matrix$1.makeRotationFromQuaternion( q );
  4248. return this.setFromRotationMatrix( _matrix$1, order, update );
  4249. }
  4250. setFromVector3( v, order = this._order ) {
  4251. return this.set( v.x, v.y, v.z, order );
  4252. }
  4253. reorder( newOrder ) {
  4254. // WARNING: this discards revolution information -bhouston
  4255. _quaternion$3.setFromEuler( this );
  4256. return this.setFromQuaternion( _quaternion$3, newOrder );
  4257. }
  4258. equals( euler ) {
  4259. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4260. }
  4261. fromArray( array ) {
  4262. this._x = array[ 0 ];
  4263. this._y = array[ 1 ];
  4264. this._z = array[ 2 ];
  4265. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4266. this._onChangeCallback();
  4267. return this;
  4268. }
  4269. toArray( array = [], offset = 0 ) {
  4270. array[ offset ] = this._x;
  4271. array[ offset + 1 ] = this._y;
  4272. array[ offset + 2 ] = this._z;
  4273. array[ offset + 3 ] = this._order;
  4274. return array;
  4275. }
  4276. _onChange( callback ) {
  4277. this._onChangeCallback = callback;
  4278. return this;
  4279. }
  4280. _onChangeCallback() {}
  4281. *[ Symbol.iterator ]() {
  4282. yield this._x;
  4283. yield this._y;
  4284. yield this._z;
  4285. yield this._order;
  4286. }
  4287. }
  4288. Euler.DEFAULT_ORDER = 'XYZ';
  4289. class Layers {
  4290. constructor() {
  4291. this.mask = 1 | 0;
  4292. }
  4293. set( channel ) {
  4294. this.mask = ( 1 << channel | 0 ) >>> 0;
  4295. }
  4296. enable( channel ) {
  4297. this.mask |= 1 << channel | 0;
  4298. }
  4299. enableAll() {
  4300. this.mask = 0xffffffff | 0;
  4301. }
  4302. toggle( channel ) {
  4303. this.mask ^= 1 << channel | 0;
  4304. }
  4305. disable( channel ) {
  4306. this.mask &= ~ ( 1 << channel | 0 );
  4307. }
  4308. disableAll() {
  4309. this.mask = 0;
  4310. }
  4311. test( layers ) {
  4312. return ( this.mask & layers.mask ) !== 0;
  4313. }
  4314. isEnabled( channel ) {
  4315. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4316. }
  4317. }
  4318. let _object3DId = 0;
  4319. const _v1$4 = /*@__PURE__*/ new Vector3();
  4320. const _q1 = /*@__PURE__*/ new Quaternion();
  4321. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4322. const _target = /*@__PURE__*/ new Vector3();
  4323. const _position$3 = /*@__PURE__*/ new Vector3();
  4324. const _scale$2 = /*@__PURE__*/ new Vector3();
  4325. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4326. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4327. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4328. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4329. const _addedEvent = { type: 'added' };
  4330. const _removedEvent = { type: 'removed' };
  4331. class Object3D extends EventDispatcher {
  4332. constructor() {
  4333. super();
  4334. this.isObject3D = true;
  4335. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4336. this.uuid = generateUUID();
  4337. this.name = '';
  4338. this.type = 'Object3D';
  4339. this.parent = null;
  4340. this.children = [];
  4341. this.up = Object3D.DEFAULT_UP.clone();
  4342. const position = new Vector3();
  4343. const rotation = new Euler();
  4344. const quaternion = new Quaternion();
  4345. const scale = new Vector3( 1, 1, 1 );
  4346. function onRotationChange() {
  4347. quaternion.setFromEuler( rotation, false );
  4348. }
  4349. function onQuaternionChange() {
  4350. rotation.setFromQuaternion( quaternion, undefined, false );
  4351. }
  4352. rotation._onChange( onRotationChange );
  4353. quaternion._onChange( onQuaternionChange );
  4354. Object.defineProperties( this, {
  4355. position: {
  4356. configurable: true,
  4357. enumerable: true,
  4358. value: position
  4359. },
  4360. rotation: {
  4361. configurable: true,
  4362. enumerable: true,
  4363. value: rotation
  4364. },
  4365. quaternion: {
  4366. configurable: true,
  4367. enumerable: true,
  4368. value: quaternion
  4369. },
  4370. scale: {
  4371. configurable: true,
  4372. enumerable: true,
  4373. value: scale
  4374. },
  4375. modelViewMatrix: {
  4376. value: new Matrix4()
  4377. },
  4378. normalMatrix: {
  4379. value: new Matrix3()
  4380. }
  4381. } );
  4382. this.matrix = new Matrix4();
  4383. this.matrixWorld = new Matrix4();
  4384. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4385. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4386. this.matrixWorldNeedsUpdate = false;
  4387. this.layers = new Layers();
  4388. this.visible = true;
  4389. this.castShadow = false;
  4390. this.receiveShadow = false;
  4391. this.frustumCulled = true;
  4392. this.renderOrder = 0;
  4393. this.animations = [];
  4394. this.userData = {};
  4395. }
  4396. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4397. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4398. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4399. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4400. applyMatrix4( matrix ) {
  4401. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4402. this.matrix.premultiply( matrix );
  4403. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4404. }
  4405. applyQuaternion( q ) {
  4406. this.quaternion.premultiply( q );
  4407. return this;
  4408. }
  4409. setRotationFromAxisAngle( axis, angle ) {
  4410. // assumes axis is normalized
  4411. this.quaternion.setFromAxisAngle( axis, angle );
  4412. }
  4413. setRotationFromEuler( euler ) {
  4414. this.quaternion.setFromEuler( euler, true );
  4415. }
  4416. setRotationFromMatrix( m ) {
  4417. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4418. this.quaternion.setFromRotationMatrix( m );
  4419. }
  4420. setRotationFromQuaternion( q ) {
  4421. // assumes q is normalized
  4422. this.quaternion.copy( q );
  4423. }
  4424. rotateOnAxis( axis, angle ) {
  4425. // rotate object on axis in object space
  4426. // axis is assumed to be normalized
  4427. _q1.setFromAxisAngle( axis, angle );
  4428. this.quaternion.multiply( _q1 );
  4429. return this;
  4430. }
  4431. rotateOnWorldAxis( axis, angle ) {
  4432. // rotate object on axis in world space
  4433. // axis is assumed to be normalized
  4434. // method assumes no rotated parent
  4435. _q1.setFromAxisAngle( axis, angle );
  4436. this.quaternion.premultiply( _q1 );
  4437. return this;
  4438. }
  4439. rotateX( angle ) {
  4440. return this.rotateOnAxis( _xAxis, angle );
  4441. }
  4442. rotateY( angle ) {
  4443. return this.rotateOnAxis( _yAxis, angle );
  4444. }
  4445. rotateZ( angle ) {
  4446. return this.rotateOnAxis( _zAxis, angle );
  4447. }
  4448. translateOnAxis( axis, distance ) {
  4449. // translate object by distance along axis in object space
  4450. // axis is assumed to be normalized
  4451. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4452. this.position.add( _v1$4.multiplyScalar( distance ) );
  4453. return this;
  4454. }
  4455. translateX( distance ) {
  4456. return this.translateOnAxis( _xAxis, distance );
  4457. }
  4458. translateY( distance ) {
  4459. return this.translateOnAxis( _yAxis, distance );
  4460. }
  4461. translateZ( distance ) {
  4462. return this.translateOnAxis( _zAxis, distance );
  4463. }
  4464. localToWorld( vector ) {
  4465. this.updateWorldMatrix( true, false );
  4466. return vector.applyMatrix4( this.matrixWorld );
  4467. }
  4468. worldToLocal( vector ) {
  4469. this.updateWorldMatrix( true, false );
  4470. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4471. }
  4472. lookAt( x, y, z ) {
  4473. // This method does not support objects having non-uniformly-scaled parent(s)
  4474. if ( x.isVector3 ) {
  4475. _target.copy( x );
  4476. } else {
  4477. _target.set( x, y, z );
  4478. }
  4479. const parent = this.parent;
  4480. this.updateWorldMatrix( true, false );
  4481. _position$3.setFromMatrixPosition( this.matrixWorld );
  4482. if ( this.isCamera || this.isLight ) {
  4483. _m1$1.lookAt( _position$3, _target, this.up );
  4484. } else {
  4485. _m1$1.lookAt( _target, _position$3, this.up );
  4486. }
  4487. this.quaternion.setFromRotationMatrix( _m1$1 );
  4488. if ( parent ) {
  4489. _m1$1.extractRotation( parent.matrixWorld );
  4490. _q1.setFromRotationMatrix( _m1$1 );
  4491. this.quaternion.premultiply( _q1.invert() );
  4492. }
  4493. }
  4494. add( object ) {
  4495. if ( arguments.length > 1 ) {
  4496. for ( let i = 0; i < arguments.length; i ++ ) {
  4497. this.add( arguments[ i ] );
  4498. }
  4499. return this;
  4500. }
  4501. if ( object === this ) {
  4502. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4503. return this;
  4504. }
  4505. if ( object && object.isObject3D ) {
  4506. if ( object.parent !== null ) {
  4507. object.parent.remove( object );
  4508. }
  4509. object.parent = this;
  4510. this.children.push( object );
  4511. object.dispatchEvent( _addedEvent );
  4512. } else {
  4513. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4514. }
  4515. return this;
  4516. }
  4517. remove( object ) {
  4518. if ( arguments.length > 1 ) {
  4519. for ( let i = 0; i < arguments.length; i ++ ) {
  4520. this.remove( arguments[ i ] );
  4521. }
  4522. return this;
  4523. }
  4524. const index = this.children.indexOf( object );
  4525. if ( index !== - 1 ) {
  4526. object.parent = null;
  4527. this.children.splice( index, 1 );
  4528. object.dispatchEvent( _removedEvent );
  4529. }
  4530. return this;
  4531. }
  4532. removeFromParent() {
  4533. const parent = this.parent;
  4534. if ( parent !== null ) {
  4535. parent.remove( this );
  4536. }
  4537. return this;
  4538. }
  4539. clear() {
  4540. return this.remove( ... this.children );
  4541. }
  4542. attach( object ) {
  4543. // adds object as a child of this, while maintaining the object's world transform
  4544. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4545. this.updateWorldMatrix( true, false );
  4546. _m1$1.copy( this.matrixWorld ).invert();
  4547. if ( object.parent !== null ) {
  4548. object.parent.updateWorldMatrix( true, false );
  4549. _m1$1.multiply( object.parent.matrixWorld );
  4550. }
  4551. object.applyMatrix4( _m1$1 );
  4552. this.add( object );
  4553. object.updateWorldMatrix( false, true );
  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.boundingSphere !== null ) {
  4739. object.boundingSphere = {
  4740. center: object.boundingSphere.center.toArray(),
  4741. radius: object.boundingSphere.radius
  4742. };
  4743. }
  4744. if ( this.boundingBox !== null ) {
  4745. object.boundingBox = {
  4746. min: object.boundingBox.min.toArray(),
  4747. max: object.boundingBox.max.toArray()
  4748. };
  4749. }
  4750. }
  4751. //
  4752. function serialize( library, element ) {
  4753. if ( library[ element.uuid ] === undefined ) {
  4754. library[ element.uuid ] = element.toJSON( meta );
  4755. }
  4756. return element.uuid;
  4757. }
  4758. if ( this.isScene ) {
  4759. if ( this.background ) {
  4760. if ( this.background.isColor ) {
  4761. object.background = this.background.toJSON();
  4762. } else if ( this.background.isTexture ) {
  4763. object.background = this.background.toJSON( meta ).uuid;
  4764. }
  4765. }
  4766. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4767. object.environment = this.environment.toJSON( meta ).uuid;
  4768. }
  4769. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4770. object.geometry = serialize( meta.geometries, this.geometry );
  4771. const parameters = this.geometry.parameters;
  4772. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4773. const shapes = parameters.shapes;
  4774. if ( Array.isArray( shapes ) ) {
  4775. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4776. const shape = shapes[ i ];
  4777. serialize( meta.shapes, shape );
  4778. }
  4779. } else {
  4780. serialize( meta.shapes, shapes );
  4781. }
  4782. }
  4783. }
  4784. if ( this.isSkinnedMesh ) {
  4785. object.bindMode = this.bindMode;
  4786. object.bindMatrix = this.bindMatrix.toArray();
  4787. if ( this.skeleton !== undefined ) {
  4788. serialize( meta.skeletons, this.skeleton );
  4789. object.skeleton = this.skeleton.uuid;
  4790. }
  4791. }
  4792. if ( this.material !== undefined ) {
  4793. if ( Array.isArray( this.material ) ) {
  4794. const uuids = [];
  4795. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4796. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4797. }
  4798. object.material = uuids;
  4799. } else {
  4800. object.material = serialize( meta.materials, this.material );
  4801. }
  4802. }
  4803. //
  4804. if ( this.children.length > 0 ) {
  4805. object.children = [];
  4806. for ( let i = 0; i < this.children.length; i ++ ) {
  4807. object.children.push( this.children[ i ].toJSON( meta ).object );
  4808. }
  4809. }
  4810. //
  4811. if ( this.animations.length > 0 ) {
  4812. object.animations = [];
  4813. for ( let i = 0; i < this.animations.length; i ++ ) {
  4814. const animation = this.animations[ i ];
  4815. object.animations.push( serialize( meta.animations, animation ) );
  4816. }
  4817. }
  4818. if ( isRootObject ) {
  4819. const geometries = extractFromCache( meta.geometries );
  4820. const materials = extractFromCache( meta.materials );
  4821. const textures = extractFromCache( meta.textures );
  4822. const images = extractFromCache( meta.images );
  4823. const shapes = extractFromCache( meta.shapes );
  4824. const skeletons = extractFromCache( meta.skeletons );
  4825. const animations = extractFromCache( meta.animations );
  4826. const nodes = extractFromCache( meta.nodes );
  4827. if ( geometries.length > 0 ) output.geometries = geometries;
  4828. if ( materials.length > 0 ) output.materials = materials;
  4829. if ( textures.length > 0 ) output.textures = textures;
  4830. if ( images.length > 0 ) output.images = images;
  4831. if ( shapes.length > 0 ) output.shapes = shapes;
  4832. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4833. if ( animations.length > 0 ) output.animations = animations;
  4834. if ( nodes.length > 0 ) output.nodes = nodes;
  4835. }
  4836. output.object = object;
  4837. return output;
  4838. // extract data from the cache hash
  4839. // remove metadata on each item
  4840. // and return as array
  4841. function extractFromCache( cache ) {
  4842. const values = [];
  4843. for ( const key in cache ) {
  4844. const data = cache[ key ];
  4845. delete data.metadata;
  4846. values.push( data );
  4847. }
  4848. return values;
  4849. }
  4850. }
  4851. clone( recursive ) {
  4852. return new this.constructor().copy( this, recursive );
  4853. }
  4854. copy( source, recursive = true ) {
  4855. this.name = source.name;
  4856. this.up.copy( source.up );
  4857. this.position.copy( source.position );
  4858. this.rotation.order = source.rotation.order;
  4859. this.quaternion.copy( source.quaternion );
  4860. this.scale.copy( source.scale );
  4861. this.matrix.copy( source.matrix );
  4862. this.matrixWorld.copy( source.matrixWorld );
  4863. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4864. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4865. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4866. this.layers.mask = source.layers.mask;
  4867. this.visible = source.visible;
  4868. this.castShadow = source.castShadow;
  4869. this.receiveShadow = source.receiveShadow;
  4870. this.frustumCulled = source.frustumCulled;
  4871. this.renderOrder = source.renderOrder;
  4872. this.animations = source.animations.slice();
  4873. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4874. if ( recursive === true ) {
  4875. for ( let i = 0; i < source.children.length; i ++ ) {
  4876. const child = source.children[ i ];
  4877. this.add( child.clone() );
  4878. }
  4879. }
  4880. return this;
  4881. }
  4882. }
  4883. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4884. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4885. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4886. const _v0$1 = /*@__PURE__*/ new Vector3();
  4887. const _v1$3 = /*@__PURE__*/ new Vector3();
  4888. const _v2$2 = /*@__PURE__*/ new Vector3();
  4889. const _v3$1 = /*@__PURE__*/ new Vector3();
  4890. const _vab = /*@__PURE__*/ new Vector3();
  4891. const _vac = /*@__PURE__*/ new Vector3();
  4892. const _vbc = /*@__PURE__*/ new Vector3();
  4893. const _vap = /*@__PURE__*/ new Vector3();
  4894. const _vbp = /*@__PURE__*/ new Vector3();
  4895. const _vcp = /*@__PURE__*/ new Vector3();
  4896. let warnedGetUV = false;
  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$1 ) === null ) {
  4939. return false;
  4940. }
  4941. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4942. }
  4943. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151
  4944. if ( warnedGetUV === false ) {
  4945. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4946. warnedGetUV = true;
  4947. }
  4948. return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );
  4949. }
  4950. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4951. if ( this.getBarycoord( point, p1, p2, p3, _v3$1 ) === null ) {
  4952. target.x = 0;
  4953. target.y = 0;
  4954. if ( 'z' in target ) target.z = 0;
  4955. if ( 'w' in target ) target.w = 0;
  4956. return null;
  4957. }
  4958. target.setScalar( 0 );
  4959. target.addScaledVector( v1, _v3$1.x );
  4960. target.addScaledVector( v2, _v3$1.y );
  4961. target.addScaledVector( v3, _v3$1.z );
  4962. return target;
  4963. }
  4964. static isFrontFacing( a, b, c, direction ) {
  4965. _v0$1.subVectors( c, b );
  4966. _v1$3.subVectors( a, b );
  4967. // strictly front facing
  4968. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4969. }
  4970. set( a, b, c ) {
  4971. this.a.copy( a );
  4972. this.b.copy( b );
  4973. this.c.copy( c );
  4974. return this;
  4975. }
  4976. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4977. this.a.copy( points[ i0 ] );
  4978. this.b.copy( points[ i1 ] );
  4979. this.c.copy( points[ i2 ] );
  4980. return this;
  4981. }
  4982. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4983. this.a.fromBufferAttribute( attribute, i0 );
  4984. this.b.fromBufferAttribute( attribute, i1 );
  4985. this.c.fromBufferAttribute( attribute, i2 );
  4986. return this;
  4987. }
  4988. clone() {
  4989. return new this.constructor().copy( this );
  4990. }
  4991. copy( triangle ) {
  4992. this.a.copy( triangle.a );
  4993. this.b.copy( triangle.b );
  4994. this.c.copy( triangle.c );
  4995. return this;
  4996. }
  4997. getArea() {
  4998. _v0$1.subVectors( this.c, this.b );
  4999. _v1$3.subVectors( this.a, this.b );
  5000. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5001. }
  5002. getMidpoint( target ) {
  5003. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5004. }
  5005. getNormal( target ) {
  5006. return Triangle.getNormal( this.a, this.b, this.c, target );
  5007. }
  5008. getPlane( target ) {
  5009. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5010. }
  5011. getBarycoord( point, target ) {
  5012. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5013. }
  5014. getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151
  5015. if ( warnedGetUV === false ) {
  5016. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  5017. warnedGetUV = true;
  5018. }
  5019. return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5020. }
  5021. getInterpolation( point, v1, v2, v3, target ) {
  5022. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5023. }
  5024. containsPoint( point ) {
  5025. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5026. }
  5027. isFrontFacing( direction ) {
  5028. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5029. }
  5030. intersectsBox( box ) {
  5031. return box.intersectsTriangle( this );
  5032. }
  5033. closestPointToPoint( p, target ) {
  5034. const a = this.a, b = this.b, c = this.c;
  5035. let v, w;
  5036. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5037. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5038. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5039. // basically, we're distinguishing which of the voronoi regions of the triangle
  5040. // the point lies in with the minimum amount of redundant computation.
  5041. _vab.subVectors( b, a );
  5042. _vac.subVectors( c, a );
  5043. _vap.subVectors( p, a );
  5044. const d1 = _vab.dot( _vap );
  5045. const d2 = _vac.dot( _vap );
  5046. if ( d1 <= 0 && d2 <= 0 ) {
  5047. // vertex region of A; barycentric coords (1, 0, 0)
  5048. return target.copy( a );
  5049. }
  5050. _vbp.subVectors( p, b );
  5051. const d3 = _vab.dot( _vbp );
  5052. const d4 = _vac.dot( _vbp );
  5053. if ( d3 >= 0 && d4 <= d3 ) {
  5054. // vertex region of B; barycentric coords (0, 1, 0)
  5055. return target.copy( b );
  5056. }
  5057. const vc = d1 * d4 - d3 * d2;
  5058. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5059. v = d1 / ( d1 - d3 );
  5060. // edge region of AB; barycentric coords (1-v, v, 0)
  5061. return target.copy( a ).addScaledVector( _vab, v );
  5062. }
  5063. _vcp.subVectors( p, c );
  5064. const d5 = _vab.dot( _vcp );
  5065. const d6 = _vac.dot( _vcp );
  5066. if ( d6 >= 0 && d5 <= d6 ) {
  5067. // vertex region of C; barycentric coords (0, 0, 1)
  5068. return target.copy( c );
  5069. }
  5070. const vb = d5 * d2 - d1 * d6;
  5071. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5072. w = d2 / ( d2 - d6 );
  5073. // edge region of AC; barycentric coords (1-w, 0, w)
  5074. return target.copy( a ).addScaledVector( _vac, w );
  5075. }
  5076. const va = d3 * d6 - d5 * d4;
  5077. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5078. _vbc.subVectors( c, b );
  5079. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5080. // edge region of BC; barycentric coords (0, 1-w, w)
  5081. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5082. }
  5083. // face region
  5084. const denom = 1 / ( va + vb + vc );
  5085. // u = va * denom
  5086. v = vb * denom;
  5087. w = vc * denom;
  5088. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5089. }
  5090. equals( triangle ) {
  5091. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5092. }
  5093. }
  5094. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5095. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5096. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5097. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5098. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5099. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5100. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5101. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5102. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5103. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5104. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5105. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5106. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5107. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5108. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5109. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5110. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5111. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5112. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5113. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5114. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5115. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5116. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5117. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5118. const _hslA = { h: 0, s: 0, l: 0 };
  5119. const _hslB = { h: 0, s: 0, l: 0 };
  5120. function hue2rgb( p, q, t ) {
  5121. if ( t < 0 ) t += 1;
  5122. if ( t > 1 ) t -= 1;
  5123. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5124. if ( t < 1 / 2 ) return q;
  5125. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5126. return p;
  5127. }
  5128. class Color {
  5129. constructor( r, g, b ) {
  5130. this.isColor = true;
  5131. this.r = 1;
  5132. this.g = 1;
  5133. this.b = 1;
  5134. return this.set( r, g, b );
  5135. }
  5136. set( r, g, b ) {
  5137. if ( g === undefined && b === undefined ) {
  5138. // r is THREE.Color, hex or string
  5139. const value = r;
  5140. if ( value && value.isColor ) {
  5141. this.copy( value );
  5142. } else if ( typeof value === 'number' ) {
  5143. this.setHex( value );
  5144. } else if ( typeof value === 'string' ) {
  5145. this.setStyle( value );
  5146. }
  5147. } else {
  5148. this.setRGB( r, g, b );
  5149. }
  5150. return this;
  5151. }
  5152. setScalar( scalar ) {
  5153. this.r = scalar;
  5154. this.g = scalar;
  5155. this.b = scalar;
  5156. return this;
  5157. }
  5158. setHex( hex, colorSpace = SRGBColorSpace ) {
  5159. hex = Math.floor( hex );
  5160. this.r = ( hex >> 16 & 255 ) / 255;
  5161. this.g = ( hex >> 8 & 255 ) / 255;
  5162. this.b = ( hex & 255 ) / 255;
  5163. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5164. return this;
  5165. }
  5166. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5167. this.r = r;
  5168. this.g = g;
  5169. this.b = b;
  5170. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5171. return this;
  5172. }
  5173. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5174. // h,s,l ranges are in 0.0 - 1.0
  5175. h = euclideanModulo( h, 1 );
  5176. s = clamp( s, 0, 1 );
  5177. l = clamp( l, 0, 1 );
  5178. if ( s === 0 ) {
  5179. this.r = this.g = this.b = l;
  5180. } else {
  5181. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5182. const q = ( 2 * l ) - p;
  5183. this.r = hue2rgb( q, p, h + 1 / 3 );
  5184. this.g = hue2rgb( q, p, h );
  5185. this.b = hue2rgb( q, p, h - 1 / 3 );
  5186. }
  5187. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5188. return this;
  5189. }
  5190. setStyle( style, colorSpace = SRGBColorSpace ) {
  5191. function handleAlpha( string ) {
  5192. if ( string === undefined ) return;
  5193. if ( parseFloat( string ) < 1 ) {
  5194. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5195. }
  5196. }
  5197. let m;
  5198. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5199. // rgb / hsl
  5200. let color;
  5201. const name = m[ 1 ];
  5202. const components = m[ 2 ];
  5203. switch ( name ) {
  5204. case 'rgb':
  5205. case 'rgba':
  5206. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5207. // rgb(255,0,0) rgba(255,0,0,0.5)
  5208. handleAlpha( color[ 4 ] );
  5209. return this.setRGB(
  5210. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5211. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5212. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5213. colorSpace
  5214. );
  5215. }
  5216. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5217. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5218. handleAlpha( color[ 4 ] );
  5219. return this.setRGB(
  5220. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5221. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5222. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5223. colorSpace
  5224. );
  5225. }
  5226. break;
  5227. case 'hsl':
  5228. case 'hsla':
  5229. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5230. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5231. handleAlpha( color[ 4 ] );
  5232. return this.setHSL(
  5233. parseFloat( color[ 1 ] ) / 360,
  5234. parseFloat( color[ 2 ] ) / 100,
  5235. parseFloat( color[ 3 ] ) / 100,
  5236. colorSpace
  5237. );
  5238. }
  5239. break;
  5240. default:
  5241. console.warn( 'THREE.Color: Unknown color model ' + style );
  5242. }
  5243. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5244. // hex color
  5245. const hex = m[ 1 ];
  5246. const size = hex.length;
  5247. if ( size === 3 ) {
  5248. // #ff0
  5249. return this.setRGB(
  5250. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5251. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5252. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5253. colorSpace
  5254. );
  5255. } else if ( size === 6 ) {
  5256. // #ff0000
  5257. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5258. } else {
  5259. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5260. }
  5261. } else if ( style && style.length > 0 ) {
  5262. return this.setColorName( style, colorSpace );
  5263. }
  5264. return this;
  5265. }
  5266. setColorName( style, colorSpace = SRGBColorSpace ) {
  5267. // color keywords
  5268. const hex = _colorKeywords[ style.toLowerCase() ];
  5269. if ( hex !== undefined ) {
  5270. // red
  5271. this.setHex( hex, colorSpace );
  5272. } else {
  5273. // unknown color
  5274. console.warn( 'THREE.Color: Unknown color ' + style );
  5275. }
  5276. return this;
  5277. }
  5278. clone() {
  5279. return new this.constructor( this.r, this.g, this.b );
  5280. }
  5281. copy( color ) {
  5282. this.r = color.r;
  5283. this.g = color.g;
  5284. this.b = color.b;
  5285. return this;
  5286. }
  5287. copySRGBToLinear( color ) {
  5288. this.r = SRGBToLinear( color.r );
  5289. this.g = SRGBToLinear( color.g );
  5290. this.b = SRGBToLinear( color.b );
  5291. return this;
  5292. }
  5293. copyLinearToSRGB( color ) {
  5294. this.r = LinearToSRGB( color.r );
  5295. this.g = LinearToSRGB( color.g );
  5296. this.b = LinearToSRGB( color.b );
  5297. return this;
  5298. }
  5299. convertSRGBToLinear() {
  5300. this.copySRGBToLinear( this );
  5301. return this;
  5302. }
  5303. convertLinearToSRGB() {
  5304. this.copyLinearToSRGB( this );
  5305. return this;
  5306. }
  5307. getHex( colorSpace = SRGBColorSpace ) {
  5308. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5309. 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 ) );
  5310. }
  5311. getHexString( colorSpace = SRGBColorSpace ) {
  5312. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5313. }
  5314. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5315. // h,s,l ranges are in 0.0 - 1.0
  5316. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5317. const r = _color.r, g = _color.g, b = _color.b;
  5318. const max = Math.max( r, g, b );
  5319. const min = Math.min( r, g, b );
  5320. let hue, saturation;
  5321. const lightness = ( min + max ) / 2.0;
  5322. if ( min === max ) {
  5323. hue = 0;
  5324. saturation = 0;
  5325. } else {
  5326. const delta = max - min;
  5327. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5328. switch ( max ) {
  5329. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5330. case g: hue = ( b - r ) / delta + 2; break;
  5331. case b: hue = ( r - g ) / delta + 4; break;
  5332. }
  5333. hue /= 6;
  5334. }
  5335. target.h = hue;
  5336. target.s = saturation;
  5337. target.l = lightness;
  5338. return target;
  5339. }
  5340. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5341. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5342. target.r = _color.r;
  5343. target.g = _color.g;
  5344. target.b = _color.b;
  5345. return target;
  5346. }
  5347. getStyle( colorSpace = SRGBColorSpace ) {
  5348. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5349. const r = _color.r, g = _color.g, b = _color.b;
  5350. if ( colorSpace !== SRGBColorSpace ) {
  5351. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5352. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5353. }
  5354. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5355. }
  5356. offsetHSL( h, s, l ) {
  5357. this.getHSL( _hslA );
  5358. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5359. }
  5360. add( color ) {
  5361. this.r += color.r;
  5362. this.g += color.g;
  5363. this.b += color.b;
  5364. return this;
  5365. }
  5366. addColors( color1, color2 ) {
  5367. this.r = color1.r + color2.r;
  5368. this.g = color1.g + color2.g;
  5369. this.b = color1.b + color2.b;
  5370. return this;
  5371. }
  5372. addScalar( s ) {
  5373. this.r += s;
  5374. this.g += s;
  5375. this.b += s;
  5376. return this;
  5377. }
  5378. sub( color ) {
  5379. this.r = Math.max( 0, this.r - color.r );
  5380. this.g = Math.max( 0, this.g - color.g );
  5381. this.b = Math.max( 0, this.b - color.b );
  5382. return this;
  5383. }
  5384. multiply( color ) {
  5385. this.r *= color.r;
  5386. this.g *= color.g;
  5387. this.b *= color.b;
  5388. return this;
  5389. }
  5390. multiplyScalar( s ) {
  5391. this.r *= s;
  5392. this.g *= s;
  5393. this.b *= s;
  5394. return this;
  5395. }
  5396. lerp( color, alpha ) {
  5397. this.r += ( color.r - this.r ) * alpha;
  5398. this.g += ( color.g - this.g ) * alpha;
  5399. this.b += ( color.b - this.b ) * alpha;
  5400. return this;
  5401. }
  5402. lerpColors( color1, color2, alpha ) {
  5403. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5404. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5405. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5406. return this;
  5407. }
  5408. lerpHSL( color, alpha ) {
  5409. this.getHSL( _hslA );
  5410. color.getHSL( _hslB );
  5411. const h = lerp( _hslA.h, _hslB.h, alpha );
  5412. const s = lerp( _hslA.s, _hslB.s, alpha );
  5413. const l = lerp( _hslA.l, _hslB.l, alpha );
  5414. this.setHSL( h, s, l );
  5415. return this;
  5416. }
  5417. setFromVector3( v ) {
  5418. this.r = v.x;
  5419. this.g = v.y;
  5420. this.b = v.z;
  5421. return this;
  5422. }
  5423. applyMatrix3( m ) {
  5424. const r = this.r, g = this.g, b = this.b;
  5425. const e = m.elements;
  5426. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5427. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5428. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5429. return this;
  5430. }
  5431. equals( c ) {
  5432. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5433. }
  5434. fromArray( array, offset = 0 ) {
  5435. this.r = array[ offset ];
  5436. this.g = array[ offset + 1 ];
  5437. this.b = array[ offset + 2 ];
  5438. return this;
  5439. }
  5440. toArray( array = [], offset = 0 ) {
  5441. array[ offset ] = this.r;
  5442. array[ offset + 1 ] = this.g;
  5443. array[ offset + 2 ] = this.b;
  5444. return array;
  5445. }
  5446. fromBufferAttribute( attribute, index ) {
  5447. this.r = attribute.getX( index );
  5448. this.g = attribute.getY( index );
  5449. this.b = attribute.getZ( index );
  5450. return this;
  5451. }
  5452. toJSON() {
  5453. return this.getHex();
  5454. }
  5455. *[ Symbol.iterator ]() {
  5456. yield this.r;
  5457. yield this.g;
  5458. yield this.b;
  5459. }
  5460. }
  5461. const _color = /*@__PURE__*/ new Color();
  5462. Color.NAMES = _colorKeywords;
  5463. let _materialId = 0;
  5464. class Material extends EventDispatcher {
  5465. constructor() {
  5466. super();
  5467. this.isMaterial = true;
  5468. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5469. this.uuid = generateUUID();
  5470. this.name = '';
  5471. this.type = 'Material';
  5472. this.blending = NormalBlending;
  5473. this.side = FrontSide;
  5474. this.vertexColors = false;
  5475. this.opacity = 1;
  5476. this.transparent = false;
  5477. this.alphaHash = false;
  5478. this.blendSrc = SrcAlphaFactor;
  5479. this.blendDst = OneMinusSrcAlphaFactor;
  5480. this.blendEquation = AddEquation;
  5481. this.blendSrcAlpha = null;
  5482. this.blendDstAlpha = null;
  5483. this.blendEquationAlpha = null;
  5484. this.blendColor = new Color( 0, 0, 0 );
  5485. this.blendAlpha = 0;
  5486. this.depthFunc = LessEqualDepth;
  5487. this.depthTest = true;
  5488. this.depthWrite = true;
  5489. this.stencilWriteMask = 0xff;
  5490. this.stencilFunc = AlwaysStencilFunc;
  5491. this.stencilRef = 0;
  5492. this.stencilFuncMask = 0xff;
  5493. this.stencilFail = KeepStencilOp;
  5494. this.stencilZFail = KeepStencilOp;
  5495. this.stencilZPass = KeepStencilOp;
  5496. this.stencilWrite = false;
  5497. this.clippingPlanes = null;
  5498. this.clipIntersection = false;
  5499. this.clipShadows = false;
  5500. this.shadowSide = null;
  5501. this.colorWrite = true;
  5502. this.precision = null; // override the renderer's default precision for this material
  5503. this.polygonOffset = false;
  5504. this.polygonOffsetFactor = 0;
  5505. this.polygonOffsetUnits = 0;
  5506. this.dithering = false;
  5507. this.alphaToCoverage = false;
  5508. this.premultipliedAlpha = false;
  5509. this.forceSinglePass = false;
  5510. this.visible = true;
  5511. this.toneMapped = true;
  5512. this.userData = {};
  5513. this.version = 0;
  5514. this._alphaTest = 0;
  5515. }
  5516. get alphaTest() {
  5517. return this._alphaTest;
  5518. }
  5519. set alphaTest( value ) {
  5520. if ( this._alphaTest > 0 !== value > 0 ) {
  5521. this.version ++;
  5522. }
  5523. this._alphaTest = value;
  5524. }
  5525. onBuild( /* shaderobject, renderer */ ) {}
  5526. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5527. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5528. customProgramCacheKey() {
  5529. return this.onBeforeCompile.toString();
  5530. }
  5531. setValues( values ) {
  5532. if ( values === undefined ) return;
  5533. for ( const key in values ) {
  5534. const newValue = values[ key ];
  5535. if ( newValue === undefined ) {
  5536. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5537. continue;
  5538. }
  5539. const currentValue = this[ key ];
  5540. if ( currentValue === undefined ) {
  5541. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5542. continue;
  5543. }
  5544. if ( currentValue && currentValue.isColor ) {
  5545. currentValue.set( newValue );
  5546. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5547. currentValue.copy( newValue );
  5548. } else {
  5549. this[ key ] = newValue;
  5550. }
  5551. }
  5552. }
  5553. toJSON( meta ) {
  5554. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5555. if ( isRootObject ) {
  5556. meta = {
  5557. textures: {},
  5558. images: {}
  5559. };
  5560. }
  5561. const data = {
  5562. metadata: {
  5563. version: 4.6,
  5564. type: 'Material',
  5565. generator: 'Material.toJSON'
  5566. }
  5567. };
  5568. // standard Material serialization
  5569. data.uuid = this.uuid;
  5570. data.type = this.type;
  5571. if ( this.name !== '' ) data.name = this.name;
  5572. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5573. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5574. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5575. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5576. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5577. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5578. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5579. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5580. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5581. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5582. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5583. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5584. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5585. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5586. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5587. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5588. }
  5589. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5590. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5591. }
  5592. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5593. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5594. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5595. }
  5596. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5597. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5598. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5599. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5600. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5601. }
  5602. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5603. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5604. }
  5605. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5606. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5607. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5608. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5609. }
  5610. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5611. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5612. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5613. if ( this.lightMap && this.lightMap.isTexture ) {
  5614. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5615. data.lightMapIntensity = this.lightMapIntensity;
  5616. }
  5617. if ( this.aoMap && this.aoMap.isTexture ) {
  5618. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5619. data.aoMapIntensity = this.aoMapIntensity;
  5620. }
  5621. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5622. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5623. data.bumpScale = this.bumpScale;
  5624. }
  5625. if ( this.normalMap && this.normalMap.isTexture ) {
  5626. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5627. data.normalMapType = this.normalMapType;
  5628. data.normalScale = this.normalScale.toArray();
  5629. }
  5630. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5631. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5632. data.displacementScale = this.displacementScale;
  5633. data.displacementBias = this.displacementBias;
  5634. }
  5635. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5636. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5637. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5638. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5639. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5640. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5641. if ( this.envMap && this.envMap.isTexture ) {
  5642. data.envMap = this.envMap.toJSON( meta ).uuid;
  5643. if ( this.combine !== undefined ) data.combine = this.combine;
  5644. }
  5645. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5646. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5647. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5648. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5649. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5650. }
  5651. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5652. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5653. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5654. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5655. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5656. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5657. if ( this.size !== undefined ) data.size = this.size;
  5658. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5659. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5660. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5661. if ( this.side !== FrontSide ) data.side = this.side;
  5662. if ( this.vertexColors === true ) data.vertexColors = true;
  5663. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5664. if ( this.transparent === true ) data.transparent = true;
  5665. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5666. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5667. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5668. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5669. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5670. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5671. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5672. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5673. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5674. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5675. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5676. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5677. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5678. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5679. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5680. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5681. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5682. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5683. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5684. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5685. // rotation (SpriteMaterial)
  5686. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5687. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5688. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5689. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5690. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5691. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5692. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5693. if ( this.scale !== undefined ) data.scale = this.scale;
  5694. if ( this.dithering === true ) data.dithering = true;
  5695. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5696. if ( this.alphaHash === true ) data.alphaHash = true;
  5697. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5698. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5699. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5700. if ( this.wireframe === true ) data.wireframe = true;
  5701. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5702. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5703. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5704. if ( this.flatShading === true ) data.flatShading = true;
  5705. if ( this.visible === false ) data.visible = false;
  5706. if ( this.toneMapped === false ) data.toneMapped = false;
  5707. if ( this.fog === false ) data.fog = false;
  5708. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5709. // TODO: Copied from Object3D.toJSON
  5710. function extractFromCache( cache ) {
  5711. const values = [];
  5712. for ( const key in cache ) {
  5713. const data = cache[ key ];
  5714. delete data.metadata;
  5715. values.push( data );
  5716. }
  5717. return values;
  5718. }
  5719. if ( isRootObject ) {
  5720. const textures = extractFromCache( meta.textures );
  5721. const images = extractFromCache( meta.images );
  5722. if ( textures.length > 0 ) data.textures = textures;
  5723. if ( images.length > 0 ) data.images = images;
  5724. }
  5725. return data;
  5726. }
  5727. clone() {
  5728. return new this.constructor().copy( this );
  5729. }
  5730. copy( source ) {
  5731. this.name = source.name;
  5732. this.blending = source.blending;
  5733. this.side = source.side;
  5734. this.vertexColors = source.vertexColors;
  5735. this.opacity = source.opacity;
  5736. this.transparent = source.transparent;
  5737. this.blendSrc = source.blendSrc;
  5738. this.blendDst = source.blendDst;
  5739. this.blendEquation = source.blendEquation;
  5740. this.blendSrcAlpha = source.blendSrcAlpha;
  5741. this.blendDstAlpha = source.blendDstAlpha;
  5742. this.blendEquationAlpha = source.blendEquationAlpha;
  5743. this.blendColor.copy( source.blendColor );
  5744. this.blendAlpha = source.blendAlpha;
  5745. this.depthFunc = source.depthFunc;
  5746. this.depthTest = source.depthTest;
  5747. this.depthWrite = source.depthWrite;
  5748. this.stencilWriteMask = source.stencilWriteMask;
  5749. this.stencilFunc = source.stencilFunc;
  5750. this.stencilRef = source.stencilRef;
  5751. this.stencilFuncMask = source.stencilFuncMask;
  5752. this.stencilFail = source.stencilFail;
  5753. this.stencilZFail = source.stencilZFail;
  5754. this.stencilZPass = source.stencilZPass;
  5755. this.stencilWrite = source.stencilWrite;
  5756. const srcPlanes = source.clippingPlanes;
  5757. let dstPlanes = null;
  5758. if ( srcPlanes !== null ) {
  5759. const n = srcPlanes.length;
  5760. dstPlanes = new Array( n );
  5761. for ( let i = 0; i !== n; ++ i ) {
  5762. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5763. }
  5764. }
  5765. this.clippingPlanes = dstPlanes;
  5766. this.clipIntersection = source.clipIntersection;
  5767. this.clipShadows = source.clipShadows;
  5768. this.shadowSide = source.shadowSide;
  5769. this.colorWrite = source.colorWrite;
  5770. this.precision = source.precision;
  5771. this.polygonOffset = source.polygonOffset;
  5772. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5773. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5774. this.dithering = source.dithering;
  5775. this.alphaTest = source.alphaTest;
  5776. this.alphaHash = source.alphaHash;
  5777. this.alphaToCoverage = source.alphaToCoverage;
  5778. this.premultipliedAlpha = source.premultipliedAlpha;
  5779. this.forceSinglePass = source.forceSinglePass;
  5780. this.visible = source.visible;
  5781. this.toneMapped = source.toneMapped;
  5782. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5783. return this;
  5784. }
  5785. dispose() {
  5786. this.dispatchEvent( { type: 'dispose' } );
  5787. }
  5788. set needsUpdate( value ) {
  5789. if ( value === true ) this.version ++;
  5790. }
  5791. }
  5792. class MeshBasicMaterial extends Material {
  5793. constructor( parameters ) {
  5794. super();
  5795. this.isMeshBasicMaterial = true;
  5796. this.type = 'MeshBasicMaterial';
  5797. this.color = new Color( 0xffffff ); // emissive
  5798. this.map = null;
  5799. this.lightMap = null;
  5800. this.lightMapIntensity = 1.0;
  5801. this.aoMap = null;
  5802. this.aoMapIntensity = 1.0;
  5803. this.specularMap = null;
  5804. this.alphaMap = null;
  5805. this.envMap = null;
  5806. this.combine = MultiplyOperation;
  5807. this.reflectivity = 1;
  5808. this.refractionRatio = 0.98;
  5809. this.wireframe = false;
  5810. this.wireframeLinewidth = 1;
  5811. this.wireframeLinecap = 'round';
  5812. this.wireframeLinejoin = 'round';
  5813. this.fog = true;
  5814. this.setValues( parameters );
  5815. }
  5816. copy( source ) {
  5817. super.copy( source );
  5818. this.color.copy( source.color );
  5819. this.map = source.map;
  5820. this.lightMap = source.lightMap;
  5821. this.lightMapIntensity = source.lightMapIntensity;
  5822. this.aoMap = source.aoMap;
  5823. this.aoMapIntensity = source.aoMapIntensity;
  5824. this.specularMap = source.specularMap;
  5825. this.alphaMap = source.alphaMap;
  5826. this.envMap = source.envMap;
  5827. this.combine = source.combine;
  5828. this.reflectivity = source.reflectivity;
  5829. this.refractionRatio = source.refractionRatio;
  5830. this.wireframe = source.wireframe;
  5831. this.wireframeLinewidth = source.wireframeLinewidth;
  5832. this.wireframeLinecap = source.wireframeLinecap;
  5833. this.wireframeLinejoin = source.wireframeLinejoin;
  5834. this.fog = source.fog;
  5835. return this;
  5836. }
  5837. }
  5838. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5839. const _tables = /*@__PURE__*/ _generateTables();
  5840. function _generateTables() {
  5841. // float32 to float16 helpers
  5842. const buffer = new ArrayBuffer( 4 );
  5843. const floatView = new Float32Array( buffer );
  5844. const uint32View = new Uint32Array( buffer );
  5845. const baseTable = new Uint32Array( 512 );
  5846. const shiftTable = new Uint32Array( 512 );
  5847. for ( let i = 0; i < 256; ++ i ) {
  5848. const e = i - 127;
  5849. // very small number (0, -0)
  5850. if ( e < - 27 ) {
  5851. baseTable[ i ] = 0x0000;
  5852. baseTable[ i | 0x100 ] = 0x8000;
  5853. shiftTable[ i ] = 24;
  5854. shiftTable[ i | 0x100 ] = 24;
  5855. // small number (denorm)
  5856. } else if ( e < - 14 ) {
  5857. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5858. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5859. shiftTable[ i ] = - e - 1;
  5860. shiftTable[ i | 0x100 ] = - e - 1;
  5861. // normal number
  5862. } else if ( e <= 15 ) {
  5863. baseTable[ i ] = ( e + 15 ) << 10;
  5864. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5865. shiftTable[ i ] = 13;
  5866. shiftTable[ i | 0x100 ] = 13;
  5867. // large number (Infinity, -Infinity)
  5868. } else if ( e < 128 ) {
  5869. baseTable[ i ] = 0x7c00;
  5870. baseTable[ i | 0x100 ] = 0xfc00;
  5871. shiftTable[ i ] = 24;
  5872. shiftTable[ i | 0x100 ] = 24;
  5873. // stay (NaN, Infinity, -Infinity)
  5874. } else {
  5875. baseTable[ i ] = 0x7c00;
  5876. baseTable[ i | 0x100 ] = 0xfc00;
  5877. shiftTable[ i ] = 13;
  5878. shiftTable[ i | 0x100 ] = 13;
  5879. }
  5880. }
  5881. // float16 to float32 helpers
  5882. const mantissaTable = new Uint32Array( 2048 );
  5883. const exponentTable = new Uint32Array( 64 );
  5884. const offsetTable = new Uint32Array( 64 );
  5885. for ( let i = 1; i < 1024; ++ i ) {
  5886. let m = i << 13; // zero pad mantissa bits
  5887. let e = 0; // zero exponent
  5888. // normalized
  5889. while ( ( m & 0x00800000 ) === 0 ) {
  5890. m <<= 1;
  5891. e -= 0x00800000; // decrement exponent
  5892. }
  5893. m &= ~ 0x00800000; // clear leading 1 bit
  5894. e += 0x38800000; // adjust bias
  5895. mantissaTable[ i ] = m | e;
  5896. }
  5897. for ( let i = 1024; i < 2048; ++ i ) {
  5898. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5899. }
  5900. for ( let i = 1; i < 31; ++ i ) {
  5901. exponentTable[ i ] = i << 23;
  5902. }
  5903. exponentTable[ 31 ] = 0x47800000;
  5904. exponentTable[ 32 ] = 0x80000000;
  5905. for ( let i = 33; i < 63; ++ i ) {
  5906. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5907. }
  5908. exponentTable[ 63 ] = 0xc7800000;
  5909. for ( let i = 1; i < 64; ++ i ) {
  5910. if ( i !== 32 ) {
  5911. offsetTable[ i ] = 1024;
  5912. }
  5913. }
  5914. return {
  5915. floatView: floatView,
  5916. uint32View: uint32View,
  5917. baseTable: baseTable,
  5918. shiftTable: shiftTable,
  5919. mantissaTable: mantissaTable,
  5920. exponentTable: exponentTable,
  5921. offsetTable: offsetTable
  5922. };
  5923. }
  5924. // float32 to float16
  5925. function toHalfFloat( val ) {
  5926. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5927. val = clamp( val, - 65504, 65504 );
  5928. _tables.floatView[ 0 ] = val;
  5929. const f = _tables.uint32View[ 0 ];
  5930. const e = ( f >> 23 ) & 0x1ff;
  5931. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5932. }
  5933. // float16 to float32
  5934. function fromHalfFloat( val ) {
  5935. const m = val >> 10;
  5936. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5937. return _tables.floatView[ 0 ];
  5938. }
  5939. const DataUtils = {
  5940. toHalfFloat: toHalfFloat,
  5941. fromHalfFloat: fromHalfFloat,
  5942. };
  5943. const _vector$9 = /*@__PURE__*/ new Vector3();
  5944. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5945. class BufferAttribute {
  5946. constructor( array, itemSize, normalized = false ) {
  5947. if ( Array.isArray( array ) ) {
  5948. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5949. }
  5950. this.isBufferAttribute = true;
  5951. this.name = '';
  5952. this.array = array;
  5953. this.itemSize = itemSize;
  5954. this.count = array !== undefined ? array.length / itemSize : 0;
  5955. this.normalized = normalized;
  5956. this.usage = StaticDrawUsage;
  5957. this._updateRange = { offset: 0, count: - 1 };
  5958. this.updateRanges = [];
  5959. this.gpuType = FloatType;
  5960. this.version = 0;
  5961. }
  5962. onUploadCallback() {}
  5963. set needsUpdate( value ) {
  5964. if ( value === true ) this.version ++;
  5965. }
  5966. get updateRange() {
  5967. console.warn( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5968. return this._updateRange;
  5969. }
  5970. setUsage( value ) {
  5971. this.usage = value;
  5972. return this;
  5973. }
  5974. addUpdateRange( start, count ) {
  5975. this.updateRanges.push( { start, count } );
  5976. }
  5977. clearUpdateRanges() {
  5978. this.updateRanges.length = 0;
  5979. }
  5980. copy( source ) {
  5981. this.name = source.name;
  5982. this.array = new source.array.constructor( source.array );
  5983. this.itemSize = source.itemSize;
  5984. this.count = source.count;
  5985. this.normalized = source.normalized;
  5986. this.usage = source.usage;
  5987. this.gpuType = source.gpuType;
  5988. return this;
  5989. }
  5990. copyAt( index1, attribute, index2 ) {
  5991. index1 *= this.itemSize;
  5992. index2 *= attribute.itemSize;
  5993. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5994. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5995. }
  5996. return this;
  5997. }
  5998. copyArray( array ) {
  5999. this.array.set( array );
  6000. return this;
  6001. }
  6002. applyMatrix3( m ) {
  6003. if ( this.itemSize === 2 ) {
  6004. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6005. _vector2$1.fromBufferAttribute( this, i );
  6006. _vector2$1.applyMatrix3( m );
  6007. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6008. }
  6009. } else if ( this.itemSize === 3 ) {
  6010. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6011. _vector$9.fromBufferAttribute( this, i );
  6012. _vector$9.applyMatrix3( m );
  6013. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6014. }
  6015. }
  6016. return this;
  6017. }
  6018. applyMatrix4( m ) {
  6019. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6020. _vector$9.fromBufferAttribute( this, i );
  6021. _vector$9.applyMatrix4( m );
  6022. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6023. }
  6024. return this;
  6025. }
  6026. applyNormalMatrix( m ) {
  6027. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6028. _vector$9.fromBufferAttribute( this, i );
  6029. _vector$9.applyNormalMatrix( m );
  6030. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6031. }
  6032. return this;
  6033. }
  6034. transformDirection( m ) {
  6035. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6036. _vector$9.fromBufferAttribute( this, i );
  6037. _vector$9.transformDirection( m );
  6038. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6039. }
  6040. return this;
  6041. }
  6042. set( value, offset = 0 ) {
  6043. // Matching BufferAttribute constructor, do not normalize the array.
  6044. this.array.set( value, offset );
  6045. return this;
  6046. }
  6047. getComponent( index, component ) {
  6048. let value = this.array[ index * this.itemSize + component ];
  6049. if ( this.normalized ) value = denormalize( value, this.array );
  6050. return value;
  6051. }
  6052. setComponent( index, component, value ) {
  6053. if ( this.normalized ) value = normalize( value, this.array );
  6054. this.array[ index * this.itemSize + component ] = value;
  6055. return this;
  6056. }
  6057. getX( index ) {
  6058. let x = this.array[ index * this.itemSize ];
  6059. if ( this.normalized ) x = denormalize( x, this.array );
  6060. return x;
  6061. }
  6062. setX( index, x ) {
  6063. if ( this.normalized ) x = normalize( x, this.array );
  6064. this.array[ index * this.itemSize ] = x;
  6065. return this;
  6066. }
  6067. getY( index ) {
  6068. let y = this.array[ index * this.itemSize + 1 ];
  6069. if ( this.normalized ) y = denormalize( y, this.array );
  6070. return y;
  6071. }
  6072. setY( index, y ) {
  6073. if ( this.normalized ) y = normalize( y, this.array );
  6074. this.array[ index * this.itemSize + 1 ] = y;
  6075. return this;
  6076. }
  6077. getZ( index ) {
  6078. let z = this.array[ index * this.itemSize + 2 ];
  6079. if ( this.normalized ) z = denormalize( z, this.array );
  6080. return z;
  6081. }
  6082. setZ( index, z ) {
  6083. if ( this.normalized ) z = normalize( z, this.array );
  6084. this.array[ index * this.itemSize + 2 ] = z;
  6085. return this;
  6086. }
  6087. getW( index ) {
  6088. let w = this.array[ index * this.itemSize + 3 ];
  6089. if ( this.normalized ) w = denormalize( w, this.array );
  6090. return w;
  6091. }
  6092. setW( index, w ) {
  6093. if ( this.normalized ) w = normalize( w, this.array );
  6094. this.array[ index * this.itemSize + 3 ] = w;
  6095. return this;
  6096. }
  6097. setXY( index, x, y ) {
  6098. index *= this.itemSize;
  6099. if ( this.normalized ) {
  6100. x = normalize( x, this.array );
  6101. y = normalize( y, this.array );
  6102. }
  6103. this.array[ index + 0 ] = x;
  6104. this.array[ index + 1 ] = y;
  6105. return this;
  6106. }
  6107. setXYZ( index, x, y, z ) {
  6108. index *= this.itemSize;
  6109. if ( this.normalized ) {
  6110. x = normalize( x, this.array );
  6111. y = normalize( y, this.array );
  6112. z = normalize( z, this.array );
  6113. }
  6114. this.array[ index + 0 ] = x;
  6115. this.array[ index + 1 ] = y;
  6116. this.array[ index + 2 ] = z;
  6117. return this;
  6118. }
  6119. setXYZW( index, x, y, z, w ) {
  6120. index *= this.itemSize;
  6121. if ( this.normalized ) {
  6122. x = normalize( x, this.array );
  6123. y = normalize( y, this.array );
  6124. z = normalize( z, this.array );
  6125. w = normalize( w, this.array );
  6126. }
  6127. this.array[ index + 0 ] = x;
  6128. this.array[ index + 1 ] = y;
  6129. this.array[ index + 2 ] = z;
  6130. this.array[ index + 3 ] = w;
  6131. return this;
  6132. }
  6133. onUpload( callback ) {
  6134. this.onUploadCallback = callback;
  6135. return this;
  6136. }
  6137. clone() {
  6138. return new this.constructor( this.array, this.itemSize ).copy( this );
  6139. }
  6140. toJSON() {
  6141. const data = {
  6142. itemSize: this.itemSize,
  6143. type: this.array.constructor.name,
  6144. array: Array.from( this.array ),
  6145. normalized: this.normalized
  6146. };
  6147. if ( this.name !== '' ) data.name = this.name;
  6148. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6149. return data;
  6150. }
  6151. }
  6152. //
  6153. class Int8BufferAttribute extends BufferAttribute {
  6154. constructor( array, itemSize, normalized ) {
  6155. super( new Int8Array( array ), itemSize, normalized );
  6156. }
  6157. }
  6158. class Uint8BufferAttribute extends BufferAttribute {
  6159. constructor( array, itemSize, normalized ) {
  6160. super( new Uint8Array( array ), itemSize, normalized );
  6161. }
  6162. }
  6163. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6164. constructor( array, itemSize, normalized ) {
  6165. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6166. }
  6167. }
  6168. class Int16BufferAttribute extends BufferAttribute {
  6169. constructor( array, itemSize, normalized ) {
  6170. super( new Int16Array( array ), itemSize, normalized );
  6171. }
  6172. }
  6173. class Uint16BufferAttribute extends BufferAttribute {
  6174. constructor( array, itemSize, normalized ) {
  6175. super( new Uint16Array( array ), itemSize, normalized );
  6176. }
  6177. }
  6178. class Int32BufferAttribute extends BufferAttribute {
  6179. constructor( array, itemSize, normalized ) {
  6180. super( new Int32Array( array ), itemSize, normalized );
  6181. }
  6182. }
  6183. class Uint32BufferAttribute extends BufferAttribute {
  6184. constructor( array, itemSize, normalized ) {
  6185. super( new Uint32Array( array ), itemSize, normalized );
  6186. }
  6187. }
  6188. class Float16BufferAttribute extends BufferAttribute {
  6189. constructor( array, itemSize, normalized ) {
  6190. super( new Uint16Array( array ), itemSize, normalized );
  6191. this.isFloat16BufferAttribute = true;
  6192. }
  6193. getX( index ) {
  6194. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6195. if ( this.normalized ) x = denormalize( x, this.array );
  6196. return x;
  6197. }
  6198. setX( index, x ) {
  6199. if ( this.normalized ) x = normalize( x, this.array );
  6200. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6201. return this;
  6202. }
  6203. getY( index ) {
  6204. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6205. if ( this.normalized ) y = denormalize( y, this.array );
  6206. return y;
  6207. }
  6208. setY( index, y ) {
  6209. if ( this.normalized ) y = normalize( y, this.array );
  6210. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6211. return this;
  6212. }
  6213. getZ( index ) {
  6214. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6215. if ( this.normalized ) z = denormalize( z, this.array );
  6216. return z;
  6217. }
  6218. setZ( index, z ) {
  6219. if ( this.normalized ) z = normalize( z, this.array );
  6220. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6221. return this;
  6222. }
  6223. getW( index ) {
  6224. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6225. if ( this.normalized ) w = denormalize( w, this.array );
  6226. return w;
  6227. }
  6228. setW( index, w ) {
  6229. if ( this.normalized ) w = normalize( w, this.array );
  6230. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6231. return this;
  6232. }
  6233. setXY( index, x, y ) {
  6234. index *= this.itemSize;
  6235. if ( this.normalized ) {
  6236. x = normalize( x, this.array );
  6237. y = normalize( y, this.array );
  6238. }
  6239. this.array[ index + 0 ] = toHalfFloat( x );
  6240. this.array[ index + 1 ] = toHalfFloat( y );
  6241. return this;
  6242. }
  6243. setXYZ( index, x, y, z ) {
  6244. index *= this.itemSize;
  6245. if ( this.normalized ) {
  6246. x = normalize( x, this.array );
  6247. y = normalize( y, this.array );
  6248. z = normalize( z, this.array );
  6249. }
  6250. this.array[ index + 0 ] = toHalfFloat( x );
  6251. this.array[ index + 1 ] = toHalfFloat( y );
  6252. this.array[ index + 2 ] = toHalfFloat( z );
  6253. return this;
  6254. }
  6255. setXYZW( index, x, y, z, w ) {
  6256. index *= this.itemSize;
  6257. if ( this.normalized ) {
  6258. x = normalize( x, this.array );
  6259. y = normalize( y, this.array );
  6260. z = normalize( z, this.array );
  6261. w = normalize( w, this.array );
  6262. }
  6263. this.array[ index + 0 ] = toHalfFloat( x );
  6264. this.array[ index + 1 ] = toHalfFloat( y );
  6265. this.array[ index + 2 ] = toHalfFloat( z );
  6266. this.array[ index + 3 ] = toHalfFloat( w );
  6267. return this;
  6268. }
  6269. }
  6270. class Float32BufferAttribute extends BufferAttribute {
  6271. constructor( array, itemSize, normalized ) {
  6272. super( new Float32Array( array ), itemSize, normalized );
  6273. }
  6274. }
  6275. class Float64BufferAttribute extends BufferAttribute {
  6276. constructor( array, itemSize, normalized ) {
  6277. super( new Float64Array( array ), itemSize, normalized );
  6278. }
  6279. }
  6280. let _id$2 = 0;
  6281. const _m1 = /*@__PURE__*/ new Matrix4();
  6282. const _obj = /*@__PURE__*/ new Object3D();
  6283. const _offset = /*@__PURE__*/ new Vector3();
  6284. const _box$2 = /*@__PURE__*/ new Box3();
  6285. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6286. const _vector$8 = /*@__PURE__*/ new Vector3();
  6287. class BufferGeometry extends EventDispatcher {
  6288. constructor() {
  6289. super();
  6290. this.isBufferGeometry = true;
  6291. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6292. this.uuid = generateUUID();
  6293. this.name = '';
  6294. this.type = 'BufferGeometry';
  6295. this.index = null;
  6296. this.attributes = {};
  6297. this.morphAttributes = {};
  6298. this.morphTargetsRelative = false;
  6299. this.groups = [];
  6300. this.boundingBox = null;
  6301. this.boundingSphere = null;
  6302. this.drawRange = { start: 0, count: Infinity };
  6303. this.userData = {};
  6304. }
  6305. getIndex() {
  6306. return this.index;
  6307. }
  6308. setIndex( index ) {
  6309. if ( Array.isArray( index ) ) {
  6310. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6311. } else {
  6312. this.index = index;
  6313. }
  6314. return this;
  6315. }
  6316. getAttribute( name ) {
  6317. return this.attributes[ name ];
  6318. }
  6319. setAttribute( name, attribute ) {
  6320. this.attributes[ name ] = attribute;
  6321. return this;
  6322. }
  6323. deleteAttribute( name ) {
  6324. delete this.attributes[ name ];
  6325. return this;
  6326. }
  6327. hasAttribute( name ) {
  6328. return this.attributes[ name ] !== undefined;
  6329. }
  6330. addGroup( start, count, materialIndex = 0 ) {
  6331. this.groups.push( {
  6332. start: start,
  6333. count: count,
  6334. materialIndex: materialIndex
  6335. } );
  6336. }
  6337. clearGroups() {
  6338. this.groups = [];
  6339. }
  6340. setDrawRange( start, count ) {
  6341. this.drawRange.start = start;
  6342. this.drawRange.count = count;
  6343. }
  6344. applyMatrix4( matrix ) {
  6345. const position = this.attributes.position;
  6346. if ( position !== undefined ) {
  6347. position.applyMatrix4( matrix );
  6348. position.needsUpdate = true;
  6349. }
  6350. const normal = this.attributes.normal;
  6351. if ( normal !== undefined ) {
  6352. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6353. normal.applyNormalMatrix( normalMatrix );
  6354. normal.needsUpdate = true;
  6355. }
  6356. const tangent = this.attributes.tangent;
  6357. if ( tangent !== undefined ) {
  6358. tangent.transformDirection( matrix );
  6359. tangent.needsUpdate = true;
  6360. }
  6361. if ( this.boundingBox !== null ) {
  6362. this.computeBoundingBox();
  6363. }
  6364. if ( this.boundingSphere !== null ) {
  6365. this.computeBoundingSphere();
  6366. }
  6367. return this;
  6368. }
  6369. applyQuaternion( q ) {
  6370. _m1.makeRotationFromQuaternion( q );
  6371. this.applyMatrix4( _m1 );
  6372. return this;
  6373. }
  6374. rotateX( angle ) {
  6375. // rotate geometry around world x-axis
  6376. _m1.makeRotationX( angle );
  6377. this.applyMatrix4( _m1 );
  6378. return this;
  6379. }
  6380. rotateY( angle ) {
  6381. // rotate geometry around world y-axis
  6382. _m1.makeRotationY( angle );
  6383. this.applyMatrix4( _m1 );
  6384. return this;
  6385. }
  6386. rotateZ( angle ) {
  6387. // rotate geometry around world z-axis
  6388. _m1.makeRotationZ( angle );
  6389. this.applyMatrix4( _m1 );
  6390. return this;
  6391. }
  6392. translate( x, y, z ) {
  6393. // translate geometry
  6394. _m1.makeTranslation( x, y, z );
  6395. this.applyMatrix4( _m1 );
  6396. return this;
  6397. }
  6398. scale( x, y, z ) {
  6399. // scale geometry
  6400. _m1.makeScale( x, y, z );
  6401. this.applyMatrix4( _m1 );
  6402. return this;
  6403. }
  6404. lookAt( vector ) {
  6405. _obj.lookAt( vector );
  6406. _obj.updateMatrix();
  6407. this.applyMatrix4( _obj.matrix );
  6408. return this;
  6409. }
  6410. center() {
  6411. this.computeBoundingBox();
  6412. this.boundingBox.getCenter( _offset ).negate();
  6413. this.translate( _offset.x, _offset.y, _offset.z );
  6414. return this;
  6415. }
  6416. setFromPoints( points ) {
  6417. const position = [];
  6418. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6419. const point = points[ i ];
  6420. position.push( point.x, point.y, point.z || 0 );
  6421. }
  6422. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6423. return this;
  6424. }
  6425. computeBoundingBox() {
  6426. if ( this.boundingBox === null ) {
  6427. this.boundingBox = new Box3();
  6428. }
  6429. const position = this.attributes.position;
  6430. const morphAttributesPosition = this.morphAttributes.position;
  6431. if ( position && position.isGLBufferAttribute ) {
  6432. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6433. this.boundingBox.set(
  6434. new Vector3( - Infinity, - Infinity, - Infinity ),
  6435. new Vector3( + Infinity, + Infinity, + Infinity )
  6436. );
  6437. return;
  6438. }
  6439. if ( position !== undefined ) {
  6440. this.boundingBox.setFromBufferAttribute( position );
  6441. // process morph attributes if present
  6442. if ( morphAttributesPosition ) {
  6443. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6444. const morphAttribute = morphAttributesPosition[ i ];
  6445. _box$2.setFromBufferAttribute( morphAttribute );
  6446. if ( this.morphTargetsRelative ) {
  6447. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6448. this.boundingBox.expandByPoint( _vector$8 );
  6449. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6450. this.boundingBox.expandByPoint( _vector$8 );
  6451. } else {
  6452. this.boundingBox.expandByPoint( _box$2.min );
  6453. this.boundingBox.expandByPoint( _box$2.max );
  6454. }
  6455. }
  6456. }
  6457. } else {
  6458. this.boundingBox.makeEmpty();
  6459. }
  6460. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6461. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6462. }
  6463. }
  6464. computeBoundingSphere() {
  6465. if ( this.boundingSphere === null ) {
  6466. this.boundingSphere = new Sphere();
  6467. }
  6468. const position = this.attributes.position;
  6469. const morphAttributesPosition = this.morphAttributes.position;
  6470. if ( position && position.isGLBufferAttribute ) {
  6471. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6472. this.boundingSphere.set( new Vector3(), Infinity );
  6473. return;
  6474. }
  6475. if ( position ) {
  6476. // first, find the center of the bounding sphere
  6477. const center = this.boundingSphere.center;
  6478. _box$2.setFromBufferAttribute( position );
  6479. // process morph attributes if present
  6480. if ( morphAttributesPosition ) {
  6481. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6482. const morphAttribute = morphAttributesPosition[ i ];
  6483. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6484. if ( this.morphTargetsRelative ) {
  6485. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6486. _box$2.expandByPoint( _vector$8 );
  6487. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6488. _box$2.expandByPoint( _vector$8 );
  6489. } else {
  6490. _box$2.expandByPoint( _boxMorphTargets.min );
  6491. _box$2.expandByPoint( _boxMorphTargets.max );
  6492. }
  6493. }
  6494. }
  6495. _box$2.getCenter( center );
  6496. // second, try to find a boundingSphere with a radius smaller than the
  6497. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6498. let maxRadiusSq = 0;
  6499. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6500. _vector$8.fromBufferAttribute( position, i );
  6501. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6502. }
  6503. // process morph attributes if present
  6504. if ( morphAttributesPosition ) {
  6505. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6506. const morphAttribute = morphAttributesPosition[ i ];
  6507. const morphTargetsRelative = this.morphTargetsRelative;
  6508. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6509. _vector$8.fromBufferAttribute( morphAttribute, j );
  6510. if ( morphTargetsRelative ) {
  6511. _offset.fromBufferAttribute( position, j );
  6512. _vector$8.add( _offset );
  6513. }
  6514. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6515. }
  6516. }
  6517. }
  6518. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6519. if ( isNaN( this.boundingSphere.radius ) ) {
  6520. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6521. }
  6522. }
  6523. }
  6524. computeTangents() {
  6525. const index = this.index;
  6526. const attributes = this.attributes;
  6527. // based on http://www.terathon.com/code/tangent.html
  6528. // (per vertex tangents)
  6529. if ( index === null ||
  6530. attributes.position === undefined ||
  6531. attributes.normal === undefined ||
  6532. attributes.uv === undefined ) {
  6533. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6534. return;
  6535. }
  6536. const indices = index.array;
  6537. const positions = attributes.position.array;
  6538. const normals = attributes.normal.array;
  6539. const uvs = attributes.uv.array;
  6540. const nVertices = positions.length / 3;
  6541. if ( this.hasAttribute( 'tangent' ) === false ) {
  6542. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6543. }
  6544. const tangents = this.getAttribute( 'tangent' ).array;
  6545. const tan1 = [], tan2 = [];
  6546. for ( let i = 0; i < nVertices; i ++ ) {
  6547. tan1[ i ] = new Vector3();
  6548. tan2[ i ] = new Vector3();
  6549. }
  6550. const vA = new Vector3(),
  6551. vB = new Vector3(),
  6552. vC = new Vector3(),
  6553. uvA = new Vector2(),
  6554. uvB = new Vector2(),
  6555. uvC = new Vector2(),
  6556. sdir = new Vector3(),
  6557. tdir = new Vector3();
  6558. function handleTriangle( a, b, c ) {
  6559. vA.fromArray( positions, a * 3 );
  6560. vB.fromArray( positions, b * 3 );
  6561. vC.fromArray( positions, c * 3 );
  6562. uvA.fromArray( uvs, a * 2 );
  6563. uvB.fromArray( uvs, b * 2 );
  6564. uvC.fromArray( uvs, c * 2 );
  6565. vB.sub( vA );
  6566. vC.sub( vA );
  6567. uvB.sub( uvA );
  6568. uvC.sub( uvA );
  6569. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6570. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6571. if ( ! isFinite( r ) ) return;
  6572. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6573. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6574. tan1[ a ].add( sdir );
  6575. tan1[ b ].add( sdir );
  6576. tan1[ c ].add( sdir );
  6577. tan2[ a ].add( tdir );
  6578. tan2[ b ].add( tdir );
  6579. tan2[ c ].add( tdir );
  6580. }
  6581. let groups = this.groups;
  6582. if ( groups.length === 0 ) {
  6583. groups = [ {
  6584. start: 0,
  6585. count: indices.length
  6586. } ];
  6587. }
  6588. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6589. const group = groups[ i ];
  6590. const start = group.start;
  6591. const count = group.count;
  6592. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6593. handleTriangle(
  6594. indices[ j + 0 ],
  6595. indices[ j + 1 ],
  6596. indices[ j + 2 ]
  6597. );
  6598. }
  6599. }
  6600. const tmp = new Vector3(), tmp2 = new Vector3();
  6601. const n = new Vector3(), n2 = new Vector3();
  6602. function handleVertex( v ) {
  6603. n.fromArray( normals, v * 3 );
  6604. n2.copy( n );
  6605. const t = tan1[ v ];
  6606. // Gram-Schmidt orthogonalize
  6607. tmp.copy( t );
  6608. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6609. // Calculate handedness
  6610. tmp2.crossVectors( n2, t );
  6611. const test = tmp2.dot( tan2[ v ] );
  6612. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6613. tangents[ v * 4 ] = tmp.x;
  6614. tangents[ v * 4 + 1 ] = tmp.y;
  6615. tangents[ v * 4 + 2 ] = tmp.z;
  6616. tangents[ v * 4 + 3 ] = w;
  6617. }
  6618. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6619. const group = groups[ i ];
  6620. const start = group.start;
  6621. const count = group.count;
  6622. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6623. handleVertex( indices[ j + 0 ] );
  6624. handleVertex( indices[ j + 1 ] );
  6625. handleVertex( indices[ j + 2 ] );
  6626. }
  6627. }
  6628. }
  6629. computeVertexNormals() {
  6630. const index = this.index;
  6631. const positionAttribute = this.getAttribute( 'position' );
  6632. if ( positionAttribute !== undefined ) {
  6633. let normalAttribute = this.getAttribute( 'normal' );
  6634. if ( normalAttribute === undefined ) {
  6635. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6636. this.setAttribute( 'normal', normalAttribute );
  6637. } else {
  6638. // reset existing normals to zero
  6639. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6640. normalAttribute.setXYZ( i, 0, 0, 0 );
  6641. }
  6642. }
  6643. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6644. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6645. const cb = new Vector3(), ab = new Vector3();
  6646. // indexed elements
  6647. if ( index ) {
  6648. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6649. const vA = index.getX( i + 0 );
  6650. const vB = index.getX( i + 1 );
  6651. const vC = index.getX( i + 2 );
  6652. pA.fromBufferAttribute( positionAttribute, vA );
  6653. pB.fromBufferAttribute( positionAttribute, vB );
  6654. pC.fromBufferAttribute( positionAttribute, vC );
  6655. cb.subVectors( pC, pB );
  6656. ab.subVectors( pA, pB );
  6657. cb.cross( ab );
  6658. nA.fromBufferAttribute( normalAttribute, vA );
  6659. nB.fromBufferAttribute( normalAttribute, vB );
  6660. nC.fromBufferAttribute( normalAttribute, vC );
  6661. nA.add( cb );
  6662. nB.add( cb );
  6663. nC.add( cb );
  6664. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6665. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6666. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6667. }
  6668. } else {
  6669. // non-indexed elements (unconnected triangle soup)
  6670. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6671. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6672. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6673. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6674. cb.subVectors( pC, pB );
  6675. ab.subVectors( pA, pB );
  6676. cb.cross( ab );
  6677. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6678. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6679. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6680. }
  6681. }
  6682. this.normalizeNormals();
  6683. normalAttribute.needsUpdate = true;
  6684. }
  6685. }
  6686. normalizeNormals() {
  6687. const normals = this.attributes.normal;
  6688. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6689. _vector$8.fromBufferAttribute( normals, i );
  6690. _vector$8.normalize();
  6691. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6692. }
  6693. }
  6694. toNonIndexed() {
  6695. function convertBufferAttribute( attribute, indices ) {
  6696. const array = attribute.array;
  6697. const itemSize = attribute.itemSize;
  6698. const normalized = attribute.normalized;
  6699. const array2 = new array.constructor( indices.length * itemSize );
  6700. let index = 0, index2 = 0;
  6701. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6702. if ( attribute.isInterleavedBufferAttribute ) {
  6703. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6704. } else {
  6705. index = indices[ i ] * itemSize;
  6706. }
  6707. for ( let j = 0; j < itemSize; j ++ ) {
  6708. array2[ index2 ++ ] = array[ index ++ ];
  6709. }
  6710. }
  6711. return new BufferAttribute( array2, itemSize, normalized );
  6712. }
  6713. //
  6714. if ( this.index === null ) {
  6715. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6716. return this;
  6717. }
  6718. const geometry2 = new BufferGeometry();
  6719. const indices = this.index.array;
  6720. const attributes = this.attributes;
  6721. // attributes
  6722. for ( const name in attributes ) {
  6723. const attribute = attributes[ name ];
  6724. const newAttribute = convertBufferAttribute( attribute, indices );
  6725. geometry2.setAttribute( name, newAttribute );
  6726. }
  6727. // morph attributes
  6728. const morphAttributes = this.morphAttributes;
  6729. for ( const name in morphAttributes ) {
  6730. const morphArray = [];
  6731. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6732. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6733. const attribute = morphAttribute[ i ];
  6734. const newAttribute = convertBufferAttribute( attribute, indices );
  6735. morphArray.push( newAttribute );
  6736. }
  6737. geometry2.morphAttributes[ name ] = morphArray;
  6738. }
  6739. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6740. // groups
  6741. const groups = this.groups;
  6742. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6743. const group = groups[ i ];
  6744. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6745. }
  6746. return geometry2;
  6747. }
  6748. toJSON() {
  6749. const data = {
  6750. metadata: {
  6751. version: 4.6,
  6752. type: 'BufferGeometry',
  6753. generator: 'BufferGeometry.toJSON'
  6754. }
  6755. };
  6756. // standard BufferGeometry serialization
  6757. data.uuid = this.uuid;
  6758. data.type = this.type;
  6759. if ( this.name !== '' ) data.name = this.name;
  6760. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6761. if ( this.parameters !== undefined ) {
  6762. const parameters = this.parameters;
  6763. for ( const key in parameters ) {
  6764. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6765. }
  6766. return data;
  6767. }
  6768. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6769. data.data = { attributes: {} };
  6770. const index = this.index;
  6771. if ( index !== null ) {
  6772. data.data.index = {
  6773. type: index.array.constructor.name,
  6774. array: Array.prototype.slice.call( index.array )
  6775. };
  6776. }
  6777. const attributes = this.attributes;
  6778. for ( const key in attributes ) {
  6779. const attribute = attributes[ key ];
  6780. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6781. }
  6782. const morphAttributes = {};
  6783. let hasMorphAttributes = false;
  6784. for ( const key in this.morphAttributes ) {
  6785. const attributeArray = this.morphAttributes[ key ];
  6786. const array = [];
  6787. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6788. const attribute = attributeArray[ i ];
  6789. array.push( attribute.toJSON( data.data ) );
  6790. }
  6791. if ( array.length > 0 ) {
  6792. morphAttributes[ key ] = array;
  6793. hasMorphAttributes = true;
  6794. }
  6795. }
  6796. if ( hasMorphAttributes ) {
  6797. data.data.morphAttributes = morphAttributes;
  6798. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6799. }
  6800. const groups = this.groups;
  6801. if ( groups.length > 0 ) {
  6802. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6803. }
  6804. const boundingSphere = this.boundingSphere;
  6805. if ( boundingSphere !== null ) {
  6806. data.data.boundingSphere = {
  6807. center: boundingSphere.center.toArray(),
  6808. radius: boundingSphere.radius
  6809. };
  6810. }
  6811. return data;
  6812. }
  6813. clone() {
  6814. return new this.constructor().copy( this );
  6815. }
  6816. copy( source ) {
  6817. // reset
  6818. this.index = null;
  6819. this.attributes = {};
  6820. this.morphAttributes = {};
  6821. this.groups = [];
  6822. this.boundingBox = null;
  6823. this.boundingSphere = null;
  6824. // used for storing cloned, shared data
  6825. const data = {};
  6826. // name
  6827. this.name = source.name;
  6828. // index
  6829. const index = source.index;
  6830. if ( index !== null ) {
  6831. this.setIndex( index.clone( data ) );
  6832. }
  6833. // attributes
  6834. const attributes = source.attributes;
  6835. for ( const name in attributes ) {
  6836. const attribute = attributes[ name ];
  6837. this.setAttribute( name, attribute.clone( data ) );
  6838. }
  6839. // morph attributes
  6840. const morphAttributes = source.morphAttributes;
  6841. for ( const name in morphAttributes ) {
  6842. const array = [];
  6843. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6844. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6845. array.push( morphAttribute[ i ].clone( data ) );
  6846. }
  6847. this.morphAttributes[ name ] = array;
  6848. }
  6849. this.morphTargetsRelative = source.morphTargetsRelative;
  6850. // groups
  6851. const groups = source.groups;
  6852. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6853. const group = groups[ i ];
  6854. this.addGroup( group.start, group.count, group.materialIndex );
  6855. }
  6856. // bounding box
  6857. const boundingBox = source.boundingBox;
  6858. if ( boundingBox !== null ) {
  6859. this.boundingBox = boundingBox.clone();
  6860. }
  6861. // bounding sphere
  6862. const boundingSphere = source.boundingSphere;
  6863. if ( boundingSphere !== null ) {
  6864. this.boundingSphere = boundingSphere.clone();
  6865. }
  6866. // draw range
  6867. this.drawRange.start = source.drawRange.start;
  6868. this.drawRange.count = source.drawRange.count;
  6869. // user data
  6870. this.userData = source.userData;
  6871. return this;
  6872. }
  6873. dispose() {
  6874. this.dispatchEvent( { type: 'dispose' } );
  6875. }
  6876. }
  6877. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6878. const _ray$3 = /*@__PURE__*/ new Ray();
  6879. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6880. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6881. const _vA$1 = /*@__PURE__*/ new Vector3();
  6882. const _vB$1 = /*@__PURE__*/ new Vector3();
  6883. const _vC$1 = /*@__PURE__*/ new Vector3();
  6884. const _tempA = /*@__PURE__*/ new Vector3();
  6885. const _morphA = /*@__PURE__*/ new Vector3();
  6886. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6887. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6888. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6889. const _normalA = /*@__PURE__*/ new Vector3();
  6890. const _normalB = /*@__PURE__*/ new Vector3();
  6891. const _normalC = /*@__PURE__*/ new Vector3();
  6892. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6893. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6894. class Mesh extends Object3D {
  6895. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6896. super();
  6897. this.isMesh = true;
  6898. this.type = 'Mesh';
  6899. this.geometry = geometry;
  6900. this.material = material;
  6901. this.updateMorphTargets();
  6902. }
  6903. copy( source, recursive ) {
  6904. super.copy( source, recursive );
  6905. if ( source.morphTargetInfluences !== undefined ) {
  6906. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6907. }
  6908. if ( source.morphTargetDictionary !== undefined ) {
  6909. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6910. }
  6911. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6912. this.geometry = source.geometry;
  6913. return this;
  6914. }
  6915. updateMorphTargets() {
  6916. const geometry = this.geometry;
  6917. const morphAttributes = geometry.morphAttributes;
  6918. const keys = Object.keys( morphAttributes );
  6919. if ( keys.length > 0 ) {
  6920. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6921. if ( morphAttribute !== undefined ) {
  6922. this.morphTargetInfluences = [];
  6923. this.morphTargetDictionary = {};
  6924. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6925. const name = morphAttribute[ m ].name || String( m );
  6926. this.morphTargetInfluences.push( 0 );
  6927. this.morphTargetDictionary[ name ] = m;
  6928. }
  6929. }
  6930. }
  6931. }
  6932. getVertexPosition( index, target ) {
  6933. const geometry = this.geometry;
  6934. const position = geometry.attributes.position;
  6935. const morphPosition = geometry.morphAttributes.position;
  6936. const morphTargetsRelative = geometry.morphTargetsRelative;
  6937. target.fromBufferAttribute( position, index );
  6938. const morphInfluences = this.morphTargetInfluences;
  6939. if ( morphPosition && morphInfluences ) {
  6940. _morphA.set( 0, 0, 0 );
  6941. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6942. const influence = morphInfluences[ i ];
  6943. const morphAttribute = morphPosition[ i ];
  6944. if ( influence === 0 ) continue;
  6945. _tempA.fromBufferAttribute( morphAttribute, index );
  6946. if ( morphTargetsRelative ) {
  6947. _morphA.addScaledVector( _tempA, influence );
  6948. } else {
  6949. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6950. }
  6951. }
  6952. target.add( _morphA );
  6953. }
  6954. return target;
  6955. }
  6956. raycast( raycaster, intersects ) {
  6957. const geometry = this.geometry;
  6958. const material = this.material;
  6959. const matrixWorld = this.matrixWorld;
  6960. if ( material === undefined ) return;
  6961. // test with bounding sphere in world space
  6962. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6963. _sphere$6.copy( geometry.boundingSphere );
  6964. _sphere$6.applyMatrix4( matrixWorld );
  6965. // check distance from ray origin to bounding sphere
  6966. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6967. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6968. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6969. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6970. }
  6971. // convert ray to local space of mesh
  6972. _inverseMatrix$3.copy( matrixWorld ).invert();
  6973. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6974. // test with bounding box in local space
  6975. if ( geometry.boundingBox !== null ) {
  6976. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6977. }
  6978. // test for intersections with geometry
  6979. this._computeIntersections( raycaster, intersects, _ray$3 );
  6980. }
  6981. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6982. let intersection;
  6983. const geometry = this.geometry;
  6984. const material = this.material;
  6985. const index = geometry.index;
  6986. const position = geometry.attributes.position;
  6987. const uv = geometry.attributes.uv;
  6988. const uv1 = geometry.attributes.uv1;
  6989. const normal = geometry.attributes.normal;
  6990. const groups = geometry.groups;
  6991. const drawRange = geometry.drawRange;
  6992. if ( index !== null ) {
  6993. // indexed buffer geometry
  6994. if ( Array.isArray( material ) ) {
  6995. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6996. const group = groups[ i ];
  6997. const groupMaterial = material[ group.materialIndex ];
  6998. const start = Math.max( group.start, drawRange.start );
  6999. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7000. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7001. const a = index.getX( j );
  7002. const b = index.getX( j + 1 );
  7003. const c = index.getX( j + 2 );
  7004. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7005. if ( intersection ) {
  7006. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7007. intersection.face.materialIndex = group.materialIndex;
  7008. intersects.push( intersection );
  7009. }
  7010. }
  7011. }
  7012. } else {
  7013. const start = Math.max( 0, drawRange.start );
  7014. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7015. for ( let i = start, il = end; i < il; i += 3 ) {
  7016. const a = index.getX( i );
  7017. const b = index.getX( i + 1 );
  7018. const c = index.getX( i + 2 );
  7019. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7020. if ( intersection ) {
  7021. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7022. intersects.push( intersection );
  7023. }
  7024. }
  7025. }
  7026. } else if ( position !== undefined ) {
  7027. // non-indexed buffer geometry
  7028. if ( Array.isArray( material ) ) {
  7029. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7030. const group = groups[ i ];
  7031. const groupMaterial = material[ group.materialIndex ];
  7032. const start = Math.max( group.start, drawRange.start );
  7033. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7034. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7035. const a = j;
  7036. const b = j + 1;
  7037. const c = j + 2;
  7038. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7039. if ( intersection ) {
  7040. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7041. intersection.face.materialIndex = group.materialIndex;
  7042. intersects.push( intersection );
  7043. }
  7044. }
  7045. }
  7046. } else {
  7047. const start = Math.max( 0, drawRange.start );
  7048. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7049. for ( let i = start, il = end; i < il; i += 3 ) {
  7050. const a = i;
  7051. const b = i + 1;
  7052. const c = i + 2;
  7053. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7054. if ( intersection ) {
  7055. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7056. intersects.push( intersection );
  7057. }
  7058. }
  7059. }
  7060. }
  7061. }
  7062. }
  7063. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7064. let intersect;
  7065. if ( material.side === BackSide ) {
  7066. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7067. } else {
  7068. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7069. }
  7070. if ( intersect === null ) return null;
  7071. _intersectionPointWorld.copy( point );
  7072. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7073. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7074. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7075. return {
  7076. distance: distance,
  7077. point: _intersectionPointWorld.clone(),
  7078. object: object
  7079. };
  7080. }
  7081. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7082. object.getVertexPosition( a, _vA$1 );
  7083. object.getVertexPosition( b, _vB$1 );
  7084. object.getVertexPosition( c, _vC$1 );
  7085. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7086. if ( intersection ) {
  7087. if ( uv ) {
  7088. _uvA$1.fromBufferAttribute( uv, a );
  7089. _uvB$1.fromBufferAttribute( uv, b );
  7090. _uvC$1.fromBufferAttribute( uv, c );
  7091. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7092. }
  7093. if ( uv1 ) {
  7094. _uvA$1.fromBufferAttribute( uv1, a );
  7095. _uvB$1.fromBufferAttribute( uv1, b );
  7096. _uvC$1.fromBufferAttribute( uv1, c );
  7097. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7098. intersection.uv2 = intersection.uv1; // @deprecated, r152
  7099. }
  7100. if ( normal ) {
  7101. _normalA.fromBufferAttribute( normal, a );
  7102. _normalB.fromBufferAttribute( normal, b );
  7103. _normalC.fromBufferAttribute( normal, c );
  7104. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7105. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7106. intersection.normal.multiplyScalar( - 1 );
  7107. }
  7108. }
  7109. const face = {
  7110. a: a,
  7111. b: b,
  7112. c: c,
  7113. normal: new Vector3(),
  7114. materialIndex: 0
  7115. };
  7116. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7117. intersection.face = face;
  7118. }
  7119. return intersection;
  7120. }
  7121. class BoxGeometry extends BufferGeometry {
  7122. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7123. super();
  7124. this.type = 'BoxGeometry';
  7125. this.parameters = {
  7126. width: width,
  7127. height: height,
  7128. depth: depth,
  7129. widthSegments: widthSegments,
  7130. heightSegments: heightSegments,
  7131. depthSegments: depthSegments
  7132. };
  7133. const scope = this;
  7134. // segments
  7135. widthSegments = Math.floor( widthSegments );
  7136. heightSegments = Math.floor( heightSegments );
  7137. depthSegments = Math.floor( depthSegments );
  7138. // buffers
  7139. const indices = [];
  7140. const vertices = [];
  7141. const normals = [];
  7142. const uvs = [];
  7143. // helper variables
  7144. let numberOfVertices = 0;
  7145. let groupStart = 0;
  7146. // build each side of the box geometry
  7147. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7148. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7149. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7150. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7151. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7152. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7153. // build geometry
  7154. this.setIndex( indices );
  7155. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7156. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7157. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7158. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7159. const segmentWidth = width / gridX;
  7160. const segmentHeight = height / gridY;
  7161. const widthHalf = width / 2;
  7162. const heightHalf = height / 2;
  7163. const depthHalf = depth / 2;
  7164. const gridX1 = gridX + 1;
  7165. const gridY1 = gridY + 1;
  7166. let vertexCounter = 0;
  7167. let groupCount = 0;
  7168. const vector = new Vector3();
  7169. // generate vertices, normals and uvs
  7170. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7171. const y = iy * segmentHeight - heightHalf;
  7172. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7173. const x = ix * segmentWidth - widthHalf;
  7174. // set values to correct vector component
  7175. vector[ u ] = x * udir;
  7176. vector[ v ] = y * vdir;
  7177. vector[ w ] = depthHalf;
  7178. // now apply vector to vertex buffer
  7179. vertices.push( vector.x, vector.y, vector.z );
  7180. // set values to correct vector component
  7181. vector[ u ] = 0;
  7182. vector[ v ] = 0;
  7183. vector[ w ] = depth > 0 ? 1 : - 1;
  7184. // now apply vector to normal buffer
  7185. normals.push( vector.x, vector.y, vector.z );
  7186. // uvs
  7187. uvs.push( ix / gridX );
  7188. uvs.push( 1 - ( iy / gridY ) );
  7189. // counters
  7190. vertexCounter += 1;
  7191. }
  7192. }
  7193. // indices
  7194. // 1. you need three indices to draw a single face
  7195. // 2. a single segment consists of two faces
  7196. // 3. so we need to generate six (2*3) indices per segment
  7197. for ( let iy = 0; iy < gridY; iy ++ ) {
  7198. for ( let ix = 0; ix < gridX; ix ++ ) {
  7199. const a = numberOfVertices + ix + gridX1 * iy;
  7200. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7201. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7202. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7203. // faces
  7204. indices.push( a, b, d );
  7205. indices.push( b, c, d );
  7206. // increase counter
  7207. groupCount += 6;
  7208. }
  7209. }
  7210. // add a group to the geometry. this will ensure multi material support
  7211. scope.addGroup( groupStart, groupCount, materialIndex );
  7212. // calculate new start value for groups
  7213. groupStart += groupCount;
  7214. // update total number of vertices
  7215. numberOfVertices += vertexCounter;
  7216. }
  7217. }
  7218. copy( source ) {
  7219. super.copy( source );
  7220. this.parameters = Object.assign( {}, source.parameters );
  7221. return this;
  7222. }
  7223. static fromJSON( data ) {
  7224. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7225. }
  7226. }
  7227. /**
  7228. * Uniform Utilities
  7229. */
  7230. function cloneUniforms( src ) {
  7231. const dst = {};
  7232. for ( const u in src ) {
  7233. dst[ u ] = {};
  7234. for ( const p in src[ u ] ) {
  7235. const property = src[ u ][ p ];
  7236. if ( property && ( property.isColor ||
  7237. property.isMatrix3 || property.isMatrix4 ||
  7238. property.isVector2 || property.isVector3 || property.isVector4 ||
  7239. property.isTexture || property.isQuaternion ) ) {
  7240. if ( property.isRenderTargetTexture ) {
  7241. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7242. dst[ u ][ p ] = null;
  7243. } else {
  7244. dst[ u ][ p ] = property.clone();
  7245. }
  7246. } else if ( Array.isArray( property ) ) {
  7247. dst[ u ][ p ] = property.slice();
  7248. } else {
  7249. dst[ u ][ p ] = property;
  7250. }
  7251. }
  7252. }
  7253. return dst;
  7254. }
  7255. function mergeUniforms( uniforms ) {
  7256. const merged = {};
  7257. for ( let u = 0; u < uniforms.length; u ++ ) {
  7258. const tmp = cloneUniforms( uniforms[ u ] );
  7259. for ( const p in tmp ) {
  7260. merged[ p ] = tmp[ p ];
  7261. }
  7262. }
  7263. return merged;
  7264. }
  7265. function cloneUniformsGroups( src ) {
  7266. const dst = [];
  7267. for ( let u = 0; u < src.length; u ++ ) {
  7268. dst.push( src[ u ].clone() );
  7269. }
  7270. return dst;
  7271. }
  7272. function getUnlitUniformColorSpace( renderer ) {
  7273. if ( renderer.getRenderTarget() === null ) {
  7274. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7275. return renderer.outputColorSpace;
  7276. }
  7277. return ColorManagement.workingColorSpace;
  7278. }
  7279. // Legacy
  7280. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7281. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7282. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7283. class ShaderMaterial extends Material {
  7284. constructor( parameters ) {
  7285. super();
  7286. this.isShaderMaterial = true;
  7287. this.type = 'ShaderMaterial';
  7288. this.defines = {};
  7289. this.uniforms = {};
  7290. this.uniformsGroups = [];
  7291. this.vertexShader = default_vertex;
  7292. this.fragmentShader = default_fragment;
  7293. this.linewidth = 1;
  7294. this.wireframe = false;
  7295. this.wireframeLinewidth = 1;
  7296. this.fog = false; // set to use scene fog
  7297. this.lights = false; // set to use scene lights
  7298. this.clipping = false; // set to use user-defined clipping planes
  7299. this.forceSinglePass = true;
  7300. this.extensions = {
  7301. derivatives: false, // set to use derivatives
  7302. fragDepth: false, // set to use fragment depth values
  7303. drawBuffers: false, // set to use draw buffers
  7304. shaderTextureLOD: false, // set to use shader texture LOD
  7305. clipCullDistance: false // set to use vertex shader clipping
  7306. };
  7307. // When rendered geometry doesn't include these attributes but the material does,
  7308. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7309. this.defaultAttributeValues = {
  7310. 'color': [ 1, 1, 1 ],
  7311. 'uv': [ 0, 0 ],
  7312. 'uv1': [ 0, 0 ]
  7313. };
  7314. this.index0AttributeName = undefined;
  7315. this.uniformsNeedUpdate = false;
  7316. this.glslVersion = null;
  7317. if ( parameters !== undefined ) {
  7318. this.setValues( parameters );
  7319. }
  7320. }
  7321. copy( source ) {
  7322. super.copy( source );
  7323. this.fragmentShader = source.fragmentShader;
  7324. this.vertexShader = source.vertexShader;
  7325. this.uniforms = cloneUniforms( source.uniforms );
  7326. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7327. this.defines = Object.assign( {}, source.defines );
  7328. this.wireframe = source.wireframe;
  7329. this.wireframeLinewidth = source.wireframeLinewidth;
  7330. this.fog = source.fog;
  7331. this.lights = source.lights;
  7332. this.clipping = source.clipping;
  7333. this.extensions = Object.assign( {}, source.extensions );
  7334. this.glslVersion = source.glslVersion;
  7335. return this;
  7336. }
  7337. toJSON( meta ) {
  7338. const data = super.toJSON( meta );
  7339. data.glslVersion = this.glslVersion;
  7340. data.uniforms = {};
  7341. for ( const name in this.uniforms ) {
  7342. const uniform = this.uniforms[ name ];
  7343. const value = uniform.value;
  7344. if ( value && value.isTexture ) {
  7345. data.uniforms[ name ] = {
  7346. type: 't',
  7347. value: value.toJSON( meta ).uuid
  7348. };
  7349. } else if ( value && value.isColor ) {
  7350. data.uniforms[ name ] = {
  7351. type: 'c',
  7352. value: value.getHex()
  7353. };
  7354. } else if ( value && value.isVector2 ) {
  7355. data.uniforms[ name ] = {
  7356. type: 'v2',
  7357. value: value.toArray()
  7358. };
  7359. } else if ( value && value.isVector3 ) {
  7360. data.uniforms[ name ] = {
  7361. type: 'v3',
  7362. value: value.toArray()
  7363. };
  7364. } else if ( value && value.isVector4 ) {
  7365. data.uniforms[ name ] = {
  7366. type: 'v4',
  7367. value: value.toArray()
  7368. };
  7369. } else if ( value && value.isMatrix3 ) {
  7370. data.uniforms[ name ] = {
  7371. type: 'm3',
  7372. value: value.toArray()
  7373. };
  7374. } else if ( value && value.isMatrix4 ) {
  7375. data.uniforms[ name ] = {
  7376. type: 'm4',
  7377. value: value.toArray()
  7378. };
  7379. } else {
  7380. data.uniforms[ name ] = {
  7381. value: value
  7382. };
  7383. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7384. }
  7385. }
  7386. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7387. data.vertexShader = this.vertexShader;
  7388. data.fragmentShader = this.fragmentShader;
  7389. data.lights = this.lights;
  7390. data.clipping = this.clipping;
  7391. const extensions = {};
  7392. for ( const key in this.extensions ) {
  7393. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7394. }
  7395. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7396. return data;
  7397. }
  7398. }
  7399. class Camera extends Object3D {
  7400. constructor() {
  7401. super();
  7402. this.isCamera = true;
  7403. this.type = 'Camera';
  7404. this.matrixWorldInverse = new Matrix4();
  7405. this.projectionMatrix = new Matrix4();
  7406. this.projectionMatrixInverse = new Matrix4();
  7407. this.coordinateSystem = WebGLCoordinateSystem;
  7408. }
  7409. copy( source, recursive ) {
  7410. super.copy( source, recursive );
  7411. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7412. this.projectionMatrix.copy( source.projectionMatrix );
  7413. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7414. this.coordinateSystem = source.coordinateSystem;
  7415. return this;
  7416. }
  7417. getWorldDirection( target ) {
  7418. return super.getWorldDirection( target ).negate();
  7419. }
  7420. updateMatrixWorld( force ) {
  7421. super.updateMatrixWorld( force );
  7422. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7423. }
  7424. updateWorldMatrix( updateParents, updateChildren ) {
  7425. super.updateWorldMatrix( updateParents, updateChildren );
  7426. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7427. }
  7428. clone() {
  7429. return new this.constructor().copy( this );
  7430. }
  7431. }
  7432. class PerspectiveCamera extends Camera {
  7433. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7434. super();
  7435. this.isPerspectiveCamera = true;
  7436. this.type = 'PerspectiveCamera';
  7437. this.fov = fov;
  7438. this.zoom = 1;
  7439. this.near = near;
  7440. this.far = far;
  7441. this.focus = 10;
  7442. this.aspect = aspect;
  7443. this.view = null;
  7444. this.filmGauge = 35; // width of the film (default in millimeters)
  7445. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7446. this.updateProjectionMatrix();
  7447. }
  7448. copy( source, recursive ) {
  7449. super.copy( source, recursive );
  7450. this.fov = source.fov;
  7451. this.zoom = source.zoom;
  7452. this.near = source.near;
  7453. this.far = source.far;
  7454. this.focus = source.focus;
  7455. this.aspect = source.aspect;
  7456. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7457. this.filmGauge = source.filmGauge;
  7458. this.filmOffset = source.filmOffset;
  7459. return this;
  7460. }
  7461. /**
  7462. * Sets the FOV by focal length in respect to the current .filmGauge.
  7463. *
  7464. * The default film gauge is 35, so that the focal length can be specified for
  7465. * a 35mm (full frame) camera.
  7466. *
  7467. * Values for focal length and film gauge must have the same unit.
  7468. */
  7469. setFocalLength( focalLength ) {
  7470. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7471. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7472. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7473. this.updateProjectionMatrix();
  7474. }
  7475. /**
  7476. * Calculates the focal length from the current .fov and .filmGauge.
  7477. */
  7478. getFocalLength() {
  7479. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7480. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7481. }
  7482. getEffectiveFOV() {
  7483. return RAD2DEG * 2 * Math.atan(
  7484. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7485. }
  7486. getFilmWidth() {
  7487. // film not completely covered in portrait format (aspect < 1)
  7488. return this.filmGauge * Math.min( this.aspect, 1 );
  7489. }
  7490. getFilmHeight() {
  7491. // film not completely covered in landscape format (aspect > 1)
  7492. return this.filmGauge / Math.max( this.aspect, 1 );
  7493. }
  7494. /**
  7495. * Sets an offset in a larger frustum. This is useful for multi-window or
  7496. * multi-monitor/multi-machine setups.
  7497. *
  7498. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7499. * the monitors are in grid like this
  7500. *
  7501. * +---+---+---+
  7502. * | A | B | C |
  7503. * +---+---+---+
  7504. * | D | E | F |
  7505. * +---+---+---+
  7506. *
  7507. * then for each monitor you would call it like this
  7508. *
  7509. * const w = 1920;
  7510. * const h = 1080;
  7511. * const fullWidth = w * 3;
  7512. * const fullHeight = h * 2;
  7513. *
  7514. * --A--
  7515. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7516. * --B--
  7517. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7518. * --C--
  7519. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7520. * --D--
  7521. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7522. * --E--
  7523. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7524. * --F--
  7525. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7526. *
  7527. * Note there is no reason monitors have to be the same size or in a grid.
  7528. */
  7529. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7530. this.aspect = fullWidth / fullHeight;
  7531. if ( this.view === null ) {
  7532. this.view = {
  7533. enabled: true,
  7534. fullWidth: 1,
  7535. fullHeight: 1,
  7536. offsetX: 0,
  7537. offsetY: 0,
  7538. width: 1,
  7539. height: 1
  7540. };
  7541. }
  7542. this.view.enabled = true;
  7543. this.view.fullWidth = fullWidth;
  7544. this.view.fullHeight = fullHeight;
  7545. this.view.offsetX = x;
  7546. this.view.offsetY = y;
  7547. this.view.width = width;
  7548. this.view.height = height;
  7549. this.updateProjectionMatrix();
  7550. }
  7551. clearViewOffset() {
  7552. if ( this.view !== null ) {
  7553. this.view.enabled = false;
  7554. }
  7555. this.updateProjectionMatrix();
  7556. }
  7557. updateProjectionMatrix() {
  7558. const near = this.near;
  7559. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7560. let height = 2 * top;
  7561. let width = this.aspect * height;
  7562. let left = - 0.5 * width;
  7563. const view = this.view;
  7564. if ( this.view !== null && this.view.enabled ) {
  7565. const fullWidth = view.fullWidth,
  7566. fullHeight = view.fullHeight;
  7567. left += view.offsetX * width / fullWidth;
  7568. top -= view.offsetY * height / fullHeight;
  7569. width *= view.width / fullWidth;
  7570. height *= view.height / fullHeight;
  7571. }
  7572. const skew = this.filmOffset;
  7573. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7574. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7575. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7576. }
  7577. toJSON( meta ) {
  7578. const data = super.toJSON( meta );
  7579. data.object.fov = this.fov;
  7580. data.object.zoom = this.zoom;
  7581. data.object.near = this.near;
  7582. data.object.far = this.far;
  7583. data.object.focus = this.focus;
  7584. data.object.aspect = this.aspect;
  7585. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7586. data.object.filmGauge = this.filmGauge;
  7587. data.object.filmOffset = this.filmOffset;
  7588. return data;
  7589. }
  7590. }
  7591. const fov = - 90; // negative fov is not an error
  7592. const aspect = 1;
  7593. class CubeCamera extends Object3D {
  7594. constructor( near, far, renderTarget ) {
  7595. super();
  7596. this.type = 'CubeCamera';
  7597. this.renderTarget = renderTarget;
  7598. this.coordinateSystem = null;
  7599. this.activeMipmapLevel = 0;
  7600. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7601. cameraPX.layers = this.layers;
  7602. this.add( cameraPX );
  7603. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7604. cameraNX.layers = this.layers;
  7605. this.add( cameraNX );
  7606. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7607. cameraPY.layers = this.layers;
  7608. this.add( cameraPY );
  7609. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7610. cameraNY.layers = this.layers;
  7611. this.add( cameraNY );
  7612. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7613. cameraPZ.layers = this.layers;
  7614. this.add( cameraPZ );
  7615. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7616. cameraNZ.layers = this.layers;
  7617. this.add( cameraNZ );
  7618. }
  7619. updateCoordinateSystem() {
  7620. const coordinateSystem = this.coordinateSystem;
  7621. const cameras = this.children.concat();
  7622. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7623. for ( const camera of cameras ) this.remove( camera );
  7624. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7625. cameraPX.up.set( 0, 1, 0 );
  7626. cameraPX.lookAt( 1, 0, 0 );
  7627. cameraNX.up.set( 0, 1, 0 );
  7628. cameraNX.lookAt( - 1, 0, 0 );
  7629. cameraPY.up.set( 0, 0, - 1 );
  7630. cameraPY.lookAt( 0, 1, 0 );
  7631. cameraNY.up.set( 0, 0, 1 );
  7632. cameraNY.lookAt( 0, - 1, 0 );
  7633. cameraPZ.up.set( 0, 1, 0 );
  7634. cameraPZ.lookAt( 0, 0, 1 );
  7635. cameraNZ.up.set( 0, 1, 0 );
  7636. cameraNZ.lookAt( 0, 0, - 1 );
  7637. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7638. cameraPX.up.set( 0, - 1, 0 );
  7639. cameraPX.lookAt( - 1, 0, 0 );
  7640. cameraNX.up.set( 0, - 1, 0 );
  7641. cameraNX.lookAt( 1, 0, 0 );
  7642. cameraPY.up.set( 0, 0, 1 );
  7643. cameraPY.lookAt( 0, 1, 0 );
  7644. cameraNY.up.set( 0, 0, - 1 );
  7645. cameraNY.lookAt( 0, - 1, 0 );
  7646. cameraPZ.up.set( 0, - 1, 0 );
  7647. cameraPZ.lookAt( 0, 0, 1 );
  7648. cameraNZ.up.set( 0, - 1, 0 );
  7649. cameraNZ.lookAt( 0, 0, - 1 );
  7650. } else {
  7651. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7652. }
  7653. for ( const camera of cameras ) {
  7654. this.add( camera );
  7655. camera.updateMatrixWorld();
  7656. }
  7657. }
  7658. update( renderer, scene ) {
  7659. if ( this.parent === null ) this.updateMatrixWorld();
  7660. const { renderTarget, activeMipmapLevel } = this;
  7661. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7662. this.coordinateSystem = renderer.coordinateSystem;
  7663. this.updateCoordinateSystem();
  7664. }
  7665. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7666. const currentRenderTarget = renderer.getRenderTarget();
  7667. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7668. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7669. const currentXrEnabled = renderer.xr.enabled;
  7670. renderer.xr.enabled = false;
  7671. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7672. renderTarget.texture.generateMipmaps = false;
  7673. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7674. renderer.render( scene, cameraPX );
  7675. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7676. renderer.render( scene, cameraNX );
  7677. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7678. renderer.render( scene, cameraPY );
  7679. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7680. renderer.render( scene, cameraNY );
  7681. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7682. renderer.render( scene, cameraPZ );
  7683. // mipmaps are generated during the last call of render()
  7684. // at this point, all sides of the cube render target are defined
  7685. renderTarget.texture.generateMipmaps = generateMipmaps;
  7686. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7687. renderer.render( scene, cameraNZ );
  7688. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7689. renderer.xr.enabled = currentXrEnabled;
  7690. renderTarget.texture.needsPMREMUpdate = true;
  7691. }
  7692. }
  7693. class CubeTexture extends Texture {
  7694. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7695. images = images !== undefined ? images : [];
  7696. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7697. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7698. this.isCubeTexture = true;
  7699. this.flipY = false;
  7700. }
  7701. get images() {
  7702. return this.image;
  7703. }
  7704. set images( value ) {
  7705. this.image = value;
  7706. }
  7707. }
  7708. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7709. constructor( size = 1, options = {} ) {
  7710. super( size, size, options );
  7711. this.isWebGLCubeRenderTarget = true;
  7712. const image = { width: size, height: size, depth: 1 };
  7713. const images = [ image, image, image, image, image, image ];
  7714. if ( options.encoding !== undefined ) {
  7715. // @deprecated, r152
  7716. warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  7717. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  7718. }
  7719. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7720. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7721. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7722. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7723. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7724. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7725. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7726. this.texture.isRenderTargetTexture = true;
  7727. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7728. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7729. }
  7730. fromEquirectangularTexture( renderer, texture ) {
  7731. this.texture.type = texture.type;
  7732. this.texture.colorSpace = texture.colorSpace;
  7733. this.texture.generateMipmaps = texture.generateMipmaps;
  7734. this.texture.minFilter = texture.minFilter;
  7735. this.texture.magFilter = texture.magFilter;
  7736. const shader = {
  7737. uniforms: {
  7738. tEquirect: { value: null },
  7739. },
  7740. vertexShader: /* glsl */`
  7741. varying vec3 vWorldDirection;
  7742. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7743. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7744. }
  7745. void main() {
  7746. vWorldDirection = transformDirection( position, modelMatrix );
  7747. #include <begin_vertex>
  7748. #include <project_vertex>
  7749. }
  7750. `,
  7751. fragmentShader: /* glsl */`
  7752. uniform sampler2D tEquirect;
  7753. varying vec3 vWorldDirection;
  7754. #include <common>
  7755. void main() {
  7756. vec3 direction = normalize( vWorldDirection );
  7757. vec2 sampleUV = equirectUv( direction );
  7758. gl_FragColor = texture2D( tEquirect, sampleUV );
  7759. }
  7760. `
  7761. };
  7762. const geometry = new BoxGeometry( 5, 5, 5 );
  7763. const material = new ShaderMaterial( {
  7764. name: 'CubemapFromEquirect',
  7765. uniforms: cloneUniforms( shader.uniforms ),
  7766. vertexShader: shader.vertexShader,
  7767. fragmentShader: shader.fragmentShader,
  7768. side: BackSide,
  7769. blending: NoBlending
  7770. } );
  7771. material.uniforms.tEquirect.value = texture;
  7772. const mesh = new Mesh( geometry, material );
  7773. const currentMinFilter = texture.minFilter;
  7774. // Avoid blurred poles
  7775. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7776. const camera = new CubeCamera( 1, 10, this );
  7777. camera.update( renderer, mesh );
  7778. texture.minFilter = currentMinFilter;
  7779. mesh.geometry.dispose();
  7780. mesh.material.dispose();
  7781. return this;
  7782. }
  7783. clear( renderer, color, depth, stencil ) {
  7784. const currentRenderTarget = renderer.getRenderTarget();
  7785. for ( let i = 0; i < 6; i ++ ) {
  7786. renderer.setRenderTarget( this, i );
  7787. renderer.clear( color, depth, stencil );
  7788. }
  7789. renderer.setRenderTarget( currentRenderTarget );
  7790. }
  7791. }
  7792. const _vector1 = /*@__PURE__*/ new Vector3();
  7793. const _vector2 = /*@__PURE__*/ new Vector3();
  7794. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7795. class Plane {
  7796. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7797. this.isPlane = true;
  7798. // normal is assumed to be normalized
  7799. this.normal = normal;
  7800. this.constant = constant;
  7801. }
  7802. set( normal, constant ) {
  7803. this.normal.copy( normal );
  7804. this.constant = constant;
  7805. return this;
  7806. }
  7807. setComponents( x, y, z, w ) {
  7808. this.normal.set( x, y, z );
  7809. this.constant = w;
  7810. return this;
  7811. }
  7812. setFromNormalAndCoplanarPoint( normal, point ) {
  7813. this.normal.copy( normal );
  7814. this.constant = - point.dot( this.normal );
  7815. return this;
  7816. }
  7817. setFromCoplanarPoints( a, b, c ) {
  7818. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7819. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7820. this.setFromNormalAndCoplanarPoint( normal, a );
  7821. return this;
  7822. }
  7823. copy( plane ) {
  7824. this.normal.copy( plane.normal );
  7825. this.constant = plane.constant;
  7826. return this;
  7827. }
  7828. normalize() {
  7829. // Note: will lead to a divide by zero if the plane is invalid.
  7830. const inverseNormalLength = 1.0 / this.normal.length();
  7831. this.normal.multiplyScalar( inverseNormalLength );
  7832. this.constant *= inverseNormalLength;
  7833. return this;
  7834. }
  7835. negate() {
  7836. this.constant *= - 1;
  7837. this.normal.negate();
  7838. return this;
  7839. }
  7840. distanceToPoint( point ) {
  7841. return this.normal.dot( point ) + this.constant;
  7842. }
  7843. distanceToSphere( sphere ) {
  7844. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7845. }
  7846. projectPoint( point, target ) {
  7847. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7848. }
  7849. intersectLine( line, target ) {
  7850. const direction = line.delta( _vector1 );
  7851. const denominator = this.normal.dot( direction );
  7852. if ( denominator === 0 ) {
  7853. // line is coplanar, return origin
  7854. if ( this.distanceToPoint( line.start ) === 0 ) {
  7855. return target.copy( line.start );
  7856. }
  7857. // Unsure if this is the correct method to handle this case.
  7858. return null;
  7859. }
  7860. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7861. if ( t < 0 || t > 1 ) {
  7862. return null;
  7863. }
  7864. return target.copy( line.start ).addScaledVector( direction, t );
  7865. }
  7866. intersectsLine( line ) {
  7867. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7868. const startSign = this.distanceToPoint( line.start );
  7869. const endSign = this.distanceToPoint( line.end );
  7870. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7871. }
  7872. intersectsBox( box ) {
  7873. return box.intersectsPlane( this );
  7874. }
  7875. intersectsSphere( sphere ) {
  7876. return sphere.intersectsPlane( this );
  7877. }
  7878. coplanarPoint( target ) {
  7879. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7880. }
  7881. applyMatrix4( matrix, optionalNormalMatrix ) {
  7882. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7883. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7884. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7885. this.constant = - referencePoint.dot( normal );
  7886. return this;
  7887. }
  7888. translate( offset ) {
  7889. this.constant -= offset.dot( this.normal );
  7890. return this;
  7891. }
  7892. equals( plane ) {
  7893. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7894. }
  7895. clone() {
  7896. return new this.constructor().copy( this );
  7897. }
  7898. }
  7899. const _sphere$5 = /*@__PURE__*/ new Sphere();
  7900. const _vector$7 = /*@__PURE__*/ new Vector3();
  7901. class Frustum {
  7902. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7903. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7904. }
  7905. set( p0, p1, p2, p3, p4, p5 ) {
  7906. const planes = this.planes;
  7907. planes[ 0 ].copy( p0 );
  7908. planes[ 1 ].copy( p1 );
  7909. planes[ 2 ].copy( p2 );
  7910. planes[ 3 ].copy( p3 );
  7911. planes[ 4 ].copy( p4 );
  7912. planes[ 5 ].copy( p5 );
  7913. return this;
  7914. }
  7915. copy( frustum ) {
  7916. const planes = this.planes;
  7917. for ( let i = 0; i < 6; i ++ ) {
  7918. planes[ i ].copy( frustum.planes[ i ] );
  7919. }
  7920. return this;
  7921. }
  7922. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7923. const planes = this.planes;
  7924. const me = m.elements;
  7925. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7926. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7927. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7928. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7929. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7930. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7931. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7932. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7933. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7934. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7935. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7936. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7937. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7938. } else {
  7939. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7940. }
  7941. return this;
  7942. }
  7943. intersectsObject( object ) {
  7944. if ( object.boundingSphere !== undefined ) {
  7945. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7946. _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7947. } else {
  7948. const geometry = object.geometry;
  7949. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7950. _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7951. }
  7952. return this.intersectsSphere( _sphere$5 );
  7953. }
  7954. intersectsSprite( sprite ) {
  7955. _sphere$5.center.set( 0, 0, 0 );
  7956. _sphere$5.radius = 0.7071067811865476;
  7957. _sphere$5.applyMatrix4( sprite.matrixWorld );
  7958. return this.intersectsSphere( _sphere$5 );
  7959. }
  7960. intersectsSphere( sphere ) {
  7961. const planes = this.planes;
  7962. const center = sphere.center;
  7963. const negRadius = - sphere.radius;
  7964. for ( let i = 0; i < 6; i ++ ) {
  7965. const distance = planes[ i ].distanceToPoint( center );
  7966. if ( distance < negRadius ) {
  7967. return false;
  7968. }
  7969. }
  7970. return true;
  7971. }
  7972. intersectsBox( box ) {
  7973. const planes = this.planes;
  7974. for ( let i = 0; i < 6; i ++ ) {
  7975. const plane = planes[ i ];
  7976. // corner at max distance
  7977. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7978. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7979. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7980. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7981. return false;
  7982. }
  7983. }
  7984. return true;
  7985. }
  7986. containsPoint( point ) {
  7987. const planes = this.planes;
  7988. for ( let i = 0; i < 6; i ++ ) {
  7989. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7990. return false;
  7991. }
  7992. }
  7993. return true;
  7994. }
  7995. clone() {
  7996. return new this.constructor().copy( this );
  7997. }
  7998. }
  7999. function WebGLAnimation() {
  8000. let context = null;
  8001. let isAnimating = false;
  8002. let animationLoop = null;
  8003. let requestId = null;
  8004. function onAnimationFrame( time, frame ) {
  8005. animationLoop( time, frame );
  8006. requestId = context.requestAnimationFrame( onAnimationFrame );
  8007. }
  8008. return {
  8009. start: function () {
  8010. if ( isAnimating === true ) return;
  8011. if ( animationLoop === null ) return;
  8012. requestId = context.requestAnimationFrame( onAnimationFrame );
  8013. isAnimating = true;
  8014. },
  8015. stop: function () {
  8016. context.cancelAnimationFrame( requestId );
  8017. isAnimating = false;
  8018. },
  8019. setAnimationLoop: function ( callback ) {
  8020. animationLoop = callback;
  8021. },
  8022. setContext: function ( value ) {
  8023. context = value;
  8024. }
  8025. };
  8026. }
  8027. function WebGLAttributes( gl, capabilities ) {
  8028. const isWebGL2 = capabilities.isWebGL2;
  8029. const buffers = new WeakMap();
  8030. function createBuffer( attribute, bufferType ) {
  8031. const array = attribute.array;
  8032. const usage = attribute.usage;
  8033. const size = array.byteLength;
  8034. const buffer = gl.createBuffer();
  8035. gl.bindBuffer( bufferType, buffer );
  8036. gl.bufferData( bufferType, array, usage );
  8037. attribute.onUploadCallback();
  8038. let type;
  8039. if ( array instanceof Float32Array ) {
  8040. type = gl.FLOAT;
  8041. } else if ( array instanceof Uint16Array ) {
  8042. if ( attribute.isFloat16BufferAttribute ) {
  8043. if ( isWebGL2 ) {
  8044. type = gl.HALF_FLOAT;
  8045. } else {
  8046. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  8047. }
  8048. } else {
  8049. type = gl.UNSIGNED_SHORT;
  8050. }
  8051. } else if ( array instanceof Int16Array ) {
  8052. type = gl.SHORT;
  8053. } else if ( array instanceof Uint32Array ) {
  8054. type = gl.UNSIGNED_INT;
  8055. } else if ( array instanceof Int32Array ) {
  8056. type = gl.INT;
  8057. } else if ( array instanceof Int8Array ) {
  8058. type = gl.BYTE;
  8059. } else if ( array instanceof Uint8Array ) {
  8060. type = gl.UNSIGNED_BYTE;
  8061. } else if ( array instanceof Uint8ClampedArray ) {
  8062. type = gl.UNSIGNED_BYTE;
  8063. } else {
  8064. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  8065. }
  8066. return {
  8067. buffer: buffer,
  8068. type: type,
  8069. bytesPerElement: array.BYTES_PER_ELEMENT,
  8070. version: attribute.version,
  8071. size: size
  8072. };
  8073. }
  8074. function updateBuffer( buffer, attribute, bufferType ) {
  8075. const array = attribute.array;
  8076. const updateRange = attribute._updateRange; // deprecated
  8077. const updateRanges = attribute.updateRanges;
  8078. gl.bindBuffer( bufferType, buffer );
  8079. if ( updateRange.count === - 1 && updateRanges.length === 0 ) {
  8080. // Not using update ranges
  8081. gl.bufferSubData( bufferType, 0, array );
  8082. }
  8083. if ( updateRanges.length !== 0 ) {
  8084. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  8085. const range = updateRanges[ i ];
  8086. if ( isWebGL2 ) {
  8087. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8088. array, range.start, range.count );
  8089. } else {
  8090. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8091. array.subarray( range.start, range.start + range.count ) );
  8092. }
  8093. }
  8094. attribute.clearUpdateRanges();
  8095. }
  8096. // deprecated
  8097. if ( updateRange.count !== - 1 ) {
  8098. if ( isWebGL2 ) {
  8099. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8100. array, updateRange.offset, updateRange.count );
  8101. } else {
  8102. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8103. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8104. }
  8105. updateRange.count = - 1; // reset range
  8106. }
  8107. attribute.onUploadCallback();
  8108. }
  8109. //
  8110. function get( attribute ) {
  8111. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8112. return buffers.get( attribute );
  8113. }
  8114. function remove( attribute ) {
  8115. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8116. const data = buffers.get( attribute );
  8117. if ( data ) {
  8118. gl.deleteBuffer( data.buffer );
  8119. buffers.delete( attribute );
  8120. }
  8121. }
  8122. function update( attribute, bufferType ) {
  8123. if ( attribute.isGLBufferAttribute ) {
  8124. const cached = buffers.get( attribute );
  8125. if ( ! cached || cached.version < attribute.version ) {
  8126. buffers.set( attribute, {
  8127. buffer: attribute.buffer,
  8128. type: attribute.type,
  8129. bytesPerElement: attribute.elementSize,
  8130. version: attribute.version
  8131. } );
  8132. }
  8133. return;
  8134. }
  8135. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8136. const data = buffers.get( attribute );
  8137. if ( data === undefined ) {
  8138. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8139. } else if ( data.version < attribute.version ) {
  8140. if ( data.size !== attribute.array.byteLength ) {
  8141. 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.' );
  8142. }
  8143. updateBuffer( data.buffer, attribute, bufferType );
  8144. data.version = attribute.version;
  8145. }
  8146. }
  8147. return {
  8148. get: get,
  8149. remove: remove,
  8150. update: update
  8151. };
  8152. }
  8153. class PlaneGeometry extends BufferGeometry {
  8154. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8155. super();
  8156. this.type = 'PlaneGeometry';
  8157. this.parameters = {
  8158. width: width,
  8159. height: height,
  8160. widthSegments: widthSegments,
  8161. heightSegments: heightSegments
  8162. };
  8163. const width_half = width / 2;
  8164. const height_half = height / 2;
  8165. const gridX = Math.floor( widthSegments );
  8166. const gridY = Math.floor( heightSegments );
  8167. const gridX1 = gridX + 1;
  8168. const gridY1 = gridY + 1;
  8169. const segment_width = width / gridX;
  8170. const segment_height = height / gridY;
  8171. //
  8172. const indices = [];
  8173. const vertices = [];
  8174. const normals = [];
  8175. const uvs = [];
  8176. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8177. const y = iy * segment_height - height_half;
  8178. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8179. const x = ix * segment_width - width_half;
  8180. vertices.push( x, - y, 0 );
  8181. normals.push( 0, 0, 1 );
  8182. uvs.push( ix / gridX );
  8183. uvs.push( 1 - ( iy / gridY ) );
  8184. }
  8185. }
  8186. for ( let iy = 0; iy < gridY; iy ++ ) {
  8187. for ( let ix = 0; ix < gridX; ix ++ ) {
  8188. const a = ix + gridX1 * iy;
  8189. const b = ix + gridX1 * ( iy + 1 );
  8190. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8191. const d = ( ix + 1 ) + gridX1 * iy;
  8192. indices.push( a, b, d );
  8193. indices.push( b, c, d );
  8194. }
  8195. }
  8196. this.setIndex( indices );
  8197. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8198. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8199. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8200. }
  8201. copy( source ) {
  8202. super.copy( source );
  8203. this.parameters = Object.assign( {}, source.parameters );
  8204. return this;
  8205. }
  8206. static fromJSON( data ) {
  8207. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8208. }
  8209. }
  8210. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8211. 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";
  8212. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8213. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8214. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8215. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8216. 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";
  8217. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8218. 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";
  8219. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( batchId );\n#endif";
  8220. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8221. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8222. 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";
  8223. 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";
  8224. 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";
  8225. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  8226. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8227. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8228. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8229. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8230. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8231. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8232. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  8233. 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";
  8234. 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";
  8235. 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";
  8236. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8237. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8238. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8239. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8240. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8241. 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}";
  8242. 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, 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";
  8243. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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";
  8244. 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";
  8245. 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";
  8246. 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";
  8247. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8248. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8249. 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";
  8250. 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";
  8251. 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}";
  8252. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8253. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8254. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8255. 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";
  8256. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  8257. 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, 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, 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";
  8258. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8259. 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";
  8260. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8261. 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";
  8262. 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_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";
  8263. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\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}";
  8264. 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";
  8265. 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";
  8266. 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";
  8267. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8268. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8269. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8270. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  8271. 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";
  8272. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8273. 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";
  8274. 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";
  8275. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8276. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8277. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  8278. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  8279. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  8280. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  8281. 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;";
  8282. 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";
  8283. 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";
  8284. 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";
  8285. 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";
  8286. 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";
  8287. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8288. 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";
  8289. 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";
  8290. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8291. 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 );";
  8292. 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}";
  8293. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8294. 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;";
  8295. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8296. 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";
  8297. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8298. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8299. 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\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8300. 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";
  8301. 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";
  8302. 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}";
  8303. 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";
  8304. 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";
  8305. 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";
  8306. 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";
  8307. 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";
  8308. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8309. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8310. 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 = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor *= toneMappingExposure;\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\treturn color;\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8311. 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.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";
  8312. 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 ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\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";
  8313. 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";
  8314. 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";
  8315. 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";
  8316. 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";
  8317. 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}";
  8318. 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}";
  8319. 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}";
  8320. 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;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, 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}";
  8321. 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}";
  8322. 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}";
  8323. 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#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}";
  8324. 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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\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}";
  8325. 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#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}";
  8326. 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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\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}";
  8327. 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}";
  8328. 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}";
  8329. 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 <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}";
  8330. 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\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8331. 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 <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}";
  8332. 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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8333. 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 <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}";
  8334. 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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8335. 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 <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}";
  8336. 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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8337. 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 <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}";
  8338. 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\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 ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8339. 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 <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}";
  8340. 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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8341. 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 <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}";
  8342. 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_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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8343. 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 <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}";
  8344. 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\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8345. 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 <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}";
  8346. 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\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8347. 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 <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}";
  8348. 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}";
  8349. 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}";
  8350. 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\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\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}";
  8351. const ShaderChunk = {
  8352. alphahash_fragment: alphahash_fragment,
  8353. alphahash_pars_fragment: alphahash_pars_fragment,
  8354. alphamap_fragment: alphamap_fragment,
  8355. alphamap_pars_fragment: alphamap_pars_fragment,
  8356. alphatest_fragment: alphatest_fragment,
  8357. alphatest_pars_fragment: alphatest_pars_fragment,
  8358. aomap_fragment: aomap_fragment,
  8359. aomap_pars_fragment: aomap_pars_fragment,
  8360. batching_pars_vertex: batching_pars_vertex,
  8361. batching_vertex: batching_vertex,
  8362. begin_vertex: begin_vertex,
  8363. beginnormal_vertex: beginnormal_vertex,
  8364. bsdfs: bsdfs,
  8365. iridescence_fragment: iridescence_fragment,
  8366. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8367. clipping_planes_fragment: clipping_planes_fragment,
  8368. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8369. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8370. clipping_planes_vertex: clipping_planes_vertex,
  8371. color_fragment: color_fragment,
  8372. color_pars_fragment: color_pars_fragment,
  8373. color_pars_vertex: color_pars_vertex,
  8374. color_vertex: color_vertex,
  8375. common: common,
  8376. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8377. defaultnormal_vertex: defaultnormal_vertex,
  8378. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8379. displacementmap_vertex: displacementmap_vertex,
  8380. emissivemap_fragment: emissivemap_fragment,
  8381. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8382. colorspace_fragment: colorspace_fragment,
  8383. colorspace_pars_fragment: colorspace_pars_fragment,
  8384. envmap_fragment: envmap_fragment,
  8385. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8386. envmap_pars_fragment: envmap_pars_fragment,
  8387. envmap_pars_vertex: envmap_pars_vertex,
  8388. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8389. envmap_vertex: envmap_vertex,
  8390. fog_vertex: fog_vertex,
  8391. fog_pars_vertex: fog_pars_vertex,
  8392. fog_fragment: fog_fragment,
  8393. fog_pars_fragment: fog_pars_fragment,
  8394. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8395. lightmap_fragment: lightmap_fragment,
  8396. lightmap_pars_fragment: lightmap_pars_fragment,
  8397. lights_lambert_fragment: lights_lambert_fragment,
  8398. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8399. lights_pars_begin: lights_pars_begin,
  8400. lights_toon_fragment: lights_toon_fragment,
  8401. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8402. lights_phong_fragment: lights_phong_fragment,
  8403. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8404. lights_physical_fragment: lights_physical_fragment,
  8405. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8406. lights_fragment_begin: lights_fragment_begin,
  8407. lights_fragment_maps: lights_fragment_maps,
  8408. lights_fragment_end: lights_fragment_end,
  8409. logdepthbuf_fragment: logdepthbuf_fragment,
  8410. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8411. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8412. logdepthbuf_vertex: logdepthbuf_vertex,
  8413. map_fragment: map_fragment,
  8414. map_pars_fragment: map_pars_fragment,
  8415. map_particle_fragment: map_particle_fragment,
  8416. map_particle_pars_fragment: map_particle_pars_fragment,
  8417. metalnessmap_fragment: metalnessmap_fragment,
  8418. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8419. morphcolor_vertex: morphcolor_vertex,
  8420. morphnormal_vertex: morphnormal_vertex,
  8421. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8422. morphtarget_vertex: morphtarget_vertex,
  8423. normal_fragment_begin: normal_fragment_begin,
  8424. normal_fragment_maps: normal_fragment_maps,
  8425. normal_pars_fragment: normal_pars_fragment,
  8426. normal_pars_vertex: normal_pars_vertex,
  8427. normal_vertex: normal_vertex,
  8428. normalmap_pars_fragment: normalmap_pars_fragment,
  8429. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8430. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8431. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8432. iridescence_pars_fragment: iridescence_pars_fragment,
  8433. opaque_fragment: opaque_fragment,
  8434. packing: packing,
  8435. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8436. project_vertex: project_vertex,
  8437. dithering_fragment: dithering_fragment,
  8438. dithering_pars_fragment: dithering_pars_fragment,
  8439. roughnessmap_fragment: roughnessmap_fragment,
  8440. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8441. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8442. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8443. shadowmap_vertex: shadowmap_vertex,
  8444. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8445. skinbase_vertex: skinbase_vertex,
  8446. skinning_pars_vertex: skinning_pars_vertex,
  8447. skinning_vertex: skinning_vertex,
  8448. skinnormal_vertex: skinnormal_vertex,
  8449. specularmap_fragment: specularmap_fragment,
  8450. specularmap_pars_fragment: specularmap_pars_fragment,
  8451. tonemapping_fragment: tonemapping_fragment,
  8452. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8453. transmission_fragment: transmission_fragment,
  8454. transmission_pars_fragment: transmission_pars_fragment,
  8455. uv_pars_fragment: uv_pars_fragment,
  8456. uv_pars_vertex: uv_pars_vertex,
  8457. uv_vertex: uv_vertex,
  8458. worldpos_vertex: worldpos_vertex,
  8459. background_vert: vertex$h,
  8460. background_frag: fragment$h,
  8461. backgroundCube_vert: vertex$g,
  8462. backgroundCube_frag: fragment$g,
  8463. cube_vert: vertex$f,
  8464. cube_frag: fragment$f,
  8465. depth_vert: vertex$e,
  8466. depth_frag: fragment$e,
  8467. distanceRGBA_vert: vertex$d,
  8468. distanceRGBA_frag: fragment$d,
  8469. equirect_vert: vertex$c,
  8470. equirect_frag: fragment$c,
  8471. linedashed_vert: vertex$b,
  8472. linedashed_frag: fragment$b,
  8473. meshbasic_vert: vertex$a,
  8474. meshbasic_frag: fragment$a,
  8475. meshlambert_vert: vertex$9,
  8476. meshlambert_frag: fragment$9,
  8477. meshmatcap_vert: vertex$8,
  8478. meshmatcap_frag: fragment$8,
  8479. meshnormal_vert: vertex$7,
  8480. meshnormal_frag: fragment$7,
  8481. meshphong_vert: vertex$6,
  8482. meshphong_frag: fragment$6,
  8483. meshphysical_vert: vertex$5,
  8484. meshphysical_frag: fragment$5,
  8485. meshtoon_vert: vertex$4,
  8486. meshtoon_frag: fragment$4,
  8487. points_vert: vertex$3,
  8488. points_frag: fragment$3,
  8489. shadow_vert: vertex$2,
  8490. shadow_frag: fragment$2,
  8491. sprite_vert: vertex$1,
  8492. sprite_frag: fragment$1
  8493. };
  8494. /**
  8495. * Uniforms library for shared webgl shaders
  8496. */
  8497. const UniformsLib = {
  8498. common: {
  8499. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8500. opacity: { value: 1.0 },
  8501. map: { value: null },
  8502. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8503. alphaMap: { value: null },
  8504. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8505. alphaTest: { value: 0 }
  8506. },
  8507. specularmap: {
  8508. specularMap: { value: null },
  8509. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8510. },
  8511. envmap: {
  8512. envMap: { value: null },
  8513. flipEnvMap: { value: - 1 },
  8514. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8515. ior: { value: 1.5 }, // physical
  8516. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8517. },
  8518. aomap: {
  8519. aoMap: { value: null },
  8520. aoMapIntensity: { value: 1 },
  8521. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8522. },
  8523. lightmap: {
  8524. lightMap: { value: null },
  8525. lightMapIntensity: { value: 1 },
  8526. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8527. },
  8528. bumpmap: {
  8529. bumpMap: { value: null },
  8530. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8531. bumpScale: { value: 1 }
  8532. },
  8533. normalmap: {
  8534. normalMap: { value: null },
  8535. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8536. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8537. },
  8538. displacementmap: {
  8539. displacementMap: { value: null },
  8540. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8541. displacementScale: { value: 1 },
  8542. displacementBias: { value: 0 }
  8543. },
  8544. emissivemap: {
  8545. emissiveMap: { value: null },
  8546. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8547. },
  8548. metalnessmap: {
  8549. metalnessMap: { value: null },
  8550. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8551. },
  8552. roughnessmap: {
  8553. roughnessMap: { value: null },
  8554. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8555. },
  8556. gradientmap: {
  8557. gradientMap: { value: null }
  8558. },
  8559. fog: {
  8560. fogDensity: { value: 0.00025 },
  8561. fogNear: { value: 1 },
  8562. fogFar: { value: 2000 },
  8563. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8564. },
  8565. lights: {
  8566. ambientLightColor: { value: [] },
  8567. lightProbe: { value: [] },
  8568. directionalLights: { value: [], properties: {
  8569. direction: {},
  8570. color: {}
  8571. } },
  8572. directionalLightShadows: { value: [], properties: {
  8573. shadowBias: {},
  8574. shadowNormalBias: {},
  8575. shadowRadius: {},
  8576. shadowMapSize: {}
  8577. } },
  8578. directionalShadowMap: { value: [] },
  8579. directionalShadowMatrix: { value: [] },
  8580. spotLights: { value: [], properties: {
  8581. color: {},
  8582. position: {},
  8583. direction: {},
  8584. distance: {},
  8585. coneCos: {},
  8586. penumbraCos: {},
  8587. decay: {}
  8588. } },
  8589. spotLightShadows: { value: [], properties: {
  8590. shadowBias: {},
  8591. shadowNormalBias: {},
  8592. shadowRadius: {},
  8593. shadowMapSize: {}
  8594. } },
  8595. spotLightMap: { value: [] },
  8596. spotShadowMap: { value: [] },
  8597. spotLightMatrix: { value: [] },
  8598. pointLights: { value: [], properties: {
  8599. color: {},
  8600. position: {},
  8601. decay: {},
  8602. distance: {}
  8603. } },
  8604. pointLightShadows: { value: [], properties: {
  8605. shadowBias: {},
  8606. shadowNormalBias: {},
  8607. shadowRadius: {},
  8608. shadowMapSize: {},
  8609. shadowCameraNear: {},
  8610. shadowCameraFar: {}
  8611. } },
  8612. pointShadowMap: { value: [] },
  8613. pointShadowMatrix: { value: [] },
  8614. hemisphereLights: { value: [], properties: {
  8615. direction: {},
  8616. skyColor: {},
  8617. groundColor: {}
  8618. } },
  8619. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8620. rectAreaLights: { value: [], properties: {
  8621. color: {},
  8622. position: {},
  8623. width: {},
  8624. height: {}
  8625. } },
  8626. ltc_1: { value: null },
  8627. ltc_2: { value: null }
  8628. },
  8629. points: {
  8630. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8631. opacity: { value: 1.0 },
  8632. size: { value: 1.0 },
  8633. scale: { value: 1.0 },
  8634. map: { value: null },
  8635. alphaMap: { value: null },
  8636. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8637. alphaTest: { value: 0 },
  8638. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8639. },
  8640. sprite: {
  8641. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8642. opacity: { value: 1.0 },
  8643. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8644. rotation: { value: 0.0 },
  8645. map: { value: null },
  8646. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8647. alphaMap: { value: null },
  8648. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8649. alphaTest: { value: 0 }
  8650. }
  8651. };
  8652. const ShaderLib = {
  8653. basic: {
  8654. uniforms: /*@__PURE__*/ mergeUniforms( [
  8655. UniformsLib.common,
  8656. UniformsLib.specularmap,
  8657. UniformsLib.envmap,
  8658. UniformsLib.aomap,
  8659. UniformsLib.lightmap,
  8660. UniformsLib.fog
  8661. ] ),
  8662. vertexShader: ShaderChunk.meshbasic_vert,
  8663. fragmentShader: ShaderChunk.meshbasic_frag
  8664. },
  8665. lambert: {
  8666. uniforms: /*@__PURE__*/ mergeUniforms( [
  8667. UniformsLib.common,
  8668. UniformsLib.specularmap,
  8669. UniformsLib.envmap,
  8670. UniformsLib.aomap,
  8671. UniformsLib.lightmap,
  8672. UniformsLib.emissivemap,
  8673. UniformsLib.bumpmap,
  8674. UniformsLib.normalmap,
  8675. UniformsLib.displacementmap,
  8676. UniformsLib.fog,
  8677. UniformsLib.lights,
  8678. {
  8679. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8680. }
  8681. ] ),
  8682. vertexShader: ShaderChunk.meshlambert_vert,
  8683. fragmentShader: ShaderChunk.meshlambert_frag
  8684. },
  8685. phong: {
  8686. uniforms: /*@__PURE__*/ mergeUniforms( [
  8687. UniformsLib.common,
  8688. UniformsLib.specularmap,
  8689. UniformsLib.envmap,
  8690. UniformsLib.aomap,
  8691. UniformsLib.lightmap,
  8692. UniformsLib.emissivemap,
  8693. UniformsLib.bumpmap,
  8694. UniformsLib.normalmap,
  8695. UniformsLib.displacementmap,
  8696. UniformsLib.fog,
  8697. UniformsLib.lights,
  8698. {
  8699. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8700. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8701. shininess: { value: 30 }
  8702. }
  8703. ] ),
  8704. vertexShader: ShaderChunk.meshphong_vert,
  8705. fragmentShader: ShaderChunk.meshphong_frag
  8706. },
  8707. standard: {
  8708. uniforms: /*@__PURE__*/ mergeUniforms( [
  8709. UniformsLib.common,
  8710. UniformsLib.envmap,
  8711. UniformsLib.aomap,
  8712. UniformsLib.lightmap,
  8713. UniformsLib.emissivemap,
  8714. UniformsLib.bumpmap,
  8715. UniformsLib.normalmap,
  8716. UniformsLib.displacementmap,
  8717. UniformsLib.roughnessmap,
  8718. UniformsLib.metalnessmap,
  8719. UniformsLib.fog,
  8720. UniformsLib.lights,
  8721. {
  8722. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8723. roughness: { value: 1.0 },
  8724. metalness: { value: 0.0 },
  8725. envMapIntensity: { value: 1 } // temporary
  8726. }
  8727. ] ),
  8728. vertexShader: ShaderChunk.meshphysical_vert,
  8729. fragmentShader: ShaderChunk.meshphysical_frag
  8730. },
  8731. toon: {
  8732. uniforms: /*@__PURE__*/ mergeUniforms( [
  8733. UniformsLib.common,
  8734. UniformsLib.aomap,
  8735. UniformsLib.lightmap,
  8736. UniformsLib.emissivemap,
  8737. UniformsLib.bumpmap,
  8738. UniformsLib.normalmap,
  8739. UniformsLib.displacementmap,
  8740. UniformsLib.gradientmap,
  8741. UniformsLib.fog,
  8742. UniformsLib.lights,
  8743. {
  8744. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8745. }
  8746. ] ),
  8747. vertexShader: ShaderChunk.meshtoon_vert,
  8748. fragmentShader: ShaderChunk.meshtoon_frag
  8749. },
  8750. matcap: {
  8751. uniforms: /*@__PURE__*/ mergeUniforms( [
  8752. UniformsLib.common,
  8753. UniformsLib.bumpmap,
  8754. UniformsLib.normalmap,
  8755. UniformsLib.displacementmap,
  8756. UniformsLib.fog,
  8757. {
  8758. matcap: { value: null }
  8759. }
  8760. ] ),
  8761. vertexShader: ShaderChunk.meshmatcap_vert,
  8762. fragmentShader: ShaderChunk.meshmatcap_frag
  8763. },
  8764. points: {
  8765. uniforms: /*@__PURE__*/ mergeUniforms( [
  8766. UniformsLib.points,
  8767. UniformsLib.fog
  8768. ] ),
  8769. vertexShader: ShaderChunk.points_vert,
  8770. fragmentShader: ShaderChunk.points_frag
  8771. },
  8772. dashed: {
  8773. uniforms: /*@__PURE__*/ mergeUniforms( [
  8774. UniformsLib.common,
  8775. UniformsLib.fog,
  8776. {
  8777. scale: { value: 1 },
  8778. dashSize: { value: 1 },
  8779. totalSize: { value: 2 }
  8780. }
  8781. ] ),
  8782. vertexShader: ShaderChunk.linedashed_vert,
  8783. fragmentShader: ShaderChunk.linedashed_frag
  8784. },
  8785. depth: {
  8786. uniforms: /*@__PURE__*/ mergeUniforms( [
  8787. UniformsLib.common,
  8788. UniformsLib.displacementmap
  8789. ] ),
  8790. vertexShader: ShaderChunk.depth_vert,
  8791. fragmentShader: ShaderChunk.depth_frag
  8792. },
  8793. normal: {
  8794. uniforms: /*@__PURE__*/ mergeUniforms( [
  8795. UniformsLib.common,
  8796. UniformsLib.bumpmap,
  8797. UniformsLib.normalmap,
  8798. UniformsLib.displacementmap,
  8799. {
  8800. opacity: { value: 1.0 }
  8801. }
  8802. ] ),
  8803. vertexShader: ShaderChunk.meshnormal_vert,
  8804. fragmentShader: ShaderChunk.meshnormal_frag
  8805. },
  8806. sprite: {
  8807. uniforms: /*@__PURE__*/ mergeUniforms( [
  8808. UniformsLib.sprite,
  8809. UniformsLib.fog
  8810. ] ),
  8811. vertexShader: ShaderChunk.sprite_vert,
  8812. fragmentShader: ShaderChunk.sprite_frag
  8813. },
  8814. background: {
  8815. uniforms: {
  8816. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8817. t2D: { value: null },
  8818. backgroundIntensity: { value: 1 }
  8819. },
  8820. vertexShader: ShaderChunk.background_vert,
  8821. fragmentShader: ShaderChunk.background_frag
  8822. },
  8823. backgroundCube: {
  8824. uniforms: {
  8825. envMap: { value: null },
  8826. flipEnvMap: { value: - 1 },
  8827. backgroundBlurriness: { value: 0 },
  8828. backgroundIntensity: { value: 1 }
  8829. },
  8830. vertexShader: ShaderChunk.backgroundCube_vert,
  8831. fragmentShader: ShaderChunk.backgroundCube_frag
  8832. },
  8833. cube: {
  8834. uniforms: {
  8835. tCube: { value: null },
  8836. tFlip: { value: - 1 },
  8837. opacity: { value: 1.0 }
  8838. },
  8839. vertexShader: ShaderChunk.cube_vert,
  8840. fragmentShader: ShaderChunk.cube_frag
  8841. },
  8842. equirect: {
  8843. uniforms: {
  8844. tEquirect: { value: null },
  8845. },
  8846. vertexShader: ShaderChunk.equirect_vert,
  8847. fragmentShader: ShaderChunk.equirect_frag
  8848. },
  8849. distanceRGBA: {
  8850. uniforms: /*@__PURE__*/ mergeUniforms( [
  8851. UniformsLib.common,
  8852. UniformsLib.displacementmap,
  8853. {
  8854. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8855. nearDistance: { value: 1 },
  8856. farDistance: { value: 1000 }
  8857. }
  8858. ] ),
  8859. vertexShader: ShaderChunk.distanceRGBA_vert,
  8860. fragmentShader: ShaderChunk.distanceRGBA_frag
  8861. },
  8862. shadow: {
  8863. uniforms: /*@__PURE__*/ mergeUniforms( [
  8864. UniformsLib.lights,
  8865. UniformsLib.fog,
  8866. {
  8867. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8868. opacity: { value: 1.0 }
  8869. },
  8870. ] ),
  8871. vertexShader: ShaderChunk.shadow_vert,
  8872. fragmentShader: ShaderChunk.shadow_frag
  8873. }
  8874. };
  8875. ShaderLib.physical = {
  8876. uniforms: /*@__PURE__*/ mergeUniforms( [
  8877. ShaderLib.standard.uniforms,
  8878. {
  8879. clearcoat: { value: 0 },
  8880. clearcoatMap: { value: null },
  8881. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8882. clearcoatNormalMap: { value: null },
  8883. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8884. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8885. clearcoatRoughness: { value: 0 },
  8886. clearcoatRoughnessMap: { value: null },
  8887. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8888. iridescence: { value: 0 },
  8889. iridescenceMap: { value: null },
  8890. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8891. iridescenceIOR: { value: 1.3 },
  8892. iridescenceThicknessMinimum: { value: 100 },
  8893. iridescenceThicknessMaximum: { value: 400 },
  8894. iridescenceThicknessMap: { value: null },
  8895. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8896. sheen: { value: 0 },
  8897. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8898. sheenColorMap: { value: null },
  8899. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8900. sheenRoughness: { value: 1 },
  8901. sheenRoughnessMap: { value: null },
  8902. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8903. transmission: { value: 0 },
  8904. transmissionMap: { value: null },
  8905. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8906. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8907. transmissionSamplerMap: { value: null },
  8908. thickness: { value: 0 },
  8909. thicknessMap: { value: null },
  8910. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8911. attenuationDistance: { value: 0 },
  8912. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8913. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8914. specularColorMap: { value: null },
  8915. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8916. specularIntensity: { value: 1 },
  8917. specularIntensityMap: { value: null },
  8918. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8919. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8920. anisotropyMap: { value: null },
  8921. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8922. }
  8923. ] ),
  8924. vertexShader: ShaderChunk.meshphysical_vert,
  8925. fragmentShader: ShaderChunk.meshphysical_frag
  8926. };
  8927. const _rgb = { r: 0, b: 0, g: 0 };
  8928. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8929. const clearColor = new Color( 0x000000 );
  8930. let clearAlpha = alpha === true ? 0 : 1;
  8931. let planeMesh;
  8932. let boxMesh;
  8933. let currentBackground = null;
  8934. let currentBackgroundVersion = 0;
  8935. let currentTonemapping = null;
  8936. function render( renderList, scene ) {
  8937. let forceClear = false;
  8938. let background = scene.isScene === true ? scene.background : null;
  8939. if ( background && background.isTexture ) {
  8940. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8941. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8942. }
  8943. if ( background === null ) {
  8944. setClear( clearColor, clearAlpha );
  8945. } else if ( background && background.isColor ) {
  8946. setClear( background, 1 );
  8947. forceClear = true;
  8948. }
  8949. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8950. if ( environmentBlendMode === 'additive' ) {
  8951. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8952. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8953. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8954. }
  8955. if ( renderer.autoClear || forceClear ) {
  8956. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8957. }
  8958. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8959. if ( boxMesh === undefined ) {
  8960. boxMesh = new Mesh(
  8961. new BoxGeometry( 1, 1, 1 ),
  8962. new ShaderMaterial( {
  8963. name: 'BackgroundCubeMaterial',
  8964. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8965. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8966. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8967. side: BackSide,
  8968. depthTest: false,
  8969. depthWrite: false,
  8970. fog: false
  8971. } )
  8972. );
  8973. boxMesh.geometry.deleteAttribute( 'normal' );
  8974. boxMesh.geometry.deleteAttribute( 'uv' );
  8975. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8976. this.matrixWorld.copyPosition( camera.matrixWorld );
  8977. };
  8978. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8979. Object.defineProperty( boxMesh.material, 'envMap', {
  8980. get: function () {
  8981. return this.uniforms.envMap.value;
  8982. }
  8983. } );
  8984. objects.update( boxMesh );
  8985. }
  8986. boxMesh.material.uniforms.envMap.value = background;
  8987. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8988. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8989. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8990. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8991. if ( currentBackground !== background ||
  8992. currentBackgroundVersion !== background.version ||
  8993. currentTonemapping !== renderer.toneMapping ) {
  8994. boxMesh.material.needsUpdate = true;
  8995. currentBackground = background;
  8996. currentBackgroundVersion = background.version;
  8997. currentTonemapping = renderer.toneMapping;
  8998. }
  8999. boxMesh.layers.enableAll();
  9000. // push to the pre-sorted opaque render list
  9001. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9002. } else if ( background && background.isTexture ) {
  9003. if ( planeMesh === undefined ) {
  9004. planeMesh = new Mesh(
  9005. new PlaneGeometry( 2, 2 ),
  9006. new ShaderMaterial( {
  9007. name: 'BackgroundMaterial',
  9008. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9009. vertexShader: ShaderLib.background.vertexShader,
  9010. fragmentShader: ShaderLib.background.fragmentShader,
  9011. side: FrontSide,
  9012. depthTest: false,
  9013. depthWrite: false,
  9014. fog: false
  9015. } )
  9016. );
  9017. planeMesh.geometry.deleteAttribute( 'normal' );
  9018. // add "map" material property so the renderer can evaluate it like for built-in materials
  9019. Object.defineProperty( planeMesh.material, 'map', {
  9020. get: function () {
  9021. return this.uniforms.t2D.value;
  9022. }
  9023. } );
  9024. objects.update( planeMesh );
  9025. }
  9026. planeMesh.material.uniforms.t2D.value = background;
  9027. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  9028. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  9029. if ( background.matrixAutoUpdate === true ) {
  9030. background.updateMatrix();
  9031. }
  9032. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9033. if ( currentBackground !== background ||
  9034. currentBackgroundVersion !== background.version ||
  9035. currentTonemapping !== renderer.toneMapping ) {
  9036. planeMesh.material.needsUpdate = true;
  9037. currentBackground = background;
  9038. currentBackgroundVersion = background.version;
  9039. currentTonemapping = renderer.toneMapping;
  9040. }
  9041. planeMesh.layers.enableAll();
  9042. // push to the pre-sorted opaque render list
  9043. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9044. }
  9045. }
  9046. function setClear( color, alpha ) {
  9047. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  9048. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  9049. }
  9050. return {
  9051. getClearColor: function () {
  9052. return clearColor;
  9053. },
  9054. setClearColor: function ( color, alpha = 1 ) {
  9055. clearColor.set( color );
  9056. clearAlpha = alpha;
  9057. setClear( clearColor, clearAlpha );
  9058. },
  9059. getClearAlpha: function () {
  9060. return clearAlpha;
  9061. },
  9062. setClearAlpha: function ( alpha ) {
  9063. clearAlpha = alpha;
  9064. setClear( clearColor, clearAlpha );
  9065. },
  9066. render: render
  9067. };
  9068. }
  9069. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9070. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9071. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9072. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9073. const bindingStates = {};
  9074. const defaultState = createBindingState( null );
  9075. let currentState = defaultState;
  9076. let forceUpdate = false;
  9077. function setup( object, material, program, geometry, index ) {
  9078. let updateBuffers = false;
  9079. if ( vaoAvailable ) {
  9080. const state = getBindingState( geometry, program, material );
  9081. if ( currentState !== state ) {
  9082. currentState = state;
  9083. bindVertexArrayObject( currentState.object );
  9084. }
  9085. updateBuffers = needsUpdate( object, geometry, program, index );
  9086. if ( updateBuffers ) saveCache( object, geometry, program, index );
  9087. } else {
  9088. const wireframe = ( material.wireframe === true );
  9089. if ( currentState.geometry !== geometry.id ||
  9090. currentState.program !== program.id ||
  9091. currentState.wireframe !== wireframe ) {
  9092. currentState.geometry = geometry.id;
  9093. currentState.program = program.id;
  9094. currentState.wireframe = wireframe;
  9095. updateBuffers = true;
  9096. }
  9097. }
  9098. if ( index !== null ) {
  9099. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9100. }
  9101. if ( updateBuffers || forceUpdate ) {
  9102. forceUpdate = false;
  9103. setupVertexAttributes( object, material, program, geometry );
  9104. if ( index !== null ) {
  9105. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9106. }
  9107. }
  9108. }
  9109. function createVertexArrayObject() {
  9110. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9111. return extension.createVertexArrayOES();
  9112. }
  9113. function bindVertexArrayObject( vao ) {
  9114. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9115. return extension.bindVertexArrayOES( vao );
  9116. }
  9117. function deleteVertexArrayObject( vao ) {
  9118. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9119. return extension.deleteVertexArrayOES( vao );
  9120. }
  9121. function getBindingState( geometry, program, material ) {
  9122. const wireframe = ( material.wireframe === true );
  9123. let programMap = bindingStates[ geometry.id ];
  9124. if ( programMap === undefined ) {
  9125. programMap = {};
  9126. bindingStates[ geometry.id ] = programMap;
  9127. }
  9128. let stateMap = programMap[ program.id ];
  9129. if ( stateMap === undefined ) {
  9130. stateMap = {};
  9131. programMap[ program.id ] = stateMap;
  9132. }
  9133. let state = stateMap[ wireframe ];
  9134. if ( state === undefined ) {
  9135. state = createBindingState( createVertexArrayObject() );
  9136. stateMap[ wireframe ] = state;
  9137. }
  9138. return state;
  9139. }
  9140. function createBindingState( vao ) {
  9141. const newAttributes = [];
  9142. const enabledAttributes = [];
  9143. const attributeDivisors = [];
  9144. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9145. newAttributes[ i ] = 0;
  9146. enabledAttributes[ i ] = 0;
  9147. attributeDivisors[ i ] = 0;
  9148. }
  9149. return {
  9150. // for backward compatibility on non-VAO support browser
  9151. geometry: null,
  9152. program: null,
  9153. wireframe: false,
  9154. newAttributes: newAttributes,
  9155. enabledAttributes: enabledAttributes,
  9156. attributeDivisors: attributeDivisors,
  9157. object: vao,
  9158. attributes: {},
  9159. index: null
  9160. };
  9161. }
  9162. function needsUpdate( object, geometry, program, index ) {
  9163. const cachedAttributes = currentState.attributes;
  9164. const geometryAttributes = geometry.attributes;
  9165. let attributesNum = 0;
  9166. const programAttributes = program.getAttributes();
  9167. for ( const name in programAttributes ) {
  9168. const programAttribute = programAttributes[ name ];
  9169. if ( programAttribute.location >= 0 ) {
  9170. const cachedAttribute = cachedAttributes[ name ];
  9171. let geometryAttribute = geometryAttributes[ name ];
  9172. if ( geometryAttribute === undefined ) {
  9173. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9174. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9175. }
  9176. if ( cachedAttribute === undefined ) return true;
  9177. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9178. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9179. attributesNum ++;
  9180. }
  9181. }
  9182. if ( currentState.attributesNum !== attributesNum ) return true;
  9183. if ( currentState.index !== index ) return true;
  9184. return false;
  9185. }
  9186. function saveCache( object, geometry, program, index ) {
  9187. const cache = {};
  9188. const attributes = geometry.attributes;
  9189. let attributesNum = 0;
  9190. const programAttributes = program.getAttributes();
  9191. for ( const name in programAttributes ) {
  9192. const programAttribute = programAttributes[ name ];
  9193. if ( programAttribute.location >= 0 ) {
  9194. let attribute = attributes[ name ];
  9195. if ( attribute === undefined ) {
  9196. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9197. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9198. }
  9199. const data = {};
  9200. data.attribute = attribute;
  9201. if ( attribute && attribute.data ) {
  9202. data.data = attribute.data;
  9203. }
  9204. cache[ name ] = data;
  9205. attributesNum ++;
  9206. }
  9207. }
  9208. currentState.attributes = cache;
  9209. currentState.attributesNum = attributesNum;
  9210. currentState.index = index;
  9211. }
  9212. function initAttributes() {
  9213. const newAttributes = currentState.newAttributes;
  9214. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9215. newAttributes[ i ] = 0;
  9216. }
  9217. }
  9218. function enableAttribute( attribute ) {
  9219. enableAttributeAndDivisor( attribute, 0 );
  9220. }
  9221. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9222. const newAttributes = currentState.newAttributes;
  9223. const enabledAttributes = currentState.enabledAttributes;
  9224. const attributeDivisors = currentState.attributeDivisors;
  9225. newAttributes[ attribute ] = 1;
  9226. if ( enabledAttributes[ attribute ] === 0 ) {
  9227. gl.enableVertexAttribArray( attribute );
  9228. enabledAttributes[ attribute ] = 1;
  9229. }
  9230. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9231. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9232. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9233. attributeDivisors[ attribute ] = meshPerAttribute;
  9234. }
  9235. }
  9236. function disableUnusedAttributes() {
  9237. const newAttributes = currentState.newAttributes;
  9238. const enabledAttributes = currentState.enabledAttributes;
  9239. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9240. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9241. gl.disableVertexAttribArray( i );
  9242. enabledAttributes[ i ] = 0;
  9243. }
  9244. }
  9245. }
  9246. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9247. if ( integer === true ) {
  9248. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9249. } else {
  9250. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9251. }
  9252. }
  9253. function setupVertexAttributes( object, material, program, geometry ) {
  9254. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9255. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9256. }
  9257. initAttributes();
  9258. const geometryAttributes = geometry.attributes;
  9259. const programAttributes = program.getAttributes();
  9260. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9261. for ( const name in programAttributes ) {
  9262. const programAttribute = programAttributes[ name ];
  9263. if ( programAttribute.location >= 0 ) {
  9264. let geometryAttribute = geometryAttributes[ name ];
  9265. if ( geometryAttribute === undefined ) {
  9266. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9267. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9268. }
  9269. if ( geometryAttribute !== undefined ) {
  9270. const normalized = geometryAttribute.normalized;
  9271. const size = geometryAttribute.itemSize;
  9272. const attribute = attributes.get( geometryAttribute );
  9273. // TODO Attribute may not be available on context restore
  9274. if ( attribute === undefined ) continue;
  9275. const buffer = attribute.buffer;
  9276. const type = attribute.type;
  9277. const bytesPerElement = attribute.bytesPerElement;
  9278. // check for integer attributes (WebGL 2 only)
  9279. const integer = ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ) );
  9280. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9281. const data = geometryAttribute.data;
  9282. const stride = data.stride;
  9283. const offset = geometryAttribute.offset;
  9284. if ( data.isInstancedInterleavedBuffer ) {
  9285. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9286. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9287. }
  9288. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9289. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9290. }
  9291. } else {
  9292. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9293. enableAttribute( programAttribute.location + i );
  9294. }
  9295. }
  9296. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9297. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9298. vertexAttribPointer(
  9299. programAttribute.location + i,
  9300. size / programAttribute.locationSize,
  9301. type,
  9302. normalized,
  9303. stride * bytesPerElement,
  9304. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9305. integer
  9306. );
  9307. }
  9308. } else {
  9309. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9310. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9311. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9312. }
  9313. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9314. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9315. }
  9316. } else {
  9317. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9318. enableAttribute( programAttribute.location + i );
  9319. }
  9320. }
  9321. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9322. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9323. vertexAttribPointer(
  9324. programAttribute.location + i,
  9325. size / programAttribute.locationSize,
  9326. type,
  9327. normalized,
  9328. size * bytesPerElement,
  9329. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9330. integer
  9331. );
  9332. }
  9333. }
  9334. } else if ( materialDefaultAttributeValues !== undefined ) {
  9335. const value = materialDefaultAttributeValues[ name ];
  9336. if ( value !== undefined ) {
  9337. switch ( value.length ) {
  9338. case 2:
  9339. gl.vertexAttrib2fv( programAttribute.location, value );
  9340. break;
  9341. case 3:
  9342. gl.vertexAttrib3fv( programAttribute.location, value );
  9343. break;
  9344. case 4:
  9345. gl.vertexAttrib4fv( programAttribute.location, value );
  9346. break;
  9347. default:
  9348. gl.vertexAttrib1fv( programAttribute.location, value );
  9349. }
  9350. }
  9351. }
  9352. }
  9353. }
  9354. disableUnusedAttributes();
  9355. }
  9356. function dispose() {
  9357. reset();
  9358. for ( const geometryId in bindingStates ) {
  9359. const programMap = bindingStates[ geometryId ];
  9360. for ( const programId in programMap ) {
  9361. const stateMap = programMap[ programId ];
  9362. for ( const wireframe in stateMap ) {
  9363. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9364. delete stateMap[ wireframe ];
  9365. }
  9366. delete programMap[ programId ];
  9367. }
  9368. delete bindingStates[ geometryId ];
  9369. }
  9370. }
  9371. function releaseStatesOfGeometry( geometry ) {
  9372. if ( bindingStates[ geometry.id ] === undefined ) return;
  9373. const programMap = bindingStates[ geometry.id ];
  9374. for ( const programId in programMap ) {
  9375. const stateMap = programMap[ programId ];
  9376. for ( const wireframe in stateMap ) {
  9377. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9378. delete stateMap[ wireframe ];
  9379. }
  9380. delete programMap[ programId ];
  9381. }
  9382. delete bindingStates[ geometry.id ];
  9383. }
  9384. function releaseStatesOfProgram( program ) {
  9385. for ( const geometryId in bindingStates ) {
  9386. const programMap = bindingStates[ geometryId ];
  9387. if ( programMap[ program.id ] === undefined ) continue;
  9388. const stateMap = programMap[ program.id ];
  9389. for ( const wireframe in stateMap ) {
  9390. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9391. delete stateMap[ wireframe ];
  9392. }
  9393. delete programMap[ program.id ];
  9394. }
  9395. }
  9396. function reset() {
  9397. resetDefaultState();
  9398. forceUpdate = true;
  9399. if ( currentState === defaultState ) return;
  9400. currentState = defaultState;
  9401. bindVertexArrayObject( currentState.object );
  9402. }
  9403. // for backward-compatibility
  9404. function resetDefaultState() {
  9405. defaultState.geometry = null;
  9406. defaultState.program = null;
  9407. defaultState.wireframe = false;
  9408. }
  9409. return {
  9410. setup: setup,
  9411. reset: reset,
  9412. resetDefaultState: resetDefaultState,
  9413. dispose: dispose,
  9414. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9415. releaseStatesOfProgram: releaseStatesOfProgram,
  9416. initAttributes: initAttributes,
  9417. enableAttribute: enableAttribute,
  9418. disableUnusedAttributes: disableUnusedAttributes
  9419. };
  9420. }
  9421. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9422. const isWebGL2 = capabilities.isWebGL2;
  9423. let mode;
  9424. function setMode( value ) {
  9425. mode = value;
  9426. }
  9427. function render( start, count ) {
  9428. gl.drawArrays( mode, start, count );
  9429. info.update( count, mode, 1 );
  9430. }
  9431. function renderInstances( start, count, primcount ) {
  9432. if ( primcount === 0 ) return;
  9433. let extension, methodName;
  9434. if ( isWebGL2 ) {
  9435. extension = gl;
  9436. methodName = 'drawArraysInstanced';
  9437. } else {
  9438. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9439. methodName = 'drawArraysInstancedANGLE';
  9440. if ( extension === null ) {
  9441. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9442. return;
  9443. }
  9444. }
  9445. extension[ methodName ]( mode, start, count, primcount );
  9446. info.update( count, mode, primcount );
  9447. }
  9448. function renderMultiDraw( starts, counts, drawCount ) {
  9449. if ( drawCount === 0 ) return;
  9450. const extension = extensions.get( 'WEBGL_multi_draw' );
  9451. if ( extension === null ) {
  9452. for ( let i = 0; i < drawCount; i ++ ) {
  9453. this.render( starts[ i ], counts[ i ] );
  9454. }
  9455. } else {
  9456. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  9457. let elementCount = 0;
  9458. for ( let i = 0; i < drawCount; i ++ ) {
  9459. elementCount += counts[ i ];
  9460. }
  9461. info.update( elementCount, mode, 1 );
  9462. }
  9463. }
  9464. //
  9465. this.setMode = setMode;
  9466. this.render = render;
  9467. this.renderInstances = renderInstances;
  9468. this.renderMultiDraw = renderMultiDraw;
  9469. }
  9470. function WebGLCapabilities( gl, extensions, parameters ) {
  9471. let maxAnisotropy;
  9472. function getMaxAnisotropy() {
  9473. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9474. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9475. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9476. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9477. } else {
  9478. maxAnisotropy = 0;
  9479. }
  9480. return maxAnisotropy;
  9481. }
  9482. function getMaxPrecision( precision ) {
  9483. if ( precision === 'highp' ) {
  9484. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9485. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9486. return 'highp';
  9487. }
  9488. precision = 'mediump';
  9489. }
  9490. if ( precision === 'mediump' ) {
  9491. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9492. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9493. return 'mediump';
  9494. }
  9495. }
  9496. return 'lowp';
  9497. }
  9498. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9499. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9500. const maxPrecision = getMaxPrecision( precision );
  9501. if ( maxPrecision !== precision ) {
  9502. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9503. precision = maxPrecision;
  9504. }
  9505. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9506. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9507. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9508. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9509. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9510. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9511. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9512. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9513. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9514. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9515. const vertexTextures = maxVertexTextures > 0;
  9516. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9517. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9518. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  9519. return {
  9520. isWebGL2: isWebGL2,
  9521. drawBuffers: drawBuffers,
  9522. getMaxAnisotropy: getMaxAnisotropy,
  9523. getMaxPrecision: getMaxPrecision,
  9524. precision: precision,
  9525. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9526. maxTextures: maxTextures,
  9527. maxVertexTextures: maxVertexTextures,
  9528. maxTextureSize: maxTextureSize,
  9529. maxCubemapSize: maxCubemapSize,
  9530. maxAttributes: maxAttributes,
  9531. maxVertexUniforms: maxVertexUniforms,
  9532. maxVaryings: maxVaryings,
  9533. maxFragmentUniforms: maxFragmentUniforms,
  9534. vertexTextures: vertexTextures,
  9535. floatFragmentTextures: floatFragmentTextures,
  9536. floatVertexTextures: floatVertexTextures,
  9537. maxSamples: maxSamples
  9538. };
  9539. }
  9540. function WebGLClipping( properties ) {
  9541. const scope = this;
  9542. let globalState = null,
  9543. numGlobalPlanes = 0,
  9544. localClippingEnabled = false,
  9545. renderingShadows = false;
  9546. const plane = new Plane(),
  9547. viewNormalMatrix = new Matrix3(),
  9548. uniform = { value: null, needsUpdate: false };
  9549. this.uniform = uniform;
  9550. this.numPlanes = 0;
  9551. this.numIntersection = 0;
  9552. this.init = function ( planes, enableLocalClipping ) {
  9553. const enabled =
  9554. planes.length !== 0 ||
  9555. enableLocalClipping ||
  9556. // enable state of previous frame - the clipping code has to
  9557. // run another frame in order to reset the state:
  9558. numGlobalPlanes !== 0 ||
  9559. localClippingEnabled;
  9560. localClippingEnabled = enableLocalClipping;
  9561. numGlobalPlanes = planes.length;
  9562. return enabled;
  9563. };
  9564. this.beginShadows = function () {
  9565. renderingShadows = true;
  9566. projectPlanes( null );
  9567. };
  9568. this.endShadows = function () {
  9569. renderingShadows = false;
  9570. };
  9571. this.setGlobalState = function ( planes, camera ) {
  9572. globalState = projectPlanes( planes, camera, 0 );
  9573. };
  9574. this.setState = function ( material, camera, useCache ) {
  9575. const planes = material.clippingPlanes,
  9576. clipIntersection = material.clipIntersection,
  9577. clipShadows = material.clipShadows;
  9578. const materialProperties = properties.get( material );
  9579. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9580. // there's no local clipping
  9581. if ( renderingShadows ) {
  9582. // there's no global clipping
  9583. projectPlanes( null );
  9584. } else {
  9585. resetGlobalState();
  9586. }
  9587. } else {
  9588. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9589. lGlobal = nGlobal * 4;
  9590. let dstArray = materialProperties.clippingState || null;
  9591. uniform.value = dstArray; // ensure unique state
  9592. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9593. for ( let i = 0; i !== lGlobal; ++ i ) {
  9594. dstArray[ i ] = globalState[ i ];
  9595. }
  9596. materialProperties.clippingState = dstArray;
  9597. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9598. this.numPlanes += nGlobal;
  9599. }
  9600. };
  9601. function resetGlobalState() {
  9602. if ( uniform.value !== globalState ) {
  9603. uniform.value = globalState;
  9604. uniform.needsUpdate = numGlobalPlanes > 0;
  9605. }
  9606. scope.numPlanes = numGlobalPlanes;
  9607. scope.numIntersection = 0;
  9608. }
  9609. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9610. const nPlanes = planes !== null ? planes.length : 0;
  9611. let dstArray = null;
  9612. if ( nPlanes !== 0 ) {
  9613. dstArray = uniform.value;
  9614. if ( skipTransform !== true || dstArray === null ) {
  9615. const flatSize = dstOffset + nPlanes * 4,
  9616. viewMatrix = camera.matrixWorldInverse;
  9617. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9618. if ( dstArray === null || dstArray.length < flatSize ) {
  9619. dstArray = new Float32Array( flatSize );
  9620. }
  9621. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9622. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9623. plane.normal.toArray( dstArray, i4 );
  9624. dstArray[ i4 + 3 ] = plane.constant;
  9625. }
  9626. }
  9627. uniform.value = dstArray;
  9628. uniform.needsUpdate = true;
  9629. }
  9630. scope.numPlanes = nPlanes;
  9631. scope.numIntersection = 0;
  9632. return dstArray;
  9633. }
  9634. }
  9635. function WebGLCubeMaps( renderer ) {
  9636. let cubemaps = new WeakMap();
  9637. function mapTextureMapping( texture, mapping ) {
  9638. if ( mapping === EquirectangularReflectionMapping ) {
  9639. texture.mapping = CubeReflectionMapping;
  9640. } else if ( mapping === EquirectangularRefractionMapping ) {
  9641. texture.mapping = CubeRefractionMapping;
  9642. }
  9643. return texture;
  9644. }
  9645. function get( texture ) {
  9646. if ( texture && texture.isTexture ) {
  9647. const mapping = texture.mapping;
  9648. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9649. if ( cubemaps.has( texture ) ) {
  9650. const cubemap = cubemaps.get( texture ).texture;
  9651. return mapTextureMapping( cubemap, texture.mapping );
  9652. } else {
  9653. const image = texture.image;
  9654. if ( image && image.height > 0 ) {
  9655. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9656. renderTarget.fromEquirectangularTexture( renderer, texture );
  9657. cubemaps.set( texture, renderTarget );
  9658. texture.addEventListener( 'dispose', onTextureDispose );
  9659. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9660. } else {
  9661. // image not yet ready. try the conversion next frame
  9662. return null;
  9663. }
  9664. }
  9665. }
  9666. }
  9667. return texture;
  9668. }
  9669. function onTextureDispose( event ) {
  9670. const texture = event.target;
  9671. texture.removeEventListener( 'dispose', onTextureDispose );
  9672. const cubemap = cubemaps.get( texture );
  9673. if ( cubemap !== undefined ) {
  9674. cubemaps.delete( texture );
  9675. cubemap.dispose();
  9676. }
  9677. }
  9678. function dispose() {
  9679. cubemaps = new WeakMap();
  9680. }
  9681. return {
  9682. get: get,
  9683. dispose: dispose
  9684. };
  9685. }
  9686. class OrthographicCamera extends Camera {
  9687. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9688. super();
  9689. this.isOrthographicCamera = true;
  9690. this.type = 'OrthographicCamera';
  9691. this.zoom = 1;
  9692. this.view = null;
  9693. this.left = left;
  9694. this.right = right;
  9695. this.top = top;
  9696. this.bottom = bottom;
  9697. this.near = near;
  9698. this.far = far;
  9699. this.updateProjectionMatrix();
  9700. }
  9701. copy( source, recursive ) {
  9702. super.copy( source, recursive );
  9703. this.left = source.left;
  9704. this.right = source.right;
  9705. this.top = source.top;
  9706. this.bottom = source.bottom;
  9707. this.near = source.near;
  9708. this.far = source.far;
  9709. this.zoom = source.zoom;
  9710. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9711. return this;
  9712. }
  9713. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9714. if ( this.view === null ) {
  9715. this.view = {
  9716. enabled: true,
  9717. fullWidth: 1,
  9718. fullHeight: 1,
  9719. offsetX: 0,
  9720. offsetY: 0,
  9721. width: 1,
  9722. height: 1
  9723. };
  9724. }
  9725. this.view.enabled = true;
  9726. this.view.fullWidth = fullWidth;
  9727. this.view.fullHeight = fullHeight;
  9728. this.view.offsetX = x;
  9729. this.view.offsetY = y;
  9730. this.view.width = width;
  9731. this.view.height = height;
  9732. this.updateProjectionMatrix();
  9733. }
  9734. clearViewOffset() {
  9735. if ( this.view !== null ) {
  9736. this.view.enabled = false;
  9737. }
  9738. this.updateProjectionMatrix();
  9739. }
  9740. updateProjectionMatrix() {
  9741. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9742. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9743. const cx = ( this.right + this.left ) / 2;
  9744. const cy = ( this.top + this.bottom ) / 2;
  9745. let left = cx - dx;
  9746. let right = cx + dx;
  9747. let top = cy + dy;
  9748. let bottom = cy - dy;
  9749. if ( this.view !== null && this.view.enabled ) {
  9750. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9751. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9752. left += scaleW * this.view.offsetX;
  9753. right = left + scaleW * this.view.width;
  9754. top -= scaleH * this.view.offsetY;
  9755. bottom = top - scaleH * this.view.height;
  9756. }
  9757. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9758. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9759. }
  9760. toJSON( meta ) {
  9761. const data = super.toJSON( meta );
  9762. data.object.zoom = this.zoom;
  9763. data.object.left = this.left;
  9764. data.object.right = this.right;
  9765. data.object.top = this.top;
  9766. data.object.bottom = this.bottom;
  9767. data.object.near = this.near;
  9768. data.object.far = this.far;
  9769. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9770. return data;
  9771. }
  9772. }
  9773. const LOD_MIN = 4;
  9774. // The standard deviations (radians) associated with the extra mips. These are
  9775. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9776. // geometric shadowing function. These sigma values squared must match the
  9777. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9778. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9779. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9780. // samples and exit early, but not recompile the shader.
  9781. const MAX_SAMPLES = 20;
  9782. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9783. const _clearColor = /*@__PURE__*/ new Color();
  9784. let _oldTarget = null;
  9785. let _oldActiveCubeFace = 0;
  9786. let _oldActiveMipmapLevel = 0;
  9787. // Golden Ratio
  9788. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9789. const INV_PHI = 1 / PHI;
  9790. // Vertices of a dodecahedron (except the opposites, which represent the
  9791. // same axis), used as axis directions evenly spread on a sphere.
  9792. const _axisDirections = [
  9793. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9794. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9795. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9796. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9797. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9798. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9799. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9800. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9801. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9802. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9803. /**
  9804. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9805. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9806. * blur to be quickly accessed based on material roughness. It is packed into a
  9807. * special CubeUV format that allows us to perform custom interpolation so that
  9808. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9809. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9810. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9811. * higher roughness levels. In this way we maintain resolution to smoothly
  9812. * interpolate diffuse lighting while limiting sampling computation.
  9813. *
  9814. * Paper: Fast, Accurate Image-Based Lighting
  9815. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9816. */
  9817. class PMREMGenerator {
  9818. constructor( renderer ) {
  9819. this._renderer = renderer;
  9820. this._pingPongRenderTarget = null;
  9821. this._lodMax = 0;
  9822. this._cubeSize = 0;
  9823. this._lodPlanes = [];
  9824. this._sizeLods = [];
  9825. this._sigmas = [];
  9826. this._blurMaterial = null;
  9827. this._cubemapMaterial = null;
  9828. this._equirectMaterial = null;
  9829. this._compileMaterial( this._blurMaterial );
  9830. }
  9831. /**
  9832. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9833. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9834. * in radians to be applied to the scene before PMREM generation. Optional near
  9835. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9836. * is placed at the origin).
  9837. */
  9838. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9839. _oldTarget = this._renderer.getRenderTarget();
  9840. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9841. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9842. this._setSize( 256 );
  9843. const cubeUVRenderTarget = this._allocateTargets();
  9844. cubeUVRenderTarget.depthBuffer = true;
  9845. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9846. if ( sigma > 0 ) {
  9847. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9848. }
  9849. this._applyPMREM( cubeUVRenderTarget );
  9850. this._cleanup( cubeUVRenderTarget );
  9851. return cubeUVRenderTarget;
  9852. }
  9853. /**
  9854. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9855. * or HDR. The ideal input image size is 1k (1024 x 512),
  9856. * as this matches best with the 256 x 256 cubemap output.
  9857. */
  9858. fromEquirectangular( equirectangular, renderTarget = null ) {
  9859. return this._fromTexture( equirectangular, renderTarget );
  9860. }
  9861. /**
  9862. * Generates a PMREM from an cubemap texture, which can be either LDR
  9863. * or HDR. The ideal input cube size is 256 x 256,
  9864. * as this matches best with the 256 x 256 cubemap output.
  9865. */
  9866. fromCubemap( cubemap, renderTarget = null ) {
  9867. return this._fromTexture( cubemap, renderTarget );
  9868. }
  9869. /**
  9870. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9871. * your texture's network fetch for increased concurrency.
  9872. */
  9873. compileCubemapShader() {
  9874. if ( this._cubemapMaterial === null ) {
  9875. this._cubemapMaterial = _getCubemapMaterial();
  9876. this._compileMaterial( this._cubemapMaterial );
  9877. }
  9878. }
  9879. /**
  9880. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9881. * your texture's network fetch for increased concurrency.
  9882. */
  9883. compileEquirectangularShader() {
  9884. if ( this._equirectMaterial === null ) {
  9885. this._equirectMaterial = _getEquirectMaterial();
  9886. this._compileMaterial( this._equirectMaterial );
  9887. }
  9888. }
  9889. /**
  9890. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9891. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9892. * one of them will cause any others to also become unusable.
  9893. */
  9894. dispose() {
  9895. this._dispose();
  9896. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9897. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9898. }
  9899. // private interface
  9900. _setSize( cubeSize ) {
  9901. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9902. this._cubeSize = Math.pow( 2, this._lodMax );
  9903. }
  9904. _dispose() {
  9905. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9906. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9907. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9908. this._lodPlanes[ i ].dispose();
  9909. }
  9910. }
  9911. _cleanup( outputTarget ) {
  9912. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  9913. outputTarget.scissorTest = false;
  9914. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9915. }
  9916. _fromTexture( texture, renderTarget ) {
  9917. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9918. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9919. } else { // Equirectangular
  9920. this._setSize( texture.image.width / 4 );
  9921. }
  9922. _oldTarget = this._renderer.getRenderTarget();
  9923. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9924. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9925. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9926. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9927. this._applyPMREM( cubeUVRenderTarget );
  9928. this._cleanup( cubeUVRenderTarget );
  9929. return cubeUVRenderTarget;
  9930. }
  9931. _allocateTargets() {
  9932. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9933. const height = 4 * this._cubeSize;
  9934. const params = {
  9935. magFilter: LinearFilter,
  9936. minFilter: LinearFilter,
  9937. generateMipmaps: false,
  9938. type: HalfFloatType,
  9939. format: RGBAFormat,
  9940. colorSpace: LinearSRGBColorSpace,
  9941. depthBuffer: false
  9942. };
  9943. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9944. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9945. if ( this._pingPongRenderTarget !== null ) {
  9946. this._dispose();
  9947. }
  9948. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9949. const { _lodMax } = this;
  9950. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9951. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9952. }
  9953. return cubeUVRenderTarget;
  9954. }
  9955. _compileMaterial( material ) {
  9956. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9957. this._renderer.compile( tmpMesh, _flatCamera );
  9958. }
  9959. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9960. const fov = 90;
  9961. const aspect = 1;
  9962. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9963. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9964. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9965. const renderer = this._renderer;
  9966. const originalAutoClear = renderer.autoClear;
  9967. const toneMapping = renderer.toneMapping;
  9968. renderer.getClearColor( _clearColor );
  9969. renderer.toneMapping = NoToneMapping;
  9970. renderer.autoClear = false;
  9971. const backgroundMaterial = new MeshBasicMaterial( {
  9972. name: 'PMREM.Background',
  9973. side: BackSide,
  9974. depthWrite: false,
  9975. depthTest: false,
  9976. } );
  9977. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9978. let useSolidColor = false;
  9979. const background = scene.background;
  9980. if ( background ) {
  9981. if ( background.isColor ) {
  9982. backgroundMaterial.color.copy( background );
  9983. scene.background = null;
  9984. useSolidColor = true;
  9985. }
  9986. } else {
  9987. backgroundMaterial.color.copy( _clearColor );
  9988. useSolidColor = true;
  9989. }
  9990. for ( let i = 0; i < 6; i ++ ) {
  9991. const col = i % 3;
  9992. if ( col === 0 ) {
  9993. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9994. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9995. } else if ( col === 1 ) {
  9996. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9997. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9998. } else {
  9999. cubeCamera.up.set( 0, upSign[ i ], 0 );
  10000. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  10001. }
  10002. const size = this._cubeSize;
  10003. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  10004. renderer.setRenderTarget( cubeUVRenderTarget );
  10005. if ( useSolidColor ) {
  10006. renderer.render( backgroundBox, cubeCamera );
  10007. }
  10008. renderer.render( scene, cubeCamera );
  10009. }
  10010. backgroundBox.geometry.dispose();
  10011. backgroundBox.material.dispose();
  10012. renderer.toneMapping = toneMapping;
  10013. renderer.autoClear = originalAutoClear;
  10014. scene.background = background;
  10015. }
  10016. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  10017. const renderer = this._renderer;
  10018. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  10019. if ( isCubeTexture ) {
  10020. if ( this._cubemapMaterial === null ) {
  10021. this._cubemapMaterial = _getCubemapMaterial();
  10022. }
  10023. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  10024. } else {
  10025. if ( this._equirectMaterial === null ) {
  10026. this._equirectMaterial = _getEquirectMaterial();
  10027. }
  10028. }
  10029. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  10030. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  10031. const uniforms = material.uniforms;
  10032. uniforms[ 'envMap' ].value = texture;
  10033. const size = this._cubeSize;
  10034. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  10035. renderer.setRenderTarget( cubeUVRenderTarget );
  10036. renderer.render( mesh, _flatCamera );
  10037. }
  10038. _applyPMREM( cubeUVRenderTarget ) {
  10039. const renderer = this._renderer;
  10040. const autoClear = renderer.autoClear;
  10041. renderer.autoClear = false;
  10042. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  10043. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  10044. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  10045. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  10046. }
  10047. renderer.autoClear = autoClear;
  10048. }
  10049. /**
  10050. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  10051. * vertically and horizontally, but this breaks down on a cube. Here we apply
  10052. * the blur latitudinally (around the poles), and then longitudinally (towards
  10053. * the poles) to approximate the orthogonally-separable blur. It is least
  10054. * accurate at the poles, but still does a decent job.
  10055. */
  10056. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  10057. const pingPongRenderTarget = this._pingPongRenderTarget;
  10058. this._halfBlur(
  10059. cubeUVRenderTarget,
  10060. pingPongRenderTarget,
  10061. lodIn,
  10062. lodOut,
  10063. sigma,
  10064. 'latitudinal',
  10065. poleAxis );
  10066. this._halfBlur(
  10067. pingPongRenderTarget,
  10068. cubeUVRenderTarget,
  10069. lodOut,
  10070. lodOut,
  10071. sigma,
  10072. 'longitudinal',
  10073. poleAxis );
  10074. }
  10075. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10076. const renderer = this._renderer;
  10077. const blurMaterial = this._blurMaterial;
  10078. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10079. console.error(
  10080. 'blur direction must be either latitudinal or longitudinal!' );
  10081. }
  10082. // Number of standard deviations at which to cut off the discrete approximation.
  10083. const STANDARD_DEVIATIONS = 3;
  10084. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  10085. const blurUniforms = blurMaterial.uniforms;
  10086. const pixels = this._sizeLods[ lodIn ] - 1;
  10087. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10088. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10089. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10090. if ( samples > MAX_SAMPLES ) {
  10091. console.warn( `sigmaRadians, ${
  10092. sigmaRadians}, is too large and will clip, as it requested ${
  10093. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10094. }
  10095. const weights = [];
  10096. let sum = 0;
  10097. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10098. const x = i / sigmaPixels;
  10099. const weight = Math.exp( - x * x / 2 );
  10100. weights.push( weight );
  10101. if ( i === 0 ) {
  10102. sum += weight;
  10103. } else if ( i < samples ) {
  10104. sum += 2 * weight;
  10105. }
  10106. }
  10107. for ( let i = 0; i < weights.length; i ++ ) {
  10108. weights[ i ] = weights[ i ] / sum;
  10109. }
  10110. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10111. blurUniforms[ 'samples' ].value = samples;
  10112. blurUniforms[ 'weights' ].value = weights;
  10113. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10114. if ( poleAxis ) {
  10115. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10116. }
  10117. const { _lodMax } = this;
  10118. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10119. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10120. const outputSize = this._sizeLods[ lodOut ];
  10121. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10122. const y = 4 * ( this._cubeSize - outputSize );
  10123. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10124. renderer.setRenderTarget( targetOut );
  10125. renderer.render( blurMesh, _flatCamera );
  10126. }
  10127. }
  10128. function _createPlanes( lodMax ) {
  10129. const lodPlanes = [];
  10130. const sizeLods = [];
  10131. const sigmas = [];
  10132. let lod = lodMax;
  10133. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10134. for ( let i = 0; i < totalLods; i ++ ) {
  10135. const sizeLod = Math.pow( 2, lod );
  10136. sizeLods.push( sizeLod );
  10137. let sigma = 1.0 / sizeLod;
  10138. if ( i > lodMax - LOD_MIN ) {
  10139. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10140. } else if ( i === 0 ) {
  10141. sigma = 0;
  10142. }
  10143. sigmas.push( sigma );
  10144. const texelSize = 1.0 / ( sizeLod - 2 );
  10145. const min = - texelSize;
  10146. const max = 1 + texelSize;
  10147. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10148. const cubeFaces = 6;
  10149. const vertices = 6;
  10150. const positionSize = 3;
  10151. const uvSize = 2;
  10152. const faceIndexSize = 1;
  10153. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10154. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10155. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10156. for ( let face = 0; face < cubeFaces; face ++ ) {
  10157. const x = ( face % 3 ) * 2 / 3 - 1;
  10158. const y = face > 2 ? 0 : - 1;
  10159. const coordinates = [
  10160. x, y, 0,
  10161. x + 2 / 3, y, 0,
  10162. x + 2 / 3, y + 1, 0,
  10163. x, y, 0,
  10164. x + 2 / 3, y + 1, 0,
  10165. x, y + 1, 0
  10166. ];
  10167. position.set( coordinates, positionSize * vertices * face );
  10168. uv.set( uv1, uvSize * vertices * face );
  10169. const fill = [ face, face, face, face, face, face ];
  10170. faceIndex.set( fill, faceIndexSize * vertices * face );
  10171. }
  10172. const planes = new BufferGeometry();
  10173. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10174. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10175. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10176. lodPlanes.push( planes );
  10177. if ( lod > LOD_MIN ) {
  10178. lod --;
  10179. }
  10180. }
  10181. return { lodPlanes, sizeLods, sigmas };
  10182. }
  10183. function _createRenderTarget( width, height, params ) {
  10184. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10185. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10186. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10187. cubeUVRenderTarget.scissorTest = true;
  10188. return cubeUVRenderTarget;
  10189. }
  10190. function _setViewport( target, x, y, width, height ) {
  10191. target.viewport.set( x, y, width, height );
  10192. target.scissor.set( x, y, width, height );
  10193. }
  10194. function _getBlurShader( lodMax, width, height ) {
  10195. const weights = new Float32Array( MAX_SAMPLES );
  10196. const poleAxis = new Vector3( 0, 1, 0 );
  10197. const shaderMaterial = new ShaderMaterial( {
  10198. name: 'SphericalGaussianBlur',
  10199. defines: {
  10200. 'n': MAX_SAMPLES,
  10201. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10202. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10203. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10204. },
  10205. uniforms: {
  10206. 'envMap': { value: null },
  10207. 'samples': { value: 1 },
  10208. 'weights': { value: weights },
  10209. 'latitudinal': { value: false },
  10210. 'dTheta': { value: 0 },
  10211. 'mipInt': { value: 0 },
  10212. 'poleAxis': { value: poleAxis }
  10213. },
  10214. vertexShader: _getCommonVertexShader(),
  10215. fragmentShader: /* glsl */`
  10216. precision mediump float;
  10217. precision mediump int;
  10218. varying vec3 vOutputDirection;
  10219. uniform sampler2D envMap;
  10220. uniform int samples;
  10221. uniform float weights[ n ];
  10222. uniform bool latitudinal;
  10223. uniform float dTheta;
  10224. uniform float mipInt;
  10225. uniform vec3 poleAxis;
  10226. #define ENVMAP_TYPE_CUBE_UV
  10227. #include <cube_uv_reflection_fragment>
  10228. vec3 getSample( float theta, vec3 axis ) {
  10229. float cosTheta = cos( theta );
  10230. // Rodrigues' axis-angle rotation
  10231. vec3 sampleDirection = vOutputDirection * cosTheta
  10232. + cross( axis, vOutputDirection ) * sin( theta )
  10233. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10234. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10235. }
  10236. void main() {
  10237. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10238. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10239. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10240. }
  10241. axis = normalize( axis );
  10242. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10243. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10244. for ( int i = 1; i < n; i++ ) {
  10245. if ( i >= samples ) {
  10246. break;
  10247. }
  10248. float theta = dTheta * float( i );
  10249. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10250. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10251. }
  10252. }
  10253. `,
  10254. blending: NoBlending,
  10255. depthTest: false,
  10256. depthWrite: false
  10257. } );
  10258. return shaderMaterial;
  10259. }
  10260. function _getEquirectMaterial() {
  10261. return new ShaderMaterial( {
  10262. name: 'EquirectangularToCubeUV',
  10263. uniforms: {
  10264. 'envMap': { value: null }
  10265. },
  10266. vertexShader: _getCommonVertexShader(),
  10267. fragmentShader: /* glsl */`
  10268. precision mediump float;
  10269. precision mediump int;
  10270. varying vec3 vOutputDirection;
  10271. uniform sampler2D envMap;
  10272. #include <common>
  10273. void main() {
  10274. vec3 outputDirection = normalize( vOutputDirection );
  10275. vec2 uv = equirectUv( outputDirection );
  10276. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10277. }
  10278. `,
  10279. blending: NoBlending,
  10280. depthTest: false,
  10281. depthWrite: false
  10282. } );
  10283. }
  10284. function _getCubemapMaterial() {
  10285. return new ShaderMaterial( {
  10286. name: 'CubemapToCubeUV',
  10287. uniforms: {
  10288. 'envMap': { value: null },
  10289. 'flipEnvMap': { value: - 1 }
  10290. },
  10291. vertexShader: _getCommonVertexShader(),
  10292. fragmentShader: /* glsl */`
  10293. precision mediump float;
  10294. precision mediump int;
  10295. uniform float flipEnvMap;
  10296. varying vec3 vOutputDirection;
  10297. uniform samplerCube envMap;
  10298. void main() {
  10299. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10300. }
  10301. `,
  10302. blending: NoBlending,
  10303. depthTest: false,
  10304. depthWrite: false
  10305. } );
  10306. }
  10307. function _getCommonVertexShader() {
  10308. return /* glsl */`
  10309. precision mediump float;
  10310. precision mediump int;
  10311. attribute float faceIndex;
  10312. varying vec3 vOutputDirection;
  10313. // RH coordinate system; PMREM face-indexing convention
  10314. vec3 getDirection( vec2 uv, float face ) {
  10315. uv = 2.0 * uv - 1.0;
  10316. vec3 direction = vec3( uv, 1.0 );
  10317. if ( face == 0.0 ) {
  10318. direction = direction.zyx; // ( 1, v, u ) pos x
  10319. } else if ( face == 1.0 ) {
  10320. direction = direction.xzy;
  10321. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10322. } else if ( face == 2.0 ) {
  10323. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10324. } else if ( face == 3.0 ) {
  10325. direction = direction.zyx;
  10326. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10327. } else if ( face == 4.0 ) {
  10328. direction = direction.xzy;
  10329. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10330. } else if ( face == 5.0 ) {
  10331. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10332. }
  10333. return direction;
  10334. }
  10335. void main() {
  10336. vOutputDirection = getDirection( uv, faceIndex );
  10337. gl_Position = vec4( position, 1.0 );
  10338. }
  10339. `;
  10340. }
  10341. function WebGLCubeUVMaps( renderer ) {
  10342. let cubeUVmaps = new WeakMap();
  10343. let pmremGenerator = null;
  10344. function get( texture ) {
  10345. if ( texture && texture.isTexture ) {
  10346. const mapping = texture.mapping;
  10347. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10348. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10349. // equirect/cube map to cubeUV conversion
  10350. if ( isEquirectMap || isCubeMap ) {
  10351. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10352. texture.needsPMREMUpdate = false;
  10353. let renderTarget = cubeUVmaps.get( texture );
  10354. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10355. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10356. cubeUVmaps.set( texture, renderTarget );
  10357. return renderTarget.texture;
  10358. } else {
  10359. if ( cubeUVmaps.has( texture ) ) {
  10360. return cubeUVmaps.get( texture ).texture;
  10361. } else {
  10362. const image = texture.image;
  10363. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10364. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10365. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10366. cubeUVmaps.set( texture, renderTarget );
  10367. texture.addEventListener( 'dispose', onTextureDispose );
  10368. return renderTarget.texture;
  10369. } else {
  10370. // image not yet ready. try the conversion next frame
  10371. return null;
  10372. }
  10373. }
  10374. }
  10375. }
  10376. }
  10377. return texture;
  10378. }
  10379. function isCubeTextureComplete( image ) {
  10380. let count = 0;
  10381. const length = 6;
  10382. for ( let i = 0; i < length; i ++ ) {
  10383. if ( image[ i ] !== undefined ) count ++;
  10384. }
  10385. return count === length;
  10386. }
  10387. function onTextureDispose( event ) {
  10388. const texture = event.target;
  10389. texture.removeEventListener( 'dispose', onTextureDispose );
  10390. const cubemapUV = cubeUVmaps.get( texture );
  10391. if ( cubemapUV !== undefined ) {
  10392. cubeUVmaps.delete( texture );
  10393. cubemapUV.dispose();
  10394. }
  10395. }
  10396. function dispose() {
  10397. cubeUVmaps = new WeakMap();
  10398. if ( pmremGenerator !== null ) {
  10399. pmremGenerator.dispose();
  10400. pmremGenerator = null;
  10401. }
  10402. }
  10403. return {
  10404. get: get,
  10405. dispose: dispose
  10406. };
  10407. }
  10408. function WebGLExtensions( gl ) {
  10409. const extensions = {};
  10410. function getExtension( name ) {
  10411. if ( extensions[ name ] !== undefined ) {
  10412. return extensions[ name ];
  10413. }
  10414. let extension;
  10415. switch ( name ) {
  10416. case 'WEBGL_depth_texture':
  10417. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10418. break;
  10419. case 'EXT_texture_filter_anisotropic':
  10420. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10421. break;
  10422. case 'WEBGL_compressed_texture_s3tc':
  10423. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10424. break;
  10425. case 'WEBGL_compressed_texture_pvrtc':
  10426. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10427. break;
  10428. default:
  10429. extension = gl.getExtension( name );
  10430. }
  10431. extensions[ name ] = extension;
  10432. return extension;
  10433. }
  10434. return {
  10435. has: function ( name ) {
  10436. return getExtension( name ) !== null;
  10437. },
  10438. init: function ( capabilities ) {
  10439. if ( capabilities.isWebGL2 ) {
  10440. getExtension( 'EXT_color_buffer_float' );
  10441. getExtension( 'WEBGL_clip_cull_distance' );
  10442. } else {
  10443. getExtension( 'WEBGL_depth_texture' );
  10444. getExtension( 'OES_texture_float' );
  10445. getExtension( 'OES_texture_half_float' );
  10446. getExtension( 'OES_texture_half_float_linear' );
  10447. getExtension( 'OES_standard_derivatives' );
  10448. getExtension( 'OES_element_index_uint' );
  10449. getExtension( 'OES_vertex_array_object' );
  10450. getExtension( 'ANGLE_instanced_arrays' );
  10451. }
  10452. getExtension( 'OES_texture_float_linear' );
  10453. getExtension( 'EXT_color_buffer_half_float' );
  10454. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10455. },
  10456. get: function ( name ) {
  10457. const extension = getExtension( name );
  10458. if ( extension === null ) {
  10459. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10460. }
  10461. return extension;
  10462. }
  10463. };
  10464. }
  10465. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10466. const geometries = {};
  10467. const wireframeAttributes = new WeakMap();
  10468. function onGeometryDispose( event ) {
  10469. const geometry = event.target;
  10470. if ( geometry.index !== null ) {
  10471. attributes.remove( geometry.index );
  10472. }
  10473. for ( const name in geometry.attributes ) {
  10474. attributes.remove( geometry.attributes[ name ] );
  10475. }
  10476. for ( const name in geometry.morphAttributes ) {
  10477. const array = geometry.morphAttributes[ name ];
  10478. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10479. attributes.remove( array[ i ] );
  10480. }
  10481. }
  10482. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10483. delete geometries[ geometry.id ];
  10484. const attribute = wireframeAttributes.get( geometry );
  10485. if ( attribute ) {
  10486. attributes.remove( attribute );
  10487. wireframeAttributes.delete( geometry );
  10488. }
  10489. bindingStates.releaseStatesOfGeometry( geometry );
  10490. if ( geometry.isInstancedBufferGeometry === true ) {
  10491. delete geometry._maxInstanceCount;
  10492. }
  10493. //
  10494. info.memory.geometries --;
  10495. }
  10496. function get( object, geometry ) {
  10497. if ( geometries[ geometry.id ] === true ) return geometry;
  10498. geometry.addEventListener( 'dispose', onGeometryDispose );
  10499. geometries[ geometry.id ] = true;
  10500. info.memory.geometries ++;
  10501. return geometry;
  10502. }
  10503. function update( geometry ) {
  10504. const geometryAttributes = geometry.attributes;
  10505. // Updating index buffer in VAO now. See WebGLBindingStates.
  10506. for ( const name in geometryAttributes ) {
  10507. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10508. }
  10509. // morph targets
  10510. const morphAttributes = geometry.morphAttributes;
  10511. for ( const name in morphAttributes ) {
  10512. const array = morphAttributes[ name ];
  10513. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10514. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10515. }
  10516. }
  10517. }
  10518. function updateWireframeAttribute( geometry ) {
  10519. const indices = [];
  10520. const geometryIndex = geometry.index;
  10521. const geometryPosition = geometry.attributes.position;
  10522. let version = 0;
  10523. if ( geometryIndex !== null ) {
  10524. const array = geometryIndex.array;
  10525. version = geometryIndex.version;
  10526. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10527. const a = array[ i + 0 ];
  10528. const b = array[ i + 1 ];
  10529. const c = array[ i + 2 ];
  10530. indices.push( a, b, b, c, c, a );
  10531. }
  10532. } else if ( geometryPosition !== undefined ) {
  10533. const array = geometryPosition.array;
  10534. version = geometryPosition.version;
  10535. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10536. const a = i + 0;
  10537. const b = i + 1;
  10538. const c = i + 2;
  10539. indices.push( a, b, b, c, c, a );
  10540. }
  10541. } else {
  10542. return;
  10543. }
  10544. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10545. attribute.version = version;
  10546. // Updating index buffer in VAO now. See WebGLBindingStates
  10547. //
  10548. const previousAttribute = wireframeAttributes.get( geometry );
  10549. if ( previousAttribute ) attributes.remove( previousAttribute );
  10550. //
  10551. wireframeAttributes.set( geometry, attribute );
  10552. }
  10553. function getWireframeAttribute( geometry ) {
  10554. const currentAttribute = wireframeAttributes.get( geometry );
  10555. if ( currentAttribute ) {
  10556. const geometryIndex = geometry.index;
  10557. if ( geometryIndex !== null ) {
  10558. // if the attribute is obsolete, create a new one
  10559. if ( currentAttribute.version < geometryIndex.version ) {
  10560. updateWireframeAttribute( geometry );
  10561. }
  10562. }
  10563. } else {
  10564. updateWireframeAttribute( geometry );
  10565. }
  10566. return wireframeAttributes.get( geometry );
  10567. }
  10568. return {
  10569. get: get,
  10570. update: update,
  10571. getWireframeAttribute: getWireframeAttribute
  10572. };
  10573. }
  10574. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10575. const isWebGL2 = capabilities.isWebGL2;
  10576. let mode;
  10577. function setMode( value ) {
  10578. mode = value;
  10579. }
  10580. let type, bytesPerElement;
  10581. function setIndex( value ) {
  10582. type = value.type;
  10583. bytesPerElement = value.bytesPerElement;
  10584. }
  10585. function render( start, count ) {
  10586. gl.drawElements( mode, count, type, start * bytesPerElement );
  10587. info.update( count, mode, 1 );
  10588. }
  10589. function renderInstances( start, count, primcount ) {
  10590. if ( primcount === 0 ) return;
  10591. let extension, methodName;
  10592. if ( isWebGL2 ) {
  10593. extension = gl;
  10594. methodName = 'drawElementsInstanced';
  10595. } else {
  10596. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10597. methodName = 'drawElementsInstancedANGLE';
  10598. if ( extension === null ) {
  10599. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10600. return;
  10601. }
  10602. }
  10603. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10604. info.update( count, mode, primcount );
  10605. }
  10606. function renderMultiDraw( starts, counts, drawCount ) {
  10607. if ( drawCount === 0 ) return;
  10608. const extension = extensions.get( 'WEBGL_multi_draw' );
  10609. if ( extension === null ) {
  10610. for ( let i = 0; i < drawCount; i ++ ) {
  10611. this.render( starts[ i ] / bytesPerElement, counts[ i ] );
  10612. }
  10613. } else {
  10614. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  10615. let elementCount = 0;
  10616. for ( let i = 0; i < drawCount; i ++ ) {
  10617. elementCount += counts[ i ];
  10618. }
  10619. info.update( elementCount, mode, 1 );
  10620. }
  10621. }
  10622. //
  10623. this.setMode = setMode;
  10624. this.setIndex = setIndex;
  10625. this.render = render;
  10626. this.renderInstances = renderInstances;
  10627. this.renderMultiDraw = renderMultiDraw;
  10628. }
  10629. function WebGLInfo( gl ) {
  10630. const memory = {
  10631. geometries: 0,
  10632. textures: 0
  10633. };
  10634. const render = {
  10635. frame: 0,
  10636. calls: 0,
  10637. triangles: 0,
  10638. points: 0,
  10639. lines: 0
  10640. };
  10641. function update( count, mode, instanceCount ) {
  10642. render.calls ++;
  10643. switch ( mode ) {
  10644. case gl.TRIANGLES:
  10645. render.triangles += instanceCount * ( count / 3 );
  10646. break;
  10647. case gl.LINES:
  10648. render.lines += instanceCount * ( count / 2 );
  10649. break;
  10650. case gl.LINE_STRIP:
  10651. render.lines += instanceCount * ( count - 1 );
  10652. break;
  10653. case gl.LINE_LOOP:
  10654. render.lines += instanceCount * count;
  10655. break;
  10656. case gl.POINTS:
  10657. render.points += instanceCount * count;
  10658. break;
  10659. default:
  10660. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10661. break;
  10662. }
  10663. }
  10664. function reset() {
  10665. render.calls = 0;
  10666. render.triangles = 0;
  10667. render.points = 0;
  10668. render.lines = 0;
  10669. }
  10670. return {
  10671. memory: memory,
  10672. render: render,
  10673. programs: null,
  10674. autoReset: true,
  10675. reset: reset,
  10676. update: update
  10677. };
  10678. }
  10679. function numericalSort( a, b ) {
  10680. return a[ 0 ] - b[ 0 ];
  10681. }
  10682. function absNumericalSort( a, b ) {
  10683. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10684. }
  10685. function WebGLMorphtargets( gl, capabilities, textures ) {
  10686. const influencesList = {};
  10687. const morphInfluences = new Float32Array( 8 );
  10688. const morphTextures = new WeakMap();
  10689. const morph = new Vector4();
  10690. const workInfluences = [];
  10691. for ( let i = 0; i < 8; i ++ ) {
  10692. workInfluences[ i ] = [ i, 0 ];
  10693. }
  10694. function update( object, geometry, program ) {
  10695. const objectInfluences = object.morphTargetInfluences;
  10696. if ( capabilities.isWebGL2 === true ) {
  10697. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10698. // into an array of data textures. Each layer represents a single morph target.
  10699. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10700. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10701. let entry = morphTextures.get( geometry );
  10702. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10703. if ( entry !== undefined ) entry.texture.dispose();
  10704. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10705. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10706. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10707. const morphTargets = geometry.morphAttributes.position || [];
  10708. const morphNormals = geometry.morphAttributes.normal || [];
  10709. const morphColors = geometry.morphAttributes.color || [];
  10710. let vertexDataCount = 0;
  10711. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10712. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10713. if ( hasMorphColors === true ) vertexDataCount = 3;
  10714. let width = geometry.attributes.position.count * vertexDataCount;
  10715. let height = 1;
  10716. if ( width > capabilities.maxTextureSize ) {
  10717. height = Math.ceil( width / capabilities.maxTextureSize );
  10718. width = capabilities.maxTextureSize;
  10719. }
  10720. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10721. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10722. texture.type = FloatType;
  10723. texture.needsUpdate = true;
  10724. // fill buffer
  10725. const vertexDataStride = vertexDataCount * 4;
  10726. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10727. const morphTarget = morphTargets[ i ];
  10728. const morphNormal = morphNormals[ i ];
  10729. const morphColor = morphColors[ i ];
  10730. const offset = width * height * 4 * i;
  10731. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10732. const stride = j * vertexDataStride;
  10733. if ( hasMorphPosition === true ) {
  10734. morph.fromBufferAttribute( morphTarget, j );
  10735. buffer[ offset + stride + 0 ] = morph.x;
  10736. buffer[ offset + stride + 1 ] = morph.y;
  10737. buffer[ offset + stride + 2 ] = morph.z;
  10738. buffer[ offset + stride + 3 ] = 0;
  10739. }
  10740. if ( hasMorphNormals === true ) {
  10741. morph.fromBufferAttribute( morphNormal, j );
  10742. buffer[ offset + stride + 4 ] = morph.x;
  10743. buffer[ offset + stride + 5 ] = morph.y;
  10744. buffer[ offset + stride + 6 ] = morph.z;
  10745. buffer[ offset + stride + 7 ] = 0;
  10746. }
  10747. if ( hasMorphColors === true ) {
  10748. morph.fromBufferAttribute( morphColor, j );
  10749. buffer[ offset + stride + 8 ] = morph.x;
  10750. buffer[ offset + stride + 9 ] = morph.y;
  10751. buffer[ offset + stride + 10 ] = morph.z;
  10752. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10753. }
  10754. }
  10755. }
  10756. entry = {
  10757. count: morphTargetsCount,
  10758. texture: texture,
  10759. size: new Vector2( width, height )
  10760. };
  10761. morphTextures.set( geometry, entry );
  10762. function disposeTexture() {
  10763. texture.dispose();
  10764. morphTextures.delete( geometry );
  10765. geometry.removeEventListener( 'dispose', disposeTexture );
  10766. }
  10767. geometry.addEventListener( 'dispose', disposeTexture );
  10768. }
  10769. //
  10770. let morphInfluencesSum = 0;
  10771. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10772. morphInfluencesSum += objectInfluences[ i ];
  10773. }
  10774. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10775. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10776. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10777. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10778. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10779. } else {
  10780. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10781. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10782. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10783. let influences = influencesList[ geometry.id ];
  10784. if ( influences === undefined || influences.length !== length ) {
  10785. // initialise list
  10786. influences = [];
  10787. for ( let i = 0; i < length; i ++ ) {
  10788. influences[ i ] = [ i, 0 ];
  10789. }
  10790. influencesList[ geometry.id ] = influences;
  10791. }
  10792. // Collect influences
  10793. for ( let i = 0; i < length; i ++ ) {
  10794. const influence = influences[ i ];
  10795. influence[ 0 ] = i;
  10796. influence[ 1 ] = objectInfluences[ i ];
  10797. }
  10798. influences.sort( absNumericalSort );
  10799. for ( let i = 0; i < 8; i ++ ) {
  10800. if ( i < length && influences[ i ][ 1 ] ) {
  10801. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10802. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10803. } else {
  10804. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10805. workInfluences[ i ][ 1 ] = 0;
  10806. }
  10807. }
  10808. workInfluences.sort( numericalSort );
  10809. const morphTargets = geometry.morphAttributes.position;
  10810. const morphNormals = geometry.morphAttributes.normal;
  10811. let morphInfluencesSum = 0;
  10812. for ( let i = 0; i < 8; i ++ ) {
  10813. const influence = workInfluences[ i ];
  10814. const index = influence[ 0 ];
  10815. const value = influence[ 1 ];
  10816. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10817. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10818. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10819. }
  10820. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10821. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10822. }
  10823. morphInfluences[ i ] = value;
  10824. morphInfluencesSum += value;
  10825. } else {
  10826. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10827. geometry.deleteAttribute( 'morphTarget' + i );
  10828. }
  10829. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10830. geometry.deleteAttribute( 'morphNormal' + i );
  10831. }
  10832. morphInfluences[ i ] = 0;
  10833. }
  10834. }
  10835. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10836. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10837. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10838. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10839. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10840. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10841. }
  10842. }
  10843. return {
  10844. update: update
  10845. };
  10846. }
  10847. function WebGLObjects( gl, geometries, attributes, info ) {
  10848. let updateMap = new WeakMap();
  10849. function update( object ) {
  10850. const frame = info.render.frame;
  10851. const geometry = object.geometry;
  10852. const buffergeometry = geometries.get( object, geometry );
  10853. // Update once per frame
  10854. if ( updateMap.get( buffergeometry ) !== frame ) {
  10855. geometries.update( buffergeometry );
  10856. updateMap.set( buffergeometry, frame );
  10857. }
  10858. if ( object.isInstancedMesh ) {
  10859. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10860. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10861. }
  10862. if ( updateMap.get( object ) !== frame ) {
  10863. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10864. if ( object.instanceColor !== null ) {
  10865. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10866. }
  10867. updateMap.set( object, frame );
  10868. }
  10869. }
  10870. if ( object.isSkinnedMesh ) {
  10871. const skeleton = object.skeleton;
  10872. if ( updateMap.get( skeleton ) !== frame ) {
  10873. skeleton.update();
  10874. updateMap.set( skeleton, frame );
  10875. }
  10876. }
  10877. return buffergeometry;
  10878. }
  10879. function dispose() {
  10880. updateMap = new WeakMap();
  10881. }
  10882. function onInstancedMeshDispose( event ) {
  10883. const instancedMesh = event.target;
  10884. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10885. attributes.remove( instancedMesh.instanceMatrix );
  10886. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10887. }
  10888. return {
  10889. update: update,
  10890. dispose: dispose
  10891. };
  10892. }
  10893. class DepthTexture extends Texture {
  10894. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  10895. format = format !== undefined ? format : DepthFormat;
  10896. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10897. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10898. }
  10899. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10900. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10901. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10902. this.isDepthTexture = true;
  10903. this.image = { width: width, height: height };
  10904. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10905. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10906. this.flipY = false;
  10907. this.generateMipmaps = false;
  10908. this.compareFunction = null;
  10909. }
  10910. copy( source ) {
  10911. super.copy( source );
  10912. this.compareFunction = source.compareFunction;
  10913. return this;
  10914. }
  10915. toJSON( meta ) {
  10916. const data = super.toJSON( meta );
  10917. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10918. return data;
  10919. }
  10920. }
  10921. /**
  10922. * Uniforms of a program.
  10923. * Those form a tree structure with a special top-level container for the root,
  10924. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10925. *
  10926. *
  10927. * Properties of inner nodes including the top-level container:
  10928. *
  10929. * .seq - array of nested uniforms
  10930. * .map - nested uniforms by name
  10931. *
  10932. *
  10933. * Methods of all nodes except the top-level container:
  10934. *
  10935. * .setValue( gl, value, [textures] )
  10936. *
  10937. * uploads a uniform value(s)
  10938. * the 'textures' parameter is needed for sampler uniforms
  10939. *
  10940. *
  10941. * Static methods of the top-level container (textures factorizations):
  10942. *
  10943. * .upload( gl, seq, values, textures )
  10944. *
  10945. * sets uniforms in 'seq' to 'values[id].value'
  10946. *
  10947. * .seqWithValue( seq, values ) : filteredSeq
  10948. *
  10949. * filters 'seq' entries with corresponding entry in values
  10950. *
  10951. *
  10952. * Methods of the top-level container (textures factorizations):
  10953. *
  10954. * .setValue( gl, name, value, textures )
  10955. *
  10956. * sets uniform with name 'name' to 'value'
  10957. *
  10958. * .setOptional( gl, obj, prop )
  10959. *
  10960. * like .set for an optional property of the object
  10961. *
  10962. */
  10963. const emptyTexture = /*@__PURE__*/ new Texture();
  10964. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  10965. emptyShadowTexture.compareFunction = LessEqualCompare;
  10966. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10967. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10968. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10969. // --- Utilities ---
  10970. // Array Caches (provide typed arrays for temporary by size)
  10971. const arrayCacheF32 = [];
  10972. const arrayCacheI32 = [];
  10973. // Float32Array caches used for uploading Matrix uniforms
  10974. const mat4array = new Float32Array( 16 );
  10975. const mat3array = new Float32Array( 9 );
  10976. const mat2array = new Float32Array( 4 );
  10977. // Flattening for arrays of vectors and matrices
  10978. function flatten( array, nBlocks, blockSize ) {
  10979. const firstElem = array[ 0 ];
  10980. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10981. // unoptimized: ! isNaN( firstElem )
  10982. // see http://jacksondunstan.com/articles/983
  10983. const n = nBlocks * blockSize;
  10984. let r = arrayCacheF32[ n ];
  10985. if ( r === undefined ) {
  10986. r = new Float32Array( n );
  10987. arrayCacheF32[ n ] = r;
  10988. }
  10989. if ( nBlocks !== 0 ) {
  10990. firstElem.toArray( r, 0 );
  10991. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10992. offset += blockSize;
  10993. array[ i ].toArray( r, offset );
  10994. }
  10995. }
  10996. return r;
  10997. }
  10998. function arraysEqual( a, b ) {
  10999. if ( a.length !== b.length ) return false;
  11000. for ( let i = 0, l = a.length; i < l; i ++ ) {
  11001. if ( a[ i ] !== b[ i ] ) return false;
  11002. }
  11003. return true;
  11004. }
  11005. function copyArray( a, b ) {
  11006. for ( let i = 0, l = b.length; i < l; i ++ ) {
  11007. a[ i ] = b[ i ];
  11008. }
  11009. }
  11010. // Texture unit allocation
  11011. function allocTexUnits( textures, n ) {
  11012. let r = arrayCacheI32[ n ];
  11013. if ( r === undefined ) {
  11014. r = new Int32Array( n );
  11015. arrayCacheI32[ n ] = r;
  11016. }
  11017. for ( let i = 0; i !== n; ++ i ) {
  11018. r[ i ] = textures.allocateTextureUnit();
  11019. }
  11020. return r;
  11021. }
  11022. // --- Setters ---
  11023. // Note: Defining these methods externally, because they come in a bunch
  11024. // and this way their names minify.
  11025. // Single scalar
  11026. function setValueV1f( gl, v ) {
  11027. const cache = this.cache;
  11028. if ( cache[ 0 ] === v ) return;
  11029. gl.uniform1f( this.addr, v );
  11030. cache[ 0 ] = v;
  11031. }
  11032. // Single float vector (from flat array or THREE.VectorN)
  11033. function setValueV2f( gl, v ) {
  11034. const cache = this.cache;
  11035. if ( v.x !== undefined ) {
  11036. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11037. gl.uniform2f( this.addr, v.x, v.y );
  11038. cache[ 0 ] = v.x;
  11039. cache[ 1 ] = v.y;
  11040. }
  11041. } else {
  11042. if ( arraysEqual( cache, v ) ) return;
  11043. gl.uniform2fv( this.addr, v );
  11044. copyArray( cache, v );
  11045. }
  11046. }
  11047. function setValueV3f( gl, v ) {
  11048. const cache = this.cache;
  11049. if ( v.x !== undefined ) {
  11050. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11051. gl.uniform3f( this.addr, v.x, v.y, v.z );
  11052. cache[ 0 ] = v.x;
  11053. cache[ 1 ] = v.y;
  11054. cache[ 2 ] = v.z;
  11055. }
  11056. } else if ( v.r !== undefined ) {
  11057. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  11058. gl.uniform3f( this.addr, v.r, v.g, v.b );
  11059. cache[ 0 ] = v.r;
  11060. cache[ 1 ] = v.g;
  11061. cache[ 2 ] = v.b;
  11062. }
  11063. } else {
  11064. if ( arraysEqual( cache, v ) ) return;
  11065. gl.uniform3fv( this.addr, v );
  11066. copyArray( cache, v );
  11067. }
  11068. }
  11069. function setValueV4f( gl, v ) {
  11070. const cache = this.cache;
  11071. if ( v.x !== undefined ) {
  11072. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11073. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  11074. cache[ 0 ] = v.x;
  11075. cache[ 1 ] = v.y;
  11076. cache[ 2 ] = v.z;
  11077. cache[ 3 ] = v.w;
  11078. }
  11079. } else {
  11080. if ( arraysEqual( cache, v ) ) return;
  11081. gl.uniform4fv( this.addr, v );
  11082. copyArray( cache, v );
  11083. }
  11084. }
  11085. // Single matrix (from flat array or THREE.MatrixN)
  11086. function setValueM2( gl, v ) {
  11087. const cache = this.cache;
  11088. const elements = v.elements;
  11089. if ( elements === undefined ) {
  11090. if ( arraysEqual( cache, v ) ) return;
  11091. gl.uniformMatrix2fv( this.addr, false, v );
  11092. copyArray( cache, v );
  11093. } else {
  11094. if ( arraysEqual( cache, elements ) ) return;
  11095. mat2array.set( elements );
  11096. gl.uniformMatrix2fv( this.addr, false, mat2array );
  11097. copyArray( cache, elements );
  11098. }
  11099. }
  11100. function setValueM3( gl, v ) {
  11101. const cache = this.cache;
  11102. const elements = v.elements;
  11103. if ( elements === undefined ) {
  11104. if ( arraysEqual( cache, v ) ) return;
  11105. gl.uniformMatrix3fv( this.addr, false, v );
  11106. copyArray( cache, v );
  11107. } else {
  11108. if ( arraysEqual( cache, elements ) ) return;
  11109. mat3array.set( elements );
  11110. gl.uniformMatrix3fv( this.addr, false, mat3array );
  11111. copyArray( cache, elements );
  11112. }
  11113. }
  11114. function setValueM4( gl, v ) {
  11115. const cache = this.cache;
  11116. const elements = v.elements;
  11117. if ( elements === undefined ) {
  11118. if ( arraysEqual( cache, v ) ) return;
  11119. gl.uniformMatrix4fv( this.addr, false, v );
  11120. copyArray( cache, v );
  11121. } else {
  11122. if ( arraysEqual( cache, elements ) ) return;
  11123. mat4array.set( elements );
  11124. gl.uniformMatrix4fv( this.addr, false, mat4array );
  11125. copyArray( cache, elements );
  11126. }
  11127. }
  11128. // Single integer / boolean
  11129. function setValueV1i( gl, v ) {
  11130. const cache = this.cache;
  11131. if ( cache[ 0 ] === v ) return;
  11132. gl.uniform1i( this.addr, v );
  11133. cache[ 0 ] = v;
  11134. }
  11135. // Single integer / boolean vector (from flat array or THREE.VectorN)
  11136. function setValueV2i( gl, v ) {
  11137. const cache = this.cache;
  11138. if ( v.x !== undefined ) {
  11139. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11140. gl.uniform2i( this.addr, v.x, v.y );
  11141. cache[ 0 ] = v.x;
  11142. cache[ 1 ] = v.y;
  11143. }
  11144. } else {
  11145. if ( arraysEqual( cache, v ) ) return;
  11146. gl.uniform2iv( this.addr, v );
  11147. copyArray( cache, v );
  11148. }
  11149. }
  11150. function setValueV3i( gl, v ) {
  11151. const cache = this.cache;
  11152. if ( v.x !== undefined ) {
  11153. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11154. gl.uniform3i( this.addr, v.x, v.y, v.z );
  11155. cache[ 0 ] = v.x;
  11156. cache[ 1 ] = v.y;
  11157. cache[ 2 ] = v.z;
  11158. }
  11159. } else {
  11160. if ( arraysEqual( cache, v ) ) return;
  11161. gl.uniform3iv( this.addr, v );
  11162. copyArray( cache, v );
  11163. }
  11164. }
  11165. function setValueV4i( gl, v ) {
  11166. const cache = this.cache;
  11167. if ( v.x !== undefined ) {
  11168. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11169. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11170. cache[ 0 ] = v.x;
  11171. cache[ 1 ] = v.y;
  11172. cache[ 2 ] = v.z;
  11173. cache[ 3 ] = v.w;
  11174. }
  11175. } else {
  11176. if ( arraysEqual( cache, v ) ) return;
  11177. gl.uniform4iv( this.addr, v );
  11178. copyArray( cache, v );
  11179. }
  11180. }
  11181. // Single unsigned integer
  11182. function setValueV1ui( gl, v ) {
  11183. const cache = this.cache;
  11184. if ( cache[ 0 ] === v ) return;
  11185. gl.uniform1ui( this.addr, v );
  11186. cache[ 0 ] = v;
  11187. }
  11188. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11189. function setValueV2ui( gl, v ) {
  11190. const cache = this.cache;
  11191. if ( v.x !== undefined ) {
  11192. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11193. gl.uniform2ui( this.addr, v.x, v.y );
  11194. cache[ 0 ] = v.x;
  11195. cache[ 1 ] = v.y;
  11196. }
  11197. } else {
  11198. if ( arraysEqual( cache, v ) ) return;
  11199. gl.uniform2uiv( this.addr, v );
  11200. copyArray( cache, v );
  11201. }
  11202. }
  11203. function setValueV3ui( gl, v ) {
  11204. const cache = this.cache;
  11205. if ( v.x !== undefined ) {
  11206. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11207. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11208. cache[ 0 ] = v.x;
  11209. cache[ 1 ] = v.y;
  11210. cache[ 2 ] = v.z;
  11211. }
  11212. } else {
  11213. if ( arraysEqual( cache, v ) ) return;
  11214. gl.uniform3uiv( this.addr, v );
  11215. copyArray( cache, v );
  11216. }
  11217. }
  11218. function setValueV4ui( gl, v ) {
  11219. const cache = this.cache;
  11220. if ( v.x !== undefined ) {
  11221. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11222. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11223. cache[ 0 ] = v.x;
  11224. cache[ 1 ] = v.y;
  11225. cache[ 2 ] = v.z;
  11226. cache[ 3 ] = v.w;
  11227. }
  11228. } else {
  11229. if ( arraysEqual( cache, v ) ) return;
  11230. gl.uniform4uiv( this.addr, v );
  11231. copyArray( cache, v );
  11232. }
  11233. }
  11234. // Single texture (2D / Cube)
  11235. function setValueT1( gl, v, textures ) {
  11236. const cache = this.cache;
  11237. const unit = textures.allocateTextureUnit();
  11238. if ( cache[ 0 ] !== unit ) {
  11239. gl.uniform1i( this.addr, unit );
  11240. cache[ 0 ] = unit;
  11241. }
  11242. const emptyTexture2D = ( this.type === gl.SAMPLER_2D_SHADOW ) ? emptyShadowTexture : emptyTexture;
  11243. textures.setTexture2D( v || emptyTexture2D, unit );
  11244. }
  11245. function setValueT3D1( gl, v, textures ) {
  11246. const cache = this.cache;
  11247. const unit = textures.allocateTextureUnit();
  11248. if ( cache[ 0 ] !== unit ) {
  11249. gl.uniform1i( this.addr, unit );
  11250. cache[ 0 ] = unit;
  11251. }
  11252. textures.setTexture3D( v || empty3dTexture, unit );
  11253. }
  11254. function setValueT6( gl, v, textures ) {
  11255. const cache = this.cache;
  11256. const unit = textures.allocateTextureUnit();
  11257. if ( cache[ 0 ] !== unit ) {
  11258. gl.uniform1i( this.addr, unit );
  11259. cache[ 0 ] = unit;
  11260. }
  11261. textures.setTextureCube( v || emptyCubeTexture, unit );
  11262. }
  11263. function setValueT2DArray1( gl, v, textures ) {
  11264. const cache = this.cache;
  11265. const unit = textures.allocateTextureUnit();
  11266. if ( cache[ 0 ] !== unit ) {
  11267. gl.uniform1i( this.addr, unit );
  11268. cache[ 0 ] = unit;
  11269. }
  11270. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11271. }
  11272. // Helper to pick the right setter for the singular case
  11273. function getSingularSetter( type ) {
  11274. switch ( type ) {
  11275. case 0x1406: return setValueV1f; // FLOAT
  11276. case 0x8b50: return setValueV2f; // _VEC2
  11277. case 0x8b51: return setValueV3f; // _VEC3
  11278. case 0x8b52: return setValueV4f; // _VEC4
  11279. case 0x8b5a: return setValueM2; // _MAT2
  11280. case 0x8b5b: return setValueM3; // _MAT3
  11281. case 0x8b5c: return setValueM4; // _MAT4
  11282. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11283. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11284. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11285. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11286. case 0x1405: return setValueV1ui; // UINT
  11287. case 0x8dc6: return setValueV2ui; // _VEC2
  11288. case 0x8dc7: return setValueV3ui; // _VEC3
  11289. case 0x8dc8: return setValueV4ui; // _VEC4
  11290. case 0x8b5e: // SAMPLER_2D
  11291. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11292. case 0x8dca: // INT_SAMPLER_2D
  11293. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11294. case 0x8b62: // SAMPLER_2D_SHADOW
  11295. return setValueT1;
  11296. case 0x8b5f: // SAMPLER_3D
  11297. case 0x8dcb: // INT_SAMPLER_3D
  11298. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11299. return setValueT3D1;
  11300. case 0x8b60: // SAMPLER_CUBE
  11301. case 0x8dcc: // INT_SAMPLER_CUBE
  11302. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11303. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11304. return setValueT6;
  11305. case 0x8dc1: // SAMPLER_2D_ARRAY
  11306. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11307. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11308. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11309. return setValueT2DArray1;
  11310. }
  11311. }
  11312. // Array of scalars
  11313. function setValueV1fArray( gl, v ) {
  11314. gl.uniform1fv( this.addr, v );
  11315. }
  11316. // Array of vectors (from flat array or array of THREE.VectorN)
  11317. function setValueV2fArray( gl, v ) {
  11318. const data = flatten( v, this.size, 2 );
  11319. gl.uniform2fv( this.addr, data );
  11320. }
  11321. function setValueV3fArray( gl, v ) {
  11322. const data = flatten( v, this.size, 3 );
  11323. gl.uniform3fv( this.addr, data );
  11324. }
  11325. function setValueV4fArray( gl, v ) {
  11326. const data = flatten( v, this.size, 4 );
  11327. gl.uniform4fv( this.addr, data );
  11328. }
  11329. // Array of matrices (from flat array or array of THREE.MatrixN)
  11330. function setValueM2Array( gl, v ) {
  11331. const data = flatten( v, this.size, 4 );
  11332. gl.uniformMatrix2fv( this.addr, false, data );
  11333. }
  11334. function setValueM3Array( gl, v ) {
  11335. const data = flatten( v, this.size, 9 );
  11336. gl.uniformMatrix3fv( this.addr, false, data );
  11337. }
  11338. function setValueM4Array( gl, v ) {
  11339. const data = flatten( v, this.size, 16 );
  11340. gl.uniformMatrix4fv( this.addr, false, data );
  11341. }
  11342. // Array of integer / boolean
  11343. function setValueV1iArray( gl, v ) {
  11344. gl.uniform1iv( this.addr, v );
  11345. }
  11346. // Array of integer / boolean vectors (from flat array)
  11347. function setValueV2iArray( gl, v ) {
  11348. gl.uniform2iv( this.addr, v );
  11349. }
  11350. function setValueV3iArray( gl, v ) {
  11351. gl.uniform3iv( this.addr, v );
  11352. }
  11353. function setValueV4iArray( gl, v ) {
  11354. gl.uniform4iv( this.addr, v );
  11355. }
  11356. // Array of unsigned integer
  11357. function setValueV1uiArray( gl, v ) {
  11358. gl.uniform1uiv( this.addr, v );
  11359. }
  11360. // Array of unsigned integer vectors (from flat array)
  11361. function setValueV2uiArray( gl, v ) {
  11362. gl.uniform2uiv( this.addr, v );
  11363. }
  11364. function setValueV3uiArray( gl, v ) {
  11365. gl.uniform3uiv( this.addr, v );
  11366. }
  11367. function setValueV4uiArray( gl, v ) {
  11368. gl.uniform4uiv( this.addr, v );
  11369. }
  11370. // Array of textures (2D / 3D / Cube / 2DArray)
  11371. function setValueT1Array( gl, v, textures ) {
  11372. const cache = this.cache;
  11373. const n = v.length;
  11374. const units = allocTexUnits( textures, n );
  11375. if ( ! arraysEqual( cache, units ) ) {
  11376. gl.uniform1iv( this.addr, units );
  11377. copyArray( cache, units );
  11378. }
  11379. for ( let i = 0; i !== n; ++ i ) {
  11380. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11381. }
  11382. }
  11383. function setValueT3DArray( gl, v, textures ) {
  11384. const cache = this.cache;
  11385. const n = v.length;
  11386. const units = allocTexUnits( textures, n );
  11387. if ( ! arraysEqual( cache, units ) ) {
  11388. gl.uniform1iv( this.addr, units );
  11389. copyArray( cache, units );
  11390. }
  11391. for ( let i = 0; i !== n; ++ i ) {
  11392. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11393. }
  11394. }
  11395. function setValueT6Array( gl, v, textures ) {
  11396. const cache = this.cache;
  11397. const n = v.length;
  11398. const units = allocTexUnits( textures, n );
  11399. if ( ! arraysEqual( cache, units ) ) {
  11400. gl.uniform1iv( this.addr, units );
  11401. copyArray( cache, units );
  11402. }
  11403. for ( let i = 0; i !== n; ++ i ) {
  11404. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11405. }
  11406. }
  11407. function setValueT2DArrayArray( gl, v, textures ) {
  11408. const cache = this.cache;
  11409. const n = v.length;
  11410. const units = allocTexUnits( textures, n );
  11411. if ( ! arraysEqual( cache, units ) ) {
  11412. gl.uniform1iv( this.addr, units );
  11413. copyArray( cache, units );
  11414. }
  11415. for ( let i = 0; i !== n; ++ i ) {
  11416. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11417. }
  11418. }
  11419. // Helper to pick the right setter for a pure (bottom-level) array
  11420. function getPureArraySetter( type ) {
  11421. switch ( type ) {
  11422. case 0x1406: return setValueV1fArray; // FLOAT
  11423. case 0x8b50: return setValueV2fArray; // _VEC2
  11424. case 0x8b51: return setValueV3fArray; // _VEC3
  11425. case 0x8b52: return setValueV4fArray; // _VEC4
  11426. case 0x8b5a: return setValueM2Array; // _MAT2
  11427. case 0x8b5b: return setValueM3Array; // _MAT3
  11428. case 0x8b5c: return setValueM4Array; // _MAT4
  11429. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11430. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11431. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11432. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11433. case 0x1405: return setValueV1uiArray; // UINT
  11434. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11435. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11436. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11437. case 0x8b5e: // SAMPLER_2D
  11438. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11439. case 0x8dca: // INT_SAMPLER_2D
  11440. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11441. case 0x8b62: // SAMPLER_2D_SHADOW
  11442. return setValueT1Array;
  11443. case 0x8b5f: // SAMPLER_3D
  11444. case 0x8dcb: // INT_SAMPLER_3D
  11445. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11446. return setValueT3DArray;
  11447. case 0x8b60: // SAMPLER_CUBE
  11448. case 0x8dcc: // INT_SAMPLER_CUBE
  11449. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11450. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11451. return setValueT6Array;
  11452. case 0x8dc1: // SAMPLER_2D_ARRAY
  11453. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11454. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11455. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11456. return setValueT2DArrayArray;
  11457. }
  11458. }
  11459. // --- Uniform Classes ---
  11460. class SingleUniform {
  11461. constructor( id, activeInfo, addr ) {
  11462. this.id = id;
  11463. this.addr = addr;
  11464. this.cache = [];
  11465. this.type = activeInfo.type;
  11466. this.setValue = getSingularSetter( activeInfo.type );
  11467. // this.path = activeInfo.name; // DEBUG
  11468. }
  11469. }
  11470. class PureArrayUniform {
  11471. constructor( id, activeInfo, addr ) {
  11472. this.id = id;
  11473. this.addr = addr;
  11474. this.cache = [];
  11475. this.type = activeInfo.type;
  11476. this.size = activeInfo.size;
  11477. this.setValue = getPureArraySetter( activeInfo.type );
  11478. // this.path = activeInfo.name; // DEBUG
  11479. }
  11480. }
  11481. class StructuredUniform {
  11482. constructor( id ) {
  11483. this.id = id;
  11484. this.seq = [];
  11485. this.map = {};
  11486. }
  11487. setValue( gl, value, textures ) {
  11488. const seq = this.seq;
  11489. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11490. const u = seq[ i ];
  11491. u.setValue( gl, value[ u.id ], textures );
  11492. }
  11493. }
  11494. }
  11495. // --- Top-level ---
  11496. // Parser - builds up the property tree from the path strings
  11497. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11498. // extracts
  11499. // - the identifier (member name or array index)
  11500. // - followed by an optional right bracket (found when array index)
  11501. // - followed by an optional left bracket or dot (type of subscript)
  11502. //
  11503. // Note: These portions can be read in a non-overlapping fashion and
  11504. // allow straightforward parsing of the hierarchy that WebGL encodes
  11505. // in the uniform names.
  11506. function addUniform( container, uniformObject ) {
  11507. container.seq.push( uniformObject );
  11508. container.map[ uniformObject.id ] = uniformObject;
  11509. }
  11510. function parseUniform( activeInfo, addr, container ) {
  11511. const path = activeInfo.name,
  11512. pathLength = path.length;
  11513. // reset RegExp object, because of the early exit of a previous run
  11514. RePathPart.lastIndex = 0;
  11515. while ( true ) {
  11516. const match = RePathPart.exec( path ),
  11517. matchEnd = RePathPart.lastIndex;
  11518. let id = match[ 1 ];
  11519. const idIsIndex = match[ 2 ] === ']',
  11520. subscript = match[ 3 ];
  11521. if ( idIsIndex ) id = id | 0; // convert to integer
  11522. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11523. // bare name or "pure" bottom-level array "[0]" suffix
  11524. addUniform( container, subscript === undefined ?
  11525. new SingleUniform( id, activeInfo, addr ) :
  11526. new PureArrayUniform( id, activeInfo, addr ) );
  11527. break;
  11528. } else {
  11529. // step into inner node / create it in case it doesn't exist
  11530. const map = container.map;
  11531. let next = map[ id ];
  11532. if ( next === undefined ) {
  11533. next = new StructuredUniform( id );
  11534. addUniform( container, next );
  11535. }
  11536. container = next;
  11537. }
  11538. }
  11539. }
  11540. // Root Container
  11541. class WebGLUniforms {
  11542. constructor( gl, program ) {
  11543. this.seq = [];
  11544. this.map = {};
  11545. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11546. for ( let i = 0; i < n; ++ i ) {
  11547. const info = gl.getActiveUniform( program, i ),
  11548. addr = gl.getUniformLocation( program, info.name );
  11549. parseUniform( info, addr, this );
  11550. }
  11551. }
  11552. setValue( gl, name, value, textures ) {
  11553. const u = this.map[ name ];
  11554. if ( u !== undefined ) u.setValue( gl, value, textures );
  11555. }
  11556. setOptional( gl, object, name ) {
  11557. const v = object[ name ];
  11558. if ( v !== undefined ) this.setValue( gl, name, v );
  11559. }
  11560. static upload( gl, seq, values, textures ) {
  11561. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11562. const u = seq[ i ],
  11563. v = values[ u.id ];
  11564. if ( v.needsUpdate !== false ) {
  11565. // note: always updating when .needsUpdate is undefined
  11566. u.setValue( gl, v.value, textures );
  11567. }
  11568. }
  11569. }
  11570. static seqWithValue( seq, values ) {
  11571. const r = [];
  11572. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11573. const u = seq[ i ];
  11574. if ( u.id in values ) r.push( u );
  11575. }
  11576. return r;
  11577. }
  11578. }
  11579. function WebGLShader( gl, type, string ) {
  11580. const shader = gl.createShader( type );
  11581. gl.shaderSource( shader, string );
  11582. gl.compileShader( shader );
  11583. return shader;
  11584. }
  11585. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  11586. const COMPLETION_STATUS_KHR = 0x91B1;
  11587. let programIdCount = 0;
  11588. function handleSource( string, errorLine ) {
  11589. const lines = string.split( '\n' );
  11590. const lines2 = [];
  11591. const from = Math.max( errorLine - 6, 0 );
  11592. const to = Math.min( errorLine + 6, lines.length );
  11593. for ( let i = from; i < to; i ++ ) {
  11594. const line = i + 1;
  11595. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11596. }
  11597. return lines2.join( '\n' );
  11598. }
  11599. function getEncodingComponents( colorSpace ) {
  11600. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11601. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11602. let gamutMapping;
  11603. if ( workingPrimaries === encodingPrimaries ) {
  11604. gamutMapping = '';
  11605. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11606. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11607. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11608. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11609. }
  11610. switch ( colorSpace ) {
  11611. case LinearSRGBColorSpace:
  11612. case LinearDisplayP3ColorSpace:
  11613. return [ gamutMapping, 'LinearTransferOETF' ];
  11614. case SRGBColorSpace:
  11615. case DisplayP3ColorSpace:
  11616. return [ gamutMapping, 'sRGBTransferOETF' ];
  11617. default:
  11618. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11619. return [ gamutMapping, 'LinearTransferOETF' ];
  11620. }
  11621. }
  11622. function getShaderErrors( gl, shader, type ) {
  11623. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11624. const errors = gl.getShaderInfoLog( shader ).trim();
  11625. if ( status && errors === '' ) return '';
  11626. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11627. if ( errorMatches ) {
  11628. // --enable-privileged-webgl-extension
  11629. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11630. const errorLine = parseInt( errorMatches[ 1 ] );
  11631. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11632. } else {
  11633. return errors;
  11634. }
  11635. }
  11636. function getTexelEncodingFunction( functionName, colorSpace ) {
  11637. const components = getEncodingComponents( colorSpace );
  11638. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11639. }
  11640. function getToneMappingFunction( functionName, toneMapping ) {
  11641. let toneMappingName;
  11642. switch ( toneMapping ) {
  11643. case LinearToneMapping:
  11644. toneMappingName = 'Linear';
  11645. break;
  11646. case ReinhardToneMapping:
  11647. toneMappingName = 'Reinhard';
  11648. break;
  11649. case CineonToneMapping:
  11650. toneMappingName = 'OptimizedCineon';
  11651. break;
  11652. case ACESFilmicToneMapping:
  11653. toneMappingName = 'ACESFilmic';
  11654. break;
  11655. case AgXToneMapping:
  11656. toneMappingName = 'AgX';
  11657. break;
  11658. case CustomToneMapping:
  11659. toneMappingName = 'Custom';
  11660. break;
  11661. default:
  11662. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11663. toneMappingName = 'Linear';
  11664. }
  11665. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11666. }
  11667. function generateExtensions( parameters ) {
  11668. const chunks = [
  11669. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11670. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11671. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11672. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11673. ];
  11674. return chunks.filter( filterEmptyLine ).join( '\n' );
  11675. }
  11676. function generateVertexExtensions( parameters ) {
  11677. const chunks = [
  11678. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : ''
  11679. ];
  11680. return chunks.filter( filterEmptyLine ).join( '\n' );
  11681. }
  11682. function generateDefines( defines ) {
  11683. const chunks = [];
  11684. for ( const name in defines ) {
  11685. const value = defines[ name ];
  11686. if ( value === false ) continue;
  11687. chunks.push( '#define ' + name + ' ' + value );
  11688. }
  11689. return chunks.join( '\n' );
  11690. }
  11691. function fetchAttributeLocations( gl, program ) {
  11692. const attributes = {};
  11693. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11694. for ( let i = 0; i < n; i ++ ) {
  11695. const info = gl.getActiveAttrib( program, i );
  11696. const name = info.name;
  11697. let locationSize = 1;
  11698. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11699. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11700. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11701. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11702. attributes[ name ] = {
  11703. type: info.type,
  11704. location: gl.getAttribLocation( program, name ),
  11705. locationSize: locationSize
  11706. };
  11707. }
  11708. return attributes;
  11709. }
  11710. function filterEmptyLine( string ) {
  11711. return string !== '';
  11712. }
  11713. function replaceLightNums( string, parameters ) {
  11714. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11715. return string
  11716. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11717. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11718. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11719. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11720. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11721. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11722. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11723. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11724. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11725. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11726. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11727. }
  11728. function replaceClippingPlaneNums( string, parameters ) {
  11729. return string
  11730. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11731. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11732. }
  11733. // Resolve Includes
  11734. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11735. function resolveIncludes( string ) {
  11736. return string.replace( includePattern, includeReplacer );
  11737. }
  11738. const shaderChunkMap = new Map( [
  11739. [ 'encodings_fragment', 'colorspace_fragment' ], // @deprecated, r154
  11740. [ 'encodings_pars_fragment', 'colorspace_pars_fragment' ], // @deprecated, r154
  11741. [ 'output_fragment', 'opaque_fragment' ], // @deprecated, r154
  11742. ] );
  11743. function includeReplacer( match, include ) {
  11744. let string = ShaderChunk[ include ];
  11745. if ( string === undefined ) {
  11746. const newInclude = shaderChunkMap.get( include );
  11747. if ( newInclude !== undefined ) {
  11748. string = ShaderChunk[ newInclude ];
  11749. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11750. } else {
  11751. throw new Error( 'Can not resolve #include <' + include + '>' );
  11752. }
  11753. }
  11754. return resolveIncludes( string );
  11755. }
  11756. // Unroll Loops
  11757. 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;
  11758. function unrollLoops( string ) {
  11759. return string.replace( unrollLoopPattern, loopReplacer );
  11760. }
  11761. function loopReplacer( match, start, end, snippet ) {
  11762. let string = '';
  11763. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11764. string += snippet
  11765. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11766. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11767. }
  11768. return string;
  11769. }
  11770. //
  11771. function generatePrecision( parameters ) {
  11772. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11773. if ( parameters.precision === 'highp' ) {
  11774. precisionstring += '\n#define HIGH_PRECISION';
  11775. } else if ( parameters.precision === 'mediump' ) {
  11776. precisionstring += '\n#define MEDIUM_PRECISION';
  11777. } else if ( parameters.precision === 'lowp' ) {
  11778. precisionstring += '\n#define LOW_PRECISION';
  11779. }
  11780. return precisionstring;
  11781. }
  11782. function generateShadowMapTypeDefine( parameters ) {
  11783. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11784. if ( parameters.shadowMapType === PCFShadowMap ) {
  11785. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11786. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11787. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11788. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11789. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11790. }
  11791. return shadowMapTypeDefine;
  11792. }
  11793. function generateEnvMapTypeDefine( parameters ) {
  11794. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11795. if ( parameters.envMap ) {
  11796. switch ( parameters.envMapMode ) {
  11797. case CubeReflectionMapping:
  11798. case CubeRefractionMapping:
  11799. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11800. break;
  11801. case CubeUVReflectionMapping:
  11802. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11803. break;
  11804. }
  11805. }
  11806. return envMapTypeDefine;
  11807. }
  11808. function generateEnvMapModeDefine( parameters ) {
  11809. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11810. if ( parameters.envMap ) {
  11811. switch ( parameters.envMapMode ) {
  11812. case CubeRefractionMapping:
  11813. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11814. break;
  11815. }
  11816. }
  11817. return envMapModeDefine;
  11818. }
  11819. function generateEnvMapBlendingDefine( parameters ) {
  11820. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11821. if ( parameters.envMap ) {
  11822. switch ( parameters.combine ) {
  11823. case MultiplyOperation:
  11824. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11825. break;
  11826. case MixOperation:
  11827. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11828. break;
  11829. case AddOperation:
  11830. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11831. break;
  11832. }
  11833. }
  11834. return envMapBlendingDefine;
  11835. }
  11836. function generateCubeUVSize( parameters ) {
  11837. const imageHeight = parameters.envMapCubeUVHeight;
  11838. if ( imageHeight === null ) return null;
  11839. const maxMip = Math.log2( imageHeight ) - 2;
  11840. const texelHeight = 1.0 / imageHeight;
  11841. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11842. return { texelWidth, texelHeight, maxMip };
  11843. }
  11844. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11845. // TODO Send this event to Three.js DevTools
  11846. // console.log( 'WebGLProgram', cacheKey );
  11847. const gl = renderer.getContext();
  11848. const defines = parameters.defines;
  11849. let vertexShader = parameters.vertexShader;
  11850. let fragmentShader = parameters.fragmentShader;
  11851. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11852. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11853. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11854. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11855. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11856. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11857. const customVertexExtensions = generateVertexExtensions( parameters );
  11858. const customDefines = generateDefines( defines );
  11859. const program = gl.createProgram();
  11860. let prefixVertex, prefixFragment;
  11861. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11862. if ( parameters.isRawShaderMaterial ) {
  11863. prefixVertex = [
  11864. '#define SHADER_TYPE ' + parameters.shaderType,
  11865. '#define SHADER_NAME ' + parameters.shaderName,
  11866. customDefines
  11867. ].filter( filterEmptyLine ).join( '\n' );
  11868. if ( prefixVertex.length > 0 ) {
  11869. prefixVertex += '\n';
  11870. }
  11871. prefixFragment = [
  11872. customExtensions,
  11873. '#define SHADER_TYPE ' + parameters.shaderType,
  11874. '#define SHADER_NAME ' + parameters.shaderName,
  11875. customDefines
  11876. ].filter( filterEmptyLine ).join( '\n' );
  11877. if ( prefixFragment.length > 0 ) {
  11878. prefixFragment += '\n';
  11879. }
  11880. } else {
  11881. prefixVertex = [
  11882. generatePrecision( parameters ),
  11883. '#define SHADER_TYPE ' + parameters.shaderType,
  11884. '#define SHADER_NAME ' + parameters.shaderName,
  11885. customDefines,
  11886. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  11887. parameters.batching ? '#define USE_BATCHING' : '',
  11888. parameters.instancing ? '#define USE_INSTANCING' : '',
  11889. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11890. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11891. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11892. parameters.map ? '#define USE_MAP' : '',
  11893. parameters.envMap ? '#define USE_ENVMAP' : '',
  11894. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11895. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11896. parameters.aoMap ? '#define USE_AOMAP' : '',
  11897. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11898. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11899. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11900. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11901. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11902. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11903. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11904. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11905. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11906. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11907. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11908. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11909. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11910. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11911. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11912. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11913. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11914. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11915. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11916. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11917. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11918. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11919. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11920. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11921. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11922. //
  11923. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11924. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11925. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11926. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11927. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11928. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11929. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11930. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11931. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11932. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11933. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11934. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11935. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11936. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11937. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11938. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11939. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11940. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11941. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11942. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11943. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11944. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11945. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11946. //
  11947. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11948. parameters.vertexColors ? '#define USE_COLOR' : '',
  11949. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11950. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11951. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11952. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11953. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11954. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11955. parameters.skinning ? '#define USE_SKINNING' : '',
  11956. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11957. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11958. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11959. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11960. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11961. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11962. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11963. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11964. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11965. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11966. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11967. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11968. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11969. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11970. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11971. 'uniform mat4 modelMatrix;',
  11972. 'uniform mat4 modelViewMatrix;',
  11973. 'uniform mat4 projectionMatrix;',
  11974. 'uniform mat4 viewMatrix;',
  11975. 'uniform mat3 normalMatrix;',
  11976. 'uniform vec3 cameraPosition;',
  11977. 'uniform bool isOrthographic;',
  11978. '#ifdef USE_INSTANCING',
  11979. ' attribute mat4 instanceMatrix;',
  11980. '#endif',
  11981. '#ifdef USE_INSTANCING_COLOR',
  11982. ' attribute vec3 instanceColor;',
  11983. '#endif',
  11984. 'attribute vec3 position;',
  11985. 'attribute vec3 normal;',
  11986. 'attribute vec2 uv;',
  11987. '#ifdef USE_UV1',
  11988. ' attribute vec2 uv1;',
  11989. '#endif',
  11990. '#ifdef USE_UV2',
  11991. ' attribute vec2 uv2;',
  11992. '#endif',
  11993. '#ifdef USE_UV3',
  11994. ' attribute vec2 uv3;',
  11995. '#endif',
  11996. '#ifdef USE_TANGENT',
  11997. ' attribute vec4 tangent;',
  11998. '#endif',
  11999. '#if defined( USE_COLOR_ALPHA )',
  12000. ' attribute vec4 color;',
  12001. '#elif defined( USE_COLOR )',
  12002. ' attribute vec3 color;',
  12003. '#endif',
  12004. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  12005. ' attribute vec3 morphTarget0;',
  12006. ' attribute vec3 morphTarget1;',
  12007. ' attribute vec3 morphTarget2;',
  12008. ' attribute vec3 morphTarget3;',
  12009. ' #ifdef USE_MORPHNORMALS',
  12010. ' attribute vec3 morphNormal0;',
  12011. ' attribute vec3 morphNormal1;',
  12012. ' attribute vec3 morphNormal2;',
  12013. ' attribute vec3 morphNormal3;',
  12014. ' #else',
  12015. ' attribute vec3 morphTarget4;',
  12016. ' attribute vec3 morphTarget5;',
  12017. ' attribute vec3 morphTarget6;',
  12018. ' attribute vec3 morphTarget7;',
  12019. ' #endif',
  12020. '#endif',
  12021. '#ifdef USE_SKINNING',
  12022. ' attribute vec4 skinIndex;',
  12023. ' attribute vec4 skinWeight;',
  12024. '#endif',
  12025. '\n'
  12026. ].filter( filterEmptyLine ).join( '\n' );
  12027. prefixFragment = [
  12028. customExtensions,
  12029. generatePrecision( parameters ),
  12030. '#define SHADER_TYPE ' + parameters.shaderType,
  12031. '#define SHADER_NAME ' + parameters.shaderName,
  12032. customDefines,
  12033. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  12034. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  12035. parameters.map ? '#define USE_MAP' : '',
  12036. parameters.matcap ? '#define USE_MATCAP' : '',
  12037. parameters.envMap ? '#define USE_ENVMAP' : '',
  12038. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  12039. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12040. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  12041. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  12042. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  12043. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  12044. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12045. parameters.aoMap ? '#define USE_AOMAP' : '',
  12046. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12047. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12048. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  12049. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  12050. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12051. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  12052. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  12053. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  12054. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12055. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12056. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12057. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  12058. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  12059. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  12060. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12061. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  12062. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  12063. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12064. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12065. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12066. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  12067. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  12068. parameters.sheen ? '#define USE_SHEEN' : '',
  12069. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  12070. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  12071. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12072. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12073. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12074. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  12075. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  12076. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12077. parameters.vertexUv1s ? '#define USE_UV1' : '',
  12078. parameters.vertexUv2s ? '#define USE_UV2' : '',
  12079. parameters.vertexUv3s ? '#define USE_UV3' : '',
  12080. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  12081. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12082. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12083. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12084. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12085. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12086. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12087. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  12088. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  12089. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  12090. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  12091. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12092. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12093. 'uniform mat4 viewMatrix;',
  12094. 'uniform vec3 cameraPosition;',
  12095. 'uniform bool isOrthographic;',
  12096. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  12097. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12098. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  12099. parameters.dithering ? '#define DITHERING' : '',
  12100. parameters.opaque ? '#define OPAQUE' : '',
  12101. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  12102. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  12103. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  12104. '\n'
  12105. ].filter( filterEmptyLine ).join( '\n' );
  12106. }
  12107. vertexShader = resolveIncludes( vertexShader );
  12108. vertexShader = replaceLightNums( vertexShader, parameters );
  12109. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  12110. fragmentShader = resolveIncludes( fragmentShader );
  12111. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12112. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  12113. vertexShader = unrollLoops( vertexShader );
  12114. fragmentShader = unrollLoops( fragmentShader );
  12115. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  12116. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  12117. versionString = '#version 300 es\n';
  12118. prefixVertex = [
  12119. customVertexExtensions,
  12120. 'precision mediump sampler2DArray;',
  12121. '#define attribute in',
  12122. '#define varying out',
  12123. '#define texture2D texture'
  12124. ].join( '\n' ) + '\n' + prefixVertex;
  12125. prefixFragment = [
  12126. 'precision mediump sampler2DArray;',
  12127. '#define varying in',
  12128. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  12129. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  12130. '#define gl_FragDepthEXT gl_FragDepth',
  12131. '#define texture2D texture',
  12132. '#define textureCube texture',
  12133. '#define texture2DProj textureProj',
  12134. '#define texture2DLodEXT textureLod',
  12135. '#define texture2DProjLodEXT textureProjLod',
  12136. '#define textureCubeLodEXT textureLod',
  12137. '#define texture2DGradEXT textureGrad',
  12138. '#define texture2DProjGradEXT textureProjGrad',
  12139. '#define textureCubeGradEXT textureGrad'
  12140. ].join( '\n' ) + '\n' + prefixFragment;
  12141. }
  12142. const vertexGlsl = versionString + prefixVertex + vertexShader;
  12143. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  12144. // console.log( '*VERTEX*', vertexGlsl );
  12145. // console.log( '*FRAGMENT*', fragmentGlsl );
  12146. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  12147. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  12148. gl.attachShader( program, glVertexShader );
  12149. gl.attachShader( program, glFragmentShader );
  12150. // Force a particular attribute to index 0.
  12151. if ( parameters.index0AttributeName !== undefined ) {
  12152. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12153. } else if ( parameters.morphTargets === true ) {
  12154. // programs with morphTargets displace position out of attribute 0
  12155. gl.bindAttribLocation( program, 0, 'position' );
  12156. }
  12157. gl.linkProgram( program );
  12158. function onFirstUse( self ) {
  12159. // check for link errors
  12160. if ( renderer.debug.checkShaderErrors ) {
  12161. const programLog = gl.getProgramInfoLog( program ).trim();
  12162. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12163. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12164. let runnable = true;
  12165. let haveDiagnostics = true;
  12166. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12167. runnable = false;
  12168. if ( typeof renderer.debug.onShaderError === 'function' ) {
  12169. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  12170. } else {
  12171. // default error reporting
  12172. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12173. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12174. console.error(
  12175. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12176. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  12177. 'Program Info Log: ' + programLog + '\n' +
  12178. vertexErrors + '\n' +
  12179. fragmentErrors
  12180. );
  12181. }
  12182. } else if ( programLog !== '' ) {
  12183. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12184. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12185. haveDiagnostics = false;
  12186. }
  12187. if ( haveDiagnostics ) {
  12188. self.diagnostics = {
  12189. runnable: runnable,
  12190. programLog: programLog,
  12191. vertexShader: {
  12192. log: vertexLog,
  12193. prefix: prefixVertex
  12194. },
  12195. fragmentShader: {
  12196. log: fragmentLog,
  12197. prefix: prefixFragment
  12198. }
  12199. };
  12200. }
  12201. }
  12202. // Clean up
  12203. // Crashes in iOS9 and iOS10. #18402
  12204. // gl.detachShader( program, glVertexShader );
  12205. // gl.detachShader( program, glFragmentShader );
  12206. gl.deleteShader( glVertexShader );
  12207. gl.deleteShader( glFragmentShader );
  12208. cachedUniforms = new WebGLUniforms( gl, program );
  12209. cachedAttributes = fetchAttributeLocations( gl, program );
  12210. }
  12211. // set up caching for uniform locations
  12212. let cachedUniforms;
  12213. this.getUniforms = function () {
  12214. if ( cachedUniforms === undefined ) {
  12215. // Populates cachedUniforms and cachedAttributes
  12216. onFirstUse( this );
  12217. }
  12218. return cachedUniforms;
  12219. };
  12220. // set up caching for attribute locations
  12221. let cachedAttributes;
  12222. this.getAttributes = function () {
  12223. if ( cachedAttributes === undefined ) {
  12224. // Populates cachedAttributes and cachedUniforms
  12225. onFirstUse( this );
  12226. }
  12227. return cachedAttributes;
  12228. };
  12229. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  12230. // flag the program as ready immediately. It may cause a stall when it's first used.
  12231. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  12232. this.isReady = function () {
  12233. if ( programReady === false ) {
  12234. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  12235. }
  12236. return programReady;
  12237. };
  12238. // free resource
  12239. this.destroy = function () {
  12240. bindingStates.releaseStatesOfProgram( this );
  12241. gl.deleteProgram( program );
  12242. this.program = undefined;
  12243. };
  12244. //
  12245. this.type = parameters.shaderType;
  12246. this.name = parameters.shaderName;
  12247. this.id = programIdCount ++;
  12248. this.cacheKey = cacheKey;
  12249. this.usedTimes = 1;
  12250. this.program = program;
  12251. this.vertexShader = glVertexShader;
  12252. this.fragmentShader = glFragmentShader;
  12253. return this;
  12254. }
  12255. let _id$1 = 0;
  12256. class WebGLShaderCache {
  12257. constructor() {
  12258. this.shaderCache = new Map();
  12259. this.materialCache = new Map();
  12260. }
  12261. update( material ) {
  12262. const vertexShader = material.vertexShader;
  12263. const fragmentShader = material.fragmentShader;
  12264. const vertexShaderStage = this._getShaderStage( vertexShader );
  12265. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12266. const materialShaders = this._getShaderCacheForMaterial( material );
  12267. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12268. materialShaders.add( vertexShaderStage );
  12269. vertexShaderStage.usedTimes ++;
  12270. }
  12271. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12272. materialShaders.add( fragmentShaderStage );
  12273. fragmentShaderStage.usedTimes ++;
  12274. }
  12275. return this;
  12276. }
  12277. remove( material ) {
  12278. const materialShaders = this.materialCache.get( material );
  12279. for ( const shaderStage of materialShaders ) {
  12280. shaderStage.usedTimes --;
  12281. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12282. }
  12283. this.materialCache.delete( material );
  12284. return this;
  12285. }
  12286. getVertexShaderID( material ) {
  12287. return this._getShaderStage( material.vertexShader ).id;
  12288. }
  12289. getFragmentShaderID( material ) {
  12290. return this._getShaderStage( material.fragmentShader ).id;
  12291. }
  12292. dispose() {
  12293. this.shaderCache.clear();
  12294. this.materialCache.clear();
  12295. }
  12296. _getShaderCacheForMaterial( material ) {
  12297. const cache = this.materialCache;
  12298. let set = cache.get( material );
  12299. if ( set === undefined ) {
  12300. set = new Set();
  12301. cache.set( material, set );
  12302. }
  12303. return set;
  12304. }
  12305. _getShaderStage( code ) {
  12306. const cache = this.shaderCache;
  12307. let stage = cache.get( code );
  12308. if ( stage === undefined ) {
  12309. stage = new WebGLShaderStage( code );
  12310. cache.set( code, stage );
  12311. }
  12312. return stage;
  12313. }
  12314. }
  12315. class WebGLShaderStage {
  12316. constructor( code ) {
  12317. this.id = _id$1 ++;
  12318. this.code = code;
  12319. this.usedTimes = 0;
  12320. }
  12321. }
  12322. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12323. const _programLayers = new Layers();
  12324. const _customShaders = new WebGLShaderCache();
  12325. const programs = [];
  12326. const IS_WEBGL2 = capabilities.isWebGL2;
  12327. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12328. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12329. let precision = capabilities.precision;
  12330. const shaderIDs = {
  12331. MeshDepthMaterial: 'depth',
  12332. MeshDistanceMaterial: 'distanceRGBA',
  12333. MeshNormalMaterial: 'normal',
  12334. MeshBasicMaterial: 'basic',
  12335. MeshLambertMaterial: 'lambert',
  12336. MeshPhongMaterial: 'phong',
  12337. MeshToonMaterial: 'toon',
  12338. MeshStandardMaterial: 'physical',
  12339. MeshPhysicalMaterial: 'physical',
  12340. MeshMatcapMaterial: 'matcap',
  12341. LineBasicMaterial: 'basic',
  12342. LineDashedMaterial: 'dashed',
  12343. PointsMaterial: 'points',
  12344. ShadowMaterial: 'shadow',
  12345. SpriteMaterial: 'sprite'
  12346. };
  12347. function getChannel( value ) {
  12348. if ( value === 0 ) return 'uv';
  12349. return `uv${ value }`;
  12350. }
  12351. function getParameters( material, lights, shadows, scene, object ) {
  12352. const fog = scene.fog;
  12353. const geometry = object.geometry;
  12354. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12355. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12356. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12357. const shaderID = shaderIDs[ material.type ];
  12358. // heuristics to create shader parameters according to lights in the scene
  12359. // (not to blow over maxLights budget)
  12360. if ( material.precision !== null ) {
  12361. precision = capabilities.getMaxPrecision( material.precision );
  12362. if ( precision !== material.precision ) {
  12363. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12364. }
  12365. }
  12366. //
  12367. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12368. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12369. let morphTextureStride = 0;
  12370. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12371. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12372. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12373. //
  12374. let vertexShader, fragmentShader;
  12375. let customVertexShaderID, customFragmentShaderID;
  12376. if ( shaderID ) {
  12377. const shader = ShaderLib[ shaderID ];
  12378. vertexShader = shader.vertexShader;
  12379. fragmentShader = shader.fragmentShader;
  12380. } else {
  12381. vertexShader = material.vertexShader;
  12382. fragmentShader = material.fragmentShader;
  12383. _customShaders.update( material );
  12384. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12385. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12386. }
  12387. const currentRenderTarget = renderer.getRenderTarget();
  12388. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12389. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  12390. const HAS_MAP = !! material.map;
  12391. const HAS_MATCAP = !! material.matcap;
  12392. const HAS_ENVMAP = !! envMap;
  12393. const HAS_AOMAP = !! material.aoMap;
  12394. const HAS_LIGHTMAP = !! material.lightMap;
  12395. const HAS_BUMPMAP = !! material.bumpMap;
  12396. const HAS_NORMALMAP = !! material.normalMap;
  12397. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12398. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12399. const HAS_METALNESSMAP = !! material.metalnessMap;
  12400. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12401. const HAS_ANISOTROPY = material.anisotropy > 0;
  12402. const HAS_CLEARCOAT = material.clearcoat > 0;
  12403. const HAS_IRIDESCENCE = material.iridescence > 0;
  12404. const HAS_SHEEN = material.sheen > 0;
  12405. const HAS_TRANSMISSION = material.transmission > 0;
  12406. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12407. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12408. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12409. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12410. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12411. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12412. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12413. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12414. const HAS_SPECULARMAP = !! material.specularMap;
  12415. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12416. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12417. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12418. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12419. const HAS_GRADIENTMAP = !! material.gradientMap;
  12420. const HAS_ALPHAMAP = !! material.alphaMap;
  12421. const HAS_ALPHATEST = material.alphaTest > 0;
  12422. const HAS_ALPHAHASH = !! material.alphaHash;
  12423. const HAS_EXTENSIONS = !! material.extensions;
  12424. const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1;
  12425. const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;
  12426. const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3;
  12427. let toneMapping = NoToneMapping;
  12428. if ( material.toneMapped ) {
  12429. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12430. toneMapping = renderer.toneMapping;
  12431. }
  12432. }
  12433. const parameters = {
  12434. isWebGL2: IS_WEBGL2,
  12435. shaderID: shaderID,
  12436. shaderType: material.type,
  12437. shaderName: material.name,
  12438. vertexShader: vertexShader,
  12439. fragmentShader: fragmentShader,
  12440. defines: material.defines,
  12441. customVertexShaderID: customVertexShaderID,
  12442. customFragmentShaderID: customFragmentShaderID,
  12443. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12444. glslVersion: material.glslVersion,
  12445. precision: precision,
  12446. batching: IS_BATCHEDMESH,
  12447. instancing: IS_INSTANCEDMESH,
  12448. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12449. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12450. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12451. map: HAS_MAP,
  12452. matcap: HAS_MATCAP,
  12453. envMap: HAS_ENVMAP,
  12454. envMapMode: HAS_ENVMAP && envMap.mapping,
  12455. envMapCubeUVHeight: envMapCubeUVHeight,
  12456. aoMap: HAS_AOMAP,
  12457. lightMap: HAS_LIGHTMAP,
  12458. bumpMap: HAS_BUMPMAP,
  12459. normalMap: HAS_NORMALMAP,
  12460. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12461. emissiveMap: HAS_EMISSIVEMAP,
  12462. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12463. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12464. metalnessMap: HAS_METALNESSMAP,
  12465. roughnessMap: HAS_ROUGHNESSMAP,
  12466. anisotropy: HAS_ANISOTROPY,
  12467. anisotropyMap: HAS_ANISOTROPYMAP,
  12468. clearcoat: HAS_CLEARCOAT,
  12469. clearcoatMap: HAS_CLEARCOATMAP,
  12470. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12471. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12472. iridescence: HAS_IRIDESCENCE,
  12473. iridescenceMap: HAS_IRIDESCENCEMAP,
  12474. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12475. sheen: HAS_SHEEN,
  12476. sheenColorMap: HAS_SHEEN_COLORMAP,
  12477. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12478. specularMap: HAS_SPECULARMAP,
  12479. specularColorMap: HAS_SPECULAR_COLORMAP,
  12480. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12481. transmission: HAS_TRANSMISSION,
  12482. transmissionMap: HAS_TRANSMISSIONMAP,
  12483. thicknessMap: HAS_THICKNESSMAP,
  12484. gradientMap: HAS_GRADIENTMAP,
  12485. opaque: material.transparent === false && material.blending === NormalBlending,
  12486. alphaMap: HAS_ALPHAMAP,
  12487. alphaTest: HAS_ALPHATEST,
  12488. alphaHash: HAS_ALPHAHASH,
  12489. combine: material.combine,
  12490. //
  12491. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12492. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12493. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12494. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12495. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12496. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12497. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12498. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12499. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12500. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12501. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12502. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12503. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12504. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12505. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12506. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12507. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12508. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12509. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12510. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12511. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12512. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12513. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12514. //
  12515. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12516. vertexColors: material.vertexColors,
  12517. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12518. vertexUv1s: HAS_ATTRIBUTE_UV1,
  12519. vertexUv2s: HAS_ATTRIBUTE_UV2,
  12520. vertexUv3s: HAS_ATTRIBUTE_UV3,
  12521. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12522. fog: !! fog,
  12523. useFog: material.fog === true,
  12524. fogExp2: ( fog && fog.isFogExp2 ),
  12525. flatShading: material.flatShading === true,
  12526. sizeAttenuation: material.sizeAttenuation === true,
  12527. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12528. skinning: object.isSkinnedMesh === true,
  12529. morphTargets: geometry.morphAttributes.position !== undefined,
  12530. morphNormals: geometry.morphAttributes.normal !== undefined,
  12531. morphColors: geometry.morphAttributes.color !== undefined,
  12532. morphTargetsCount: morphTargetsCount,
  12533. morphTextureStride: morphTextureStride,
  12534. numDirLights: lights.directional.length,
  12535. numPointLights: lights.point.length,
  12536. numSpotLights: lights.spot.length,
  12537. numSpotLightMaps: lights.spotLightMap.length,
  12538. numRectAreaLights: lights.rectArea.length,
  12539. numHemiLights: lights.hemi.length,
  12540. numDirLightShadows: lights.directionalShadowMap.length,
  12541. numPointLightShadows: lights.pointShadowMap.length,
  12542. numSpotLightShadows: lights.spotShadowMap.length,
  12543. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12544. numLightProbes: lights.numLightProbes,
  12545. numClippingPlanes: clipping.numPlanes,
  12546. numClipIntersection: clipping.numIntersection,
  12547. dithering: material.dithering,
  12548. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12549. shadowMapType: renderer.shadowMap.type,
  12550. toneMapping: toneMapping,
  12551. useLegacyLights: renderer._useLegacyLights,
  12552. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12553. premultipliedAlpha: material.premultipliedAlpha,
  12554. doubleSided: material.side === DoubleSide,
  12555. flipSided: material.side === BackSide,
  12556. useDepthPacking: material.depthPacking >= 0,
  12557. depthPacking: material.depthPacking || 0,
  12558. index0AttributeName: material.index0AttributeName,
  12559. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12560. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12561. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12562. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12563. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance && extensions.has( 'WEBGL_clip_cull_distance' ),
  12564. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12565. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12566. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12567. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  12568. customProgramCacheKey: material.customProgramCacheKey()
  12569. };
  12570. return parameters;
  12571. }
  12572. function getProgramCacheKey( parameters ) {
  12573. const array = [];
  12574. if ( parameters.shaderID ) {
  12575. array.push( parameters.shaderID );
  12576. } else {
  12577. array.push( parameters.customVertexShaderID );
  12578. array.push( parameters.customFragmentShaderID );
  12579. }
  12580. if ( parameters.defines !== undefined ) {
  12581. for ( const name in parameters.defines ) {
  12582. array.push( name );
  12583. array.push( parameters.defines[ name ] );
  12584. }
  12585. }
  12586. if ( parameters.isRawShaderMaterial === false ) {
  12587. getProgramCacheKeyParameters( array, parameters );
  12588. getProgramCacheKeyBooleans( array, parameters );
  12589. array.push( renderer.outputColorSpace );
  12590. }
  12591. array.push( parameters.customProgramCacheKey );
  12592. return array.join();
  12593. }
  12594. function getProgramCacheKeyParameters( array, parameters ) {
  12595. array.push( parameters.precision );
  12596. array.push( parameters.outputColorSpace );
  12597. array.push( parameters.envMapMode );
  12598. array.push( parameters.envMapCubeUVHeight );
  12599. array.push( parameters.mapUv );
  12600. array.push( parameters.alphaMapUv );
  12601. array.push( parameters.lightMapUv );
  12602. array.push( parameters.aoMapUv );
  12603. array.push( parameters.bumpMapUv );
  12604. array.push( parameters.normalMapUv );
  12605. array.push( parameters.displacementMapUv );
  12606. array.push( parameters.emissiveMapUv );
  12607. array.push( parameters.metalnessMapUv );
  12608. array.push( parameters.roughnessMapUv );
  12609. array.push( parameters.anisotropyMapUv );
  12610. array.push( parameters.clearcoatMapUv );
  12611. array.push( parameters.clearcoatNormalMapUv );
  12612. array.push( parameters.clearcoatRoughnessMapUv );
  12613. array.push( parameters.iridescenceMapUv );
  12614. array.push( parameters.iridescenceThicknessMapUv );
  12615. array.push( parameters.sheenColorMapUv );
  12616. array.push( parameters.sheenRoughnessMapUv );
  12617. array.push( parameters.specularMapUv );
  12618. array.push( parameters.specularColorMapUv );
  12619. array.push( parameters.specularIntensityMapUv );
  12620. array.push( parameters.transmissionMapUv );
  12621. array.push( parameters.thicknessMapUv );
  12622. array.push( parameters.combine );
  12623. array.push( parameters.fogExp2 );
  12624. array.push( parameters.sizeAttenuation );
  12625. array.push( parameters.morphTargetsCount );
  12626. array.push( parameters.morphAttributeCount );
  12627. array.push( parameters.numDirLights );
  12628. array.push( parameters.numPointLights );
  12629. array.push( parameters.numSpotLights );
  12630. array.push( parameters.numSpotLightMaps );
  12631. array.push( parameters.numHemiLights );
  12632. array.push( parameters.numRectAreaLights );
  12633. array.push( parameters.numDirLightShadows );
  12634. array.push( parameters.numPointLightShadows );
  12635. array.push( parameters.numSpotLightShadows );
  12636. array.push( parameters.numSpotLightShadowsWithMaps );
  12637. array.push( parameters.numLightProbes );
  12638. array.push( parameters.shadowMapType );
  12639. array.push( parameters.toneMapping );
  12640. array.push( parameters.numClippingPlanes );
  12641. array.push( parameters.numClipIntersection );
  12642. array.push( parameters.depthPacking );
  12643. }
  12644. function getProgramCacheKeyBooleans( array, parameters ) {
  12645. _programLayers.disableAll();
  12646. if ( parameters.isWebGL2 )
  12647. _programLayers.enable( 0 );
  12648. if ( parameters.supportsVertexTextures )
  12649. _programLayers.enable( 1 );
  12650. if ( parameters.instancing )
  12651. _programLayers.enable( 2 );
  12652. if ( parameters.instancingColor )
  12653. _programLayers.enable( 3 );
  12654. if ( parameters.matcap )
  12655. _programLayers.enable( 4 );
  12656. if ( parameters.envMap )
  12657. _programLayers.enable( 5 );
  12658. if ( parameters.normalMapObjectSpace )
  12659. _programLayers.enable( 6 );
  12660. if ( parameters.normalMapTangentSpace )
  12661. _programLayers.enable( 7 );
  12662. if ( parameters.clearcoat )
  12663. _programLayers.enable( 8 );
  12664. if ( parameters.iridescence )
  12665. _programLayers.enable( 9 );
  12666. if ( parameters.alphaTest )
  12667. _programLayers.enable( 10 );
  12668. if ( parameters.vertexColors )
  12669. _programLayers.enable( 11 );
  12670. if ( parameters.vertexAlphas )
  12671. _programLayers.enable( 12 );
  12672. if ( parameters.vertexUv1s )
  12673. _programLayers.enable( 13 );
  12674. if ( parameters.vertexUv2s )
  12675. _programLayers.enable( 14 );
  12676. if ( parameters.vertexUv3s )
  12677. _programLayers.enable( 15 );
  12678. if ( parameters.vertexTangents )
  12679. _programLayers.enable( 16 );
  12680. if ( parameters.anisotropy )
  12681. _programLayers.enable( 17 );
  12682. if ( parameters.alphaHash )
  12683. _programLayers.enable( 18 );
  12684. if ( parameters.batching )
  12685. _programLayers.enable( 19 );
  12686. array.push( _programLayers.mask );
  12687. _programLayers.disableAll();
  12688. if ( parameters.fog )
  12689. _programLayers.enable( 0 );
  12690. if ( parameters.useFog )
  12691. _programLayers.enable( 1 );
  12692. if ( parameters.flatShading )
  12693. _programLayers.enable( 2 );
  12694. if ( parameters.logarithmicDepthBuffer )
  12695. _programLayers.enable( 3 );
  12696. if ( parameters.skinning )
  12697. _programLayers.enable( 4 );
  12698. if ( parameters.morphTargets )
  12699. _programLayers.enable( 5 );
  12700. if ( parameters.morphNormals )
  12701. _programLayers.enable( 6 );
  12702. if ( parameters.morphColors )
  12703. _programLayers.enable( 7 );
  12704. if ( parameters.premultipliedAlpha )
  12705. _programLayers.enable( 8 );
  12706. if ( parameters.shadowMapEnabled )
  12707. _programLayers.enable( 9 );
  12708. if ( parameters.useLegacyLights )
  12709. _programLayers.enable( 10 );
  12710. if ( parameters.doubleSided )
  12711. _programLayers.enable( 11 );
  12712. if ( parameters.flipSided )
  12713. _programLayers.enable( 12 );
  12714. if ( parameters.useDepthPacking )
  12715. _programLayers.enable( 13 );
  12716. if ( parameters.dithering )
  12717. _programLayers.enable( 14 );
  12718. if ( parameters.transmission )
  12719. _programLayers.enable( 15 );
  12720. if ( parameters.sheen )
  12721. _programLayers.enable( 16 );
  12722. if ( parameters.opaque )
  12723. _programLayers.enable( 17 );
  12724. if ( parameters.pointsUvs )
  12725. _programLayers.enable( 18 );
  12726. if ( parameters.decodeVideoTexture )
  12727. _programLayers.enable( 19 );
  12728. array.push( _programLayers.mask );
  12729. }
  12730. function getUniforms( material ) {
  12731. const shaderID = shaderIDs[ material.type ];
  12732. let uniforms;
  12733. if ( shaderID ) {
  12734. const shader = ShaderLib[ shaderID ];
  12735. uniforms = UniformsUtils.clone( shader.uniforms );
  12736. } else {
  12737. uniforms = material.uniforms;
  12738. }
  12739. return uniforms;
  12740. }
  12741. function acquireProgram( parameters, cacheKey ) {
  12742. let program;
  12743. // Check if code has been already compiled
  12744. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12745. const preexistingProgram = programs[ p ];
  12746. if ( preexistingProgram.cacheKey === cacheKey ) {
  12747. program = preexistingProgram;
  12748. ++ program.usedTimes;
  12749. break;
  12750. }
  12751. }
  12752. if ( program === undefined ) {
  12753. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12754. programs.push( program );
  12755. }
  12756. return program;
  12757. }
  12758. function releaseProgram( program ) {
  12759. if ( -- program.usedTimes === 0 ) {
  12760. // Remove from unordered set
  12761. const i = programs.indexOf( program );
  12762. programs[ i ] = programs[ programs.length - 1 ];
  12763. programs.pop();
  12764. // Free WebGL resources
  12765. program.destroy();
  12766. }
  12767. }
  12768. function releaseShaderCache( material ) {
  12769. _customShaders.remove( material );
  12770. }
  12771. function dispose() {
  12772. _customShaders.dispose();
  12773. }
  12774. return {
  12775. getParameters: getParameters,
  12776. getProgramCacheKey: getProgramCacheKey,
  12777. getUniforms: getUniforms,
  12778. acquireProgram: acquireProgram,
  12779. releaseProgram: releaseProgram,
  12780. releaseShaderCache: releaseShaderCache,
  12781. // Exposed for resource monitoring & error feedback via renderer.info:
  12782. programs: programs,
  12783. dispose: dispose
  12784. };
  12785. }
  12786. function WebGLProperties() {
  12787. let properties = new WeakMap();
  12788. function get( object ) {
  12789. let map = properties.get( object );
  12790. if ( map === undefined ) {
  12791. map = {};
  12792. properties.set( object, map );
  12793. }
  12794. return map;
  12795. }
  12796. function remove( object ) {
  12797. properties.delete( object );
  12798. }
  12799. function update( object, key, value ) {
  12800. properties.get( object )[ key ] = value;
  12801. }
  12802. function dispose() {
  12803. properties = new WeakMap();
  12804. }
  12805. return {
  12806. get: get,
  12807. remove: remove,
  12808. update: update,
  12809. dispose: dispose
  12810. };
  12811. }
  12812. function painterSortStable( a, b ) {
  12813. if ( a.groupOrder !== b.groupOrder ) {
  12814. return a.groupOrder - b.groupOrder;
  12815. } else if ( a.renderOrder !== b.renderOrder ) {
  12816. return a.renderOrder - b.renderOrder;
  12817. } else if ( a.material.id !== b.material.id ) {
  12818. return a.material.id - b.material.id;
  12819. } else if ( a.z !== b.z ) {
  12820. return a.z - b.z;
  12821. } else {
  12822. return a.id - b.id;
  12823. }
  12824. }
  12825. function reversePainterSortStable( a, b ) {
  12826. if ( a.groupOrder !== b.groupOrder ) {
  12827. return a.groupOrder - b.groupOrder;
  12828. } else if ( a.renderOrder !== b.renderOrder ) {
  12829. return a.renderOrder - b.renderOrder;
  12830. } else if ( a.z !== b.z ) {
  12831. return b.z - a.z;
  12832. } else {
  12833. return a.id - b.id;
  12834. }
  12835. }
  12836. function WebGLRenderList() {
  12837. const renderItems = [];
  12838. let renderItemsIndex = 0;
  12839. const opaque = [];
  12840. const transmissive = [];
  12841. const transparent = [];
  12842. function init() {
  12843. renderItemsIndex = 0;
  12844. opaque.length = 0;
  12845. transmissive.length = 0;
  12846. transparent.length = 0;
  12847. }
  12848. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12849. let renderItem = renderItems[ renderItemsIndex ];
  12850. if ( renderItem === undefined ) {
  12851. renderItem = {
  12852. id: object.id,
  12853. object: object,
  12854. geometry: geometry,
  12855. material: material,
  12856. groupOrder: groupOrder,
  12857. renderOrder: object.renderOrder,
  12858. z: z,
  12859. group: group
  12860. };
  12861. renderItems[ renderItemsIndex ] = renderItem;
  12862. } else {
  12863. renderItem.id = object.id;
  12864. renderItem.object = object;
  12865. renderItem.geometry = geometry;
  12866. renderItem.material = material;
  12867. renderItem.groupOrder = groupOrder;
  12868. renderItem.renderOrder = object.renderOrder;
  12869. renderItem.z = z;
  12870. renderItem.group = group;
  12871. }
  12872. renderItemsIndex ++;
  12873. return renderItem;
  12874. }
  12875. function push( object, geometry, material, groupOrder, z, group ) {
  12876. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12877. if ( material.transmission > 0.0 ) {
  12878. transmissive.push( renderItem );
  12879. } else if ( material.transparent === true ) {
  12880. transparent.push( renderItem );
  12881. } else {
  12882. opaque.push( renderItem );
  12883. }
  12884. }
  12885. function unshift( object, geometry, material, groupOrder, z, group ) {
  12886. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12887. if ( material.transmission > 0.0 ) {
  12888. transmissive.unshift( renderItem );
  12889. } else if ( material.transparent === true ) {
  12890. transparent.unshift( renderItem );
  12891. } else {
  12892. opaque.unshift( renderItem );
  12893. }
  12894. }
  12895. function sort( customOpaqueSort, customTransparentSort ) {
  12896. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12897. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12898. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12899. }
  12900. function finish() {
  12901. // Clear references from inactive renderItems in the list
  12902. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12903. const renderItem = renderItems[ i ];
  12904. if ( renderItem.id === null ) break;
  12905. renderItem.id = null;
  12906. renderItem.object = null;
  12907. renderItem.geometry = null;
  12908. renderItem.material = null;
  12909. renderItem.group = null;
  12910. }
  12911. }
  12912. return {
  12913. opaque: opaque,
  12914. transmissive: transmissive,
  12915. transparent: transparent,
  12916. init: init,
  12917. push: push,
  12918. unshift: unshift,
  12919. finish: finish,
  12920. sort: sort
  12921. };
  12922. }
  12923. function WebGLRenderLists() {
  12924. let lists = new WeakMap();
  12925. function get( scene, renderCallDepth ) {
  12926. const listArray = lists.get( scene );
  12927. let list;
  12928. if ( listArray === undefined ) {
  12929. list = new WebGLRenderList();
  12930. lists.set( scene, [ list ] );
  12931. } else {
  12932. if ( renderCallDepth >= listArray.length ) {
  12933. list = new WebGLRenderList();
  12934. listArray.push( list );
  12935. } else {
  12936. list = listArray[ renderCallDepth ];
  12937. }
  12938. }
  12939. return list;
  12940. }
  12941. function dispose() {
  12942. lists = new WeakMap();
  12943. }
  12944. return {
  12945. get: get,
  12946. dispose: dispose
  12947. };
  12948. }
  12949. function UniformsCache() {
  12950. const lights = {};
  12951. return {
  12952. get: function ( light ) {
  12953. if ( lights[ light.id ] !== undefined ) {
  12954. return lights[ light.id ];
  12955. }
  12956. let uniforms;
  12957. switch ( light.type ) {
  12958. case 'DirectionalLight':
  12959. uniforms = {
  12960. direction: new Vector3(),
  12961. color: new Color()
  12962. };
  12963. break;
  12964. case 'SpotLight':
  12965. uniforms = {
  12966. position: new Vector3(),
  12967. direction: new Vector3(),
  12968. color: new Color(),
  12969. distance: 0,
  12970. coneCos: 0,
  12971. penumbraCos: 0,
  12972. decay: 0
  12973. };
  12974. break;
  12975. case 'PointLight':
  12976. uniforms = {
  12977. position: new Vector3(),
  12978. color: new Color(),
  12979. distance: 0,
  12980. decay: 0
  12981. };
  12982. break;
  12983. case 'HemisphereLight':
  12984. uniforms = {
  12985. direction: new Vector3(),
  12986. skyColor: new Color(),
  12987. groundColor: new Color()
  12988. };
  12989. break;
  12990. case 'RectAreaLight':
  12991. uniforms = {
  12992. color: new Color(),
  12993. position: new Vector3(),
  12994. halfWidth: new Vector3(),
  12995. halfHeight: new Vector3()
  12996. };
  12997. break;
  12998. }
  12999. lights[ light.id ] = uniforms;
  13000. return uniforms;
  13001. }
  13002. };
  13003. }
  13004. function ShadowUniformsCache() {
  13005. const lights = {};
  13006. return {
  13007. get: function ( light ) {
  13008. if ( lights[ light.id ] !== undefined ) {
  13009. return lights[ light.id ];
  13010. }
  13011. let uniforms;
  13012. switch ( light.type ) {
  13013. case 'DirectionalLight':
  13014. uniforms = {
  13015. shadowBias: 0,
  13016. shadowNormalBias: 0,
  13017. shadowRadius: 1,
  13018. shadowMapSize: new Vector2()
  13019. };
  13020. break;
  13021. case 'SpotLight':
  13022. uniforms = {
  13023. shadowBias: 0,
  13024. shadowNormalBias: 0,
  13025. shadowRadius: 1,
  13026. shadowMapSize: new Vector2()
  13027. };
  13028. break;
  13029. case 'PointLight':
  13030. uniforms = {
  13031. shadowBias: 0,
  13032. shadowNormalBias: 0,
  13033. shadowRadius: 1,
  13034. shadowMapSize: new Vector2(),
  13035. shadowCameraNear: 1,
  13036. shadowCameraFar: 1000
  13037. };
  13038. break;
  13039. // TODO (abelnation): set RectAreaLight shadow uniforms
  13040. }
  13041. lights[ light.id ] = uniforms;
  13042. return uniforms;
  13043. }
  13044. };
  13045. }
  13046. let nextVersion = 0;
  13047. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  13048. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  13049. }
  13050. function WebGLLights( extensions, capabilities ) {
  13051. const cache = new UniformsCache();
  13052. const shadowCache = ShadowUniformsCache();
  13053. const state = {
  13054. version: 0,
  13055. hash: {
  13056. directionalLength: - 1,
  13057. pointLength: - 1,
  13058. spotLength: - 1,
  13059. rectAreaLength: - 1,
  13060. hemiLength: - 1,
  13061. numDirectionalShadows: - 1,
  13062. numPointShadows: - 1,
  13063. numSpotShadows: - 1,
  13064. numSpotMaps: - 1,
  13065. numLightProbes: - 1
  13066. },
  13067. ambient: [ 0, 0, 0 ],
  13068. probe: [],
  13069. directional: [],
  13070. directionalShadow: [],
  13071. directionalShadowMap: [],
  13072. directionalShadowMatrix: [],
  13073. spot: [],
  13074. spotLightMap: [],
  13075. spotShadow: [],
  13076. spotShadowMap: [],
  13077. spotLightMatrix: [],
  13078. rectArea: [],
  13079. rectAreaLTC1: null,
  13080. rectAreaLTC2: null,
  13081. point: [],
  13082. pointShadow: [],
  13083. pointShadowMap: [],
  13084. pointShadowMatrix: [],
  13085. hemi: [],
  13086. numSpotLightShadowsWithMaps: 0,
  13087. numLightProbes: 0
  13088. };
  13089. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  13090. const vector3 = new Vector3();
  13091. const matrix4 = new Matrix4();
  13092. const matrix42 = new Matrix4();
  13093. function setup( lights, useLegacyLights ) {
  13094. let r = 0, g = 0, b = 0;
  13095. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  13096. let directionalLength = 0;
  13097. let pointLength = 0;
  13098. let spotLength = 0;
  13099. let rectAreaLength = 0;
  13100. let hemiLength = 0;
  13101. let numDirectionalShadows = 0;
  13102. let numPointShadows = 0;
  13103. let numSpotShadows = 0;
  13104. let numSpotMaps = 0;
  13105. let numSpotShadowsWithMaps = 0;
  13106. let numLightProbes = 0;
  13107. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  13108. lights.sort( shadowCastingAndTexturingLightsFirst );
  13109. // artist-friendly light intensity scaling factor
  13110. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  13111. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13112. const light = lights[ i ];
  13113. const color = light.color;
  13114. const intensity = light.intensity;
  13115. const distance = light.distance;
  13116. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13117. if ( light.isAmbientLight ) {
  13118. r += color.r * intensity * scaleFactor;
  13119. g += color.g * intensity * scaleFactor;
  13120. b += color.b * intensity * scaleFactor;
  13121. } else if ( light.isLightProbe ) {
  13122. for ( let j = 0; j < 9; j ++ ) {
  13123. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  13124. }
  13125. numLightProbes ++;
  13126. } else if ( light.isDirectionalLight ) {
  13127. const uniforms = cache.get( light );
  13128. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13129. if ( light.castShadow ) {
  13130. const shadow = light.shadow;
  13131. const shadowUniforms = shadowCache.get( light );
  13132. shadowUniforms.shadowBias = shadow.bias;
  13133. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13134. shadowUniforms.shadowRadius = shadow.radius;
  13135. shadowUniforms.shadowMapSize = shadow.mapSize;
  13136. state.directionalShadow[ directionalLength ] = shadowUniforms;
  13137. state.directionalShadowMap[ directionalLength ] = shadowMap;
  13138. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13139. numDirectionalShadows ++;
  13140. }
  13141. state.directional[ directionalLength ] = uniforms;
  13142. directionalLength ++;
  13143. } else if ( light.isSpotLight ) {
  13144. const uniforms = cache.get( light );
  13145. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13146. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  13147. uniforms.distance = distance;
  13148. uniforms.coneCos = Math.cos( light.angle );
  13149. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13150. uniforms.decay = light.decay;
  13151. state.spot[ spotLength ] = uniforms;
  13152. const shadow = light.shadow;
  13153. if ( light.map ) {
  13154. state.spotLightMap[ numSpotMaps ] = light.map;
  13155. numSpotMaps ++;
  13156. // make sure the lightMatrix is up to date
  13157. // TODO : do it if required only
  13158. shadow.updateMatrices( light );
  13159. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  13160. }
  13161. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  13162. if ( light.castShadow ) {
  13163. const shadowUniforms = shadowCache.get( light );
  13164. shadowUniforms.shadowBias = shadow.bias;
  13165. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13166. shadowUniforms.shadowRadius = shadow.radius;
  13167. shadowUniforms.shadowMapSize = shadow.mapSize;
  13168. state.spotShadow[ spotLength ] = shadowUniforms;
  13169. state.spotShadowMap[ spotLength ] = shadowMap;
  13170. numSpotShadows ++;
  13171. }
  13172. spotLength ++;
  13173. } else if ( light.isRectAreaLight ) {
  13174. const uniforms = cache.get( light );
  13175. uniforms.color.copy( color ).multiplyScalar( intensity );
  13176. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13177. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13178. state.rectArea[ rectAreaLength ] = uniforms;
  13179. rectAreaLength ++;
  13180. } else if ( light.isPointLight ) {
  13181. const uniforms = cache.get( light );
  13182. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13183. uniforms.distance = light.distance;
  13184. uniforms.decay = light.decay;
  13185. if ( light.castShadow ) {
  13186. const shadow = light.shadow;
  13187. const shadowUniforms = shadowCache.get( light );
  13188. shadowUniforms.shadowBias = shadow.bias;
  13189. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13190. shadowUniforms.shadowRadius = shadow.radius;
  13191. shadowUniforms.shadowMapSize = shadow.mapSize;
  13192. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13193. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13194. state.pointShadow[ pointLength ] = shadowUniforms;
  13195. state.pointShadowMap[ pointLength ] = shadowMap;
  13196. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13197. numPointShadows ++;
  13198. }
  13199. state.point[ pointLength ] = uniforms;
  13200. pointLength ++;
  13201. } else if ( light.isHemisphereLight ) {
  13202. const uniforms = cache.get( light );
  13203. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  13204. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  13205. state.hemi[ hemiLength ] = uniforms;
  13206. hemiLength ++;
  13207. }
  13208. }
  13209. if ( rectAreaLength > 0 ) {
  13210. if ( capabilities.isWebGL2 ) {
  13211. // WebGL 2
  13212. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13213. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13214. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13215. } else {
  13216. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13217. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13218. }
  13219. } else {
  13220. // WebGL 1
  13221. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13222. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13223. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13224. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  13225. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13226. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13227. } else {
  13228. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  13229. }
  13230. }
  13231. }
  13232. state.ambient[ 0 ] = r;
  13233. state.ambient[ 1 ] = g;
  13234. state.ambient[ 2 ] = b;
  13235. const hash = state.hash;
  13236. if ( hash.directionalLength !== directionalLength ||
  13237. hash.pointLength !== pointLength ||
  13238. hash.spotLength !== spotLength ||
  13239. hash.rectAreaLength !== rectAreaLength ||
  13240. hash.hemiLength !== hemiLength ||
  13241. hash.numDirectionalShadows !== numDirectionalShadows ||
  13242. hash.numPointShadows !== numPointShadows ||
  13243. hash.numSpotShadows !== numSpotShadows ||
  13244. hash.numSpotMaps !== numSpotMaps ||
  13245. hash.numLightProbes !== numLightProbes ) {
  13246. state.directional.length = directionalLength;
  13247. state.spot.length = spotLength;
  13248. state.rectArea.length = rectAreaLength;
  13249. state.point.length = pointLength;
  13250. state.hemi.length = hemiLength;
  13251. state.directionalShadow.length = numDirectionalShadows;
  13252. state.directionalShadowMap.length = numDirectionalShadows;
  13253. state.pointShadow.length = numPointShadows;
  13254. state.pointShadowMap.length = numPointShadows;
  13255. state.spotShadow.length = numSpotShadows;
  13256. state.spotShadowMap.length = numSpotShadows;
  13257. state.directionalShadowMatrix.length = numDirectionalShadows;
  13258. state.pointShadowMatrix.length = numPointShadows;
  13259. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13260. state.spotLightMap.length = numSpotMaps;
  13261. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13262. state.numLightProbes = numLightProbes;
  13263. hash.directionalLength = directionalLength;
  13264. hash.pointLength = pointLength;
  13265. hash.spotLength = spotLength;
  13266. hash.rectAreaLength = rectAreaLength;
  13267. hash.hemiLength = hemiLength;
  13268. hash.numDirectionalShadows = numDirectionalShadows;
  13269. hash.numPointShadows = numPointShadows;
  13270. hash.numSpotShadows = numSpotShadows;
  13271. hash.numSpotMaps = numSpotMaps;
  13272. hash.numLightProbes = numLightProbes;
  13273. state.version = nextVersion ++;
  13274. }
  13275. }
  13276. function setupView( lights, camera ) {
  13277. let directionalLength = 0;
  13278. let pointLength = 0;
  13279. let spotLength = 0;
  13280. let rectAreaLength = 0;
  13281. let hemiLength = 0;
  13282. const viewMatrix = camera.matrixWorldInverse;
  13283. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13284. const light = lights[ i ];
  13285. if ( light.isDirectionalLight ) {
  13286. const uniforms = state.directional[ directionalLength ];
  13287. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13288. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13289. uniforms.direction.sub( vector3 );
  13290. uniforms.direction.transformDirection( viewMatrix );
  13291. directionalLength ++;
  13292. } else if ( light.isSpotLight ) {
  13293. const uniforms = state.spot[ spotLength ];
  13294. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13295. uniforms.position.applyMatrix4( viewMatrix );
  13296. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13297. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13298. uniforms.direction.sub( vector3 );
  13299. uniforms.direction.transformDirection( viewMatrix );
  13300. spotLength ++;
  13301. } else if ( light.isRectAreaLight ) {
  13302. const uniforms = state.rectArea[ rectAreaLength ];
  13303. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13304. uniforms.position.applyMatrix4( viewMatrix );
  13305. // extract local rotation of light to derive width/height half vectors
  13306. matrix42.identity();
  13307. matrix4.copy( light.matrixWorld );
  13308. matrix4.premultiply( viewMatrix );
  13309. matrix42.extractRotation( matrix4 );
  13310. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13311. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13312. uniforms.halfWidth.applyMatrix4( matrix42 );
  13313. uniforms.halfHeight.applyMatrix4( matrix42 );
  13314. rectAreaLength ++;
  13315. } else if ( light.isPointLight ) {
  13316. const uniforms = state.point[ pointLength ];
  13317. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13318. uniforms.position.applyMatrix4( viewMatrix );
  13319. pointLength ++;
  13320. } else if ( light.isHemisphereLight ) {
  13321. const uniforms = state.hemi[ hemiLength ];
  13322. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13323. uniforms.direction.transformDirection( viewMatrix );
  13324. hemiLength ++;
  13325. }
  13326. }
  13327. }
  13328. return {
  13329. setup: setup,
  13330. setupView: setupView,
  13331. state: state
  13332. };
  13333. }
  13334. function WebGLRenderState( extensions, capabilities ) {
  13335. const lights = new WebGLLights( extensions, capabilities );
  13336. const lightsArray = [];
  13337. const shadowsArray = [];
  13338. function init() {
  13339. lightsArray.length = 0;
  13340. shadowsArray.length = 0;
  13341. }
  13342. function pushLight( light ) {
  13343. lightsArray.push( light );
  13344. }
  13345. function pushShadow( shadowLight ) {
  13346. shadowsArray.push( shadowLight );
  13347. }
  13348. function setupLights( useLegacyLights ) {
  13349. lights.setup( lightsArray, useLegacyLights );
  13350. }
  13351. function setupLightsView( camera ) {
  13352. lights.setupView( lightsArray, camera );
  13353. }
  13354. const state = {
  13355. lightsArray: lightsArray,
  13356. shadowsArray: shadowsArray,
  13357. lights: lights
  13358. };
  13359. return {
  13360. init: init,
  13361. state: state,
  13362. setupLights: setupLights,
  13363. setupLightsView: setupLightsView,
  13364. pushLight: pushLight,
  13365. pushShadow: pushShadow
  13366. };
  13367. }
  13368. function WebGLRenderStates( extensions, capabilities ) {
  13369. let renderStates = new WeakMap();
  13370. function get( scene, renderCallDepth = 0 ) {
  13371. const renderStateArray = renderStates.get( scene );
  13372. let renderState;
  13373. if ( renderStateArray === undefined ) {
  13374. renderState = new WebGLRenderState( extensions, capabilities );
  13375. renderStates.set( scene, [ renderState ] );
  13376. } else {
  13377. if ( renderCallDepth >= renderStateArray.length ) {
  13378. renderState = new WebGLRenderState( extensions, capabilities );
  13379. renderStateArray.push( renderState );
  13380. } else {
  13381. renderState = renderStateArray[ renderCallDepth ];
  13382. }
  13383. }
  13384. return renderState;
  13385. }
  13386. function dispose() {
  13387. renderStates = new WeakMap();
  13388. }
  13389. return {
  13390. get: get,
  13391. dispose: dispose
  13392. };
  13393. }
  13394. class MeshDepthMaterial extends Material {
  13395. constructor( parameters ) {
  13396. super();
  13397. this.isMeshDepthMaterial = true;
  13398. this.type = 'MeshDepthMaterial';
  13399. this.depthPacking = BasicDepthPacking;
  13400. this.map = null;
  13401. this.alphaMap = null;
  13402. this.displacementMap = null;
  13403. this.displacementScale = 1;
  13404. this.displacementBias = 0;
  13405. this.wireframe = false;
  13406. this.wireframeLinewidth = 1;
  13407. this.setValues( parameters );
  13408. }
  13409. copy( source ) {
  13410. super.copy( source );
  13411. this.depthPacking = source.depthPacking;
  13412. this.map = source.map;
  13413. this.alphaMap = source.alphaMap;
  13414. this.displacementMap = source.displacementMap;
  13415. this.displacementScale = source.displacementScale;
  13416. this.displacementBias = source.displacementBias;
  13417. this.wireframe = source.wireframe;
  13418. this.wireframeLinewidth = source.wireframeLinewidth;
  13419. return this;
  13420. }
  13421. }
  13422. class MeshDistanceMaterial extends Material {
  13423. constructor( parameters ) {
  13424. super();
  13425. this.isMeshDistanceMaterial = true;
  13426. this.type = 'MeshDistanceMaterial';
  13427. this.map = null;
  13428. this.alphaMap = null;
  13429. this.displacementMap = null;
  13430. this.displacementScale = 1;
  13431. this.displacementBias = 0;
  13432. this.setValues( parameters );
  13433. }
  13434. copy( source ) {
  13435. super.copy( source );
  13436. this.map = source.map;
  13437. this.alphaMap = source.alphaMap;
  13438. this.displacementMap = source.displacementMap;
  13439. this.displacementScale = source.displacementScale;
  13440. this.displacementBias = source.displacementBias;
  13441. return this;
  13442. }
  13443. }
  13444. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13445. 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}";
  13446. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13447. let _frustum = new Frustum();
  13448. const _shadowMapSize = new Vector2(),
  13449. _viewportSize = new Vector2(),
  13450. _viewport = new Vector4(),
  13451. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13452. _distanceMaterial = new MeshDistanceMaterial(),
  13453. _materialCache = {},
  13454. _maxTextureSize = _capabilities.maxTextureSize;
  13455. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13456. const shadowMaterialVertical = new ShaderMaterial( {
  13457. defines: {
  13458. VSM_SAMPLES: 8
  13459. },
  13460. uniforms: {
  13461. shadow_pass: { value: null },
  13462. resolution: { value: new Vector2() },
  13463. radius: { value: 4.0 }
  13464. },
  13465. vertexShader: vertex,
  13466. fragmentShader: fragment
  13467. } );
  13468. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13469. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13470. const fullScreenTri = new BufferGeometry();
  13471. fullScreenTri.setAttribute(
  13472. 'position',
  13473. new BufferAttribute(
  13474. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13475. 3
  13476. )
  13477. );
  13478. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13479. const scope = this;
  13480. this.enabled = false;
  13481. this.autoUpdate = true;
  13482. this.needsUpdate = false;
  13483. this.type = PCFShadowMap;
  13484. let _previousType = this.type;
  13485. this.render = function ( lights, scene, camera ) {
  13486. if ( scope.enabled === false ) return;
  13487. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13488. if ( lights.length === 0 ) return;
  13489. const currentRenderTarget = _renderer.getRenderTarget();
  13490. const activeCubeFace = _renderer.getActiveCubeFace();
  13491. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13492. const _state = _renderer.state;
  13493. // Set GL state for depth map.
  13494. _state.setBlending( NoBlending );
  13495. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13496. _state.buffers.depth.setTest( true );
  13497. _state.setScissorTest( false );
  13498. // check for shadow map type changes
  13499. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13500. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13501. // render depth map
  13502. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13503. const light = lights[ i ];
  13504. const shadow = light.shadow;
  13505. if ( shadow === undefined ) {
  13506. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13507. continue;
  13508. }
  13509. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13510. _shadowMapSize.copy( shadow.mapSize );
  13511. const shadowFrameExtents = shadow.getFrameExtents();
  13512. _shadowMapSize.multiply( shadowFrameExtents );
  13513. _viewportSize.copy( shadow.mapSize );
  13514. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13515. if ( _shadowMapSize.x > _maxTextureSize ) {
  13516. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13517. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13518. shadow.mapSize.x = _viewportSize.x;
  13519. }
  13520. if ( _shadowMapSize.y > _maxTextureSize ) {
  13521. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13522. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13523. shadow.mapSize.y = _viewportSize.y;
  13524. }
  13525. }
  13526. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13527. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13528. if ( shadow.map !== null ) {
  13529. shadow.map.dispose();
  13530. }
  13531. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13532. shadow.map.texture.name = light.name + '.shadowMap';
  13533. shadow.camera.updateProjectionMatrix();
  13534. }
  13535. _renderer.setRenderTarget( shadow.map );
  13536. _renderer.clear();
  13537. const viewportCount = shadow.getViewportCount();
  13538. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13539. const viewport = shadow.getViewport( vp );
  13540. _viewport.set(
  13541. _viewportSize.x * viewport.x,
  13542. _viewportSize.y * viewport.y,
  13543. _viewportSize.x * viewport.z,
  13544. _viewportSize.y * viewport.w
  13545. );
  13546. _state.viewport( _viewport );
  13547. shadow.updateMatrices( light, vp );
  13548. _frustum = shadow.getFrustum();
  13549. renderObject( scene, camera, shadow.camera, light, this.type );
  13550. }
  13551. // do blur pass for VSM
  13552. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13553. VSMPass( shadow, camera );
  13554. }
  13555. shadow.needsUpdate = false;
  13556. }
  13557. _previousType = this.type;
  13558. scope.needsUpdate = false;
  13559. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13560. };
  13561. function VSMPass( shadow, camera ) {
  13562. const geometry = _objects.update( fullScreenMesh );
  13563. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13564. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13565. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13566. shadowMaterialVertical.needsUpdate = true;
  13567. shadowMaterialHorizontal.needsUpdate = true;
  13568. }
  13569. if ( shadow.mapPass === null ) {
  13570. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13571. }
  13572. // vertical pass
  13573. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13574. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13575. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13576. _renderer.setRenderTarget( shadow.mapPass );
  13577. _renderer.clear();
  13578. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13579. // horizontal pass
  13580. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13581. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13582. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13583. _renderer.setRenderTarget( shadow.map );
  13584. _renderer.clear();
  13585. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13586. }
  13587. function getDepthMaterial( object, material, light, type ) {
  13588. let result = null;
  13589. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13590. if ( customMaterial !== undefined ) {
  13591. result = customMaterial;
  13592. } else {
  13593. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13594. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13595. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13596. ( material.alphaMap && material.alphaTest > 0 ) ||
  13597. ( material.map && material.alphaTest > 0 ) ) {
  13598. // in this case we need a unique material instance reflecting the
  13599. // appropriate state
  13600. const keyA = result.uuid, keyB = material.uuid;
  13601. let materialsForVariant = _materialCache[ keyA ];
  13602. if ( materialsForVariant === undefined ) {
  13603. materialsForVariant = {};
  13604. _materialCache[ keyA ] = materialsForVariant;
  13605. }
  13606. let cachedMaterial = materialsForVariant[ keyB ];
  13607. if ( cachedMaterial === undefined ) {
  13608. cachedMaterial = result.clone();
  13609. materialsForVariant[ keyB ] = cachedMaterial;
  13610. material.addEventListener( 'dispose', onMaterialDispose );
  13611. }
  13612. result = cachedMaterial;
  13613. }
  13614. }
  13615. result.visible = material.visible;
  13616. result.wireframe = material.wireframe;
  13617. if ( type === VSMShadowMap ) {
  13618. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13619. } else {
  13620. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13621. }
  13622. result.alphaMap = material.alphaMap;
  13623. result.alphaTest = material.alphaTest;
  13624. result.map = material.map;
  13625. result.clipShadows = material.clipShadows;
  13626. result.clippingPlanes = material.clippingPlanes;
  13627. result.clipIntersection = material.clipIntersection;
  13628. result.displacementMap = material.displacementMap;
  13629. result.displacementScale = material.displacementScale;
  13630. result.displacementBias = material.displacementBias;
  13631. result.wireframeLinewidth = material.wireframeLinewidth;
  13632. result.linewidth = material.linewidth;
  13633. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13634. const materialProperties = _renderer.properties.get( result );
  13635. materialProperties.light = light;
  13636. }
  13637. return result;
  13638. }
  13639. function renderObject( object, camera, shadowCamera, light, type ) {
  13640. if ( object.visible === false ) return;
  13641. const visible = object.layers.test( camera.layers );
  13642. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13643. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13644. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13645. const geometry = _objects.update( object );
  13646. const material = object.material;
  13647. if ( Array.isArray( material ) ) {
  13648. const groups = geometry.groups;
  13649. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13650. const group = groups[ k ];
  13651. const groupMaterial = material[ group.materialIndex ];
  13652. if ( groupMaterial && groupMaterial.visible ) {
  13653. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13654. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13655. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13656. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13657. }
  13658. }
  13659. } else if ( material.visible ) {
  13660. const depthMaterial = getDepthMaterial( object, material, light, type );
  13661. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13662. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13663. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13664. }
  13665. }
  13666. }
  13667. const children = object.children;
  13668. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13669. renderObject( children[ i ], camera, shadowCamera, light, type );
  13670. }
  13671. }
  13672. function onMaterialDispose( event ) {
  13673. const material = event.target;
  13674. material.removeEventListener( 'dispose', onMaterialDispose );
  13675. // make sure to remove the unique distance/depth materials used for shadow map rendering
  13676. for ( const id in _materialCache ) {
  13677. const cache = _materialCache[ id ];
  13678. const uuid = event.target.uuid;
  13679. if ( uuid in cache ) {
  13680. const shadowMaterial = cache[ uuid ];
  13681. shadowMaterial.dispose();
  13682. delete cache[ uuid ];
  13683. }
  13684. }
  13685. }
  13686. }
  13687. function WebGLState( gl, extensions, capabilities ) {
  13688. const isWebGL2 = capabilities.isWebGL2;
  13689. function ColorBuffer() {
  13690. let locked = false;
  13691. const color = new Vector4();
  13692. let currentColorMask = null;
  13693. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13694. return {
  13695. setMask: function ( colorMask ) {
  13696. if ( currentColorMask !== colorMask && ! locked ) {
  13697. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13698. currentColorMask = colorMask;
  13699. }
  13700. },
  13701. setLocked: function ( lock ) {
  13702. locked = lock;
  13703. },
  13704. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13705. if ( premultipliedAlpha === true ) {
  13706. r *= a; g *= a; b *= a;
  13707. }
  13708. color.set( r, g, b, a );
  13709. if ( currentColorClear.equals( color ) === false ) {
  13710. gl.clearColor( r, g, b, a );
  13711. currentColorClear.copy( color );
  13712. }
  13713. },
  13714. reset: function () {
  13715. locked = false;
  13716. currentColorMask = null;
  13717. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13718. }
  13719. };
  13720. }
  13721. function DepthBuffer() {
  13722. let locked = false;
  13723. let currentDepthMask = null;
  13724. let currentDepthFunc = null;
  13725. let currentDepthClear = null;
  13726. return {
  13727. setTest: function ( depthTest ) {
  13728. if ( depthTest ) {
  13729. enable( gl.DEPTH_TEST );
  13730. } else {
  13731. disable( gl.DEPTH_TEST );
  13732. }
  13733. },
  13734. setMask: function ( depthMask ) {
  13735. if ( currentDepthMask !== depthMask && ! locked ) {
  13736. gl.depthMask( depthMask );
  13737. currentDepthMask = depthMask;
  13738. }
  13739. },
  13740. setFunc: function ( depthFunc ) {
  13741. if ( currentDepthFunc !== depthFunc ) {
  13742. switch ( depthFunc ) {
  13743. case NeverDepth:
  13744. gl.depthFunc( gl.NEVER );
  13745. break;
  13746. case AlwaysDepth:
  13747. gl.depthFunc( gl.ALWAYS );
  13748. break;
  13749. case LessDepth:
  13750. gl.depthFunc( gl.LESS );
  13751. break;
  13752. case LessEqualDepth:
  13753. gl.depthFunc( gl.LEQUAL );
  13754. break;
  13755. case EqualDepth:
  13756. gl.depthFunc( gl.EQUAL );
  13757. break;
  13758. case GreaterEqualDepth:
  13759. gl.depthFunc( gl.GEQUAL );
  13760. break;
  13761. case GreaterDepth:
  13762. gl.depthFunc( gl.GREATER );
  13763. break;
  13764. case NotEqualDepth:
  13765. gl.depthFunc( gl.NOTEQUAL );
  13766. break;
  13767. default:
  13768. gl.depthFunc( gl.LEQUAL );
  13769. }
  13770. currentDepthFunc = depthFunc;
  13771. }
  13772. },
  13773. setLocked: function ( lock ) {
  13774. locked = lock;
  13775. },
  13776. setClear: function ( depth ) {
  13777. if ( currentDepthClear !== depth ) {
  13778. gl.clearDepth( depth );
  13779. currentDepthClear = depth;
  13780. }
  13781. },
  13782. reset: function () {
  13783. locked = false;
  13784. currentDepthMask = null;
  13785. currentDepthFunc = null;
  13786. currentDepthClear = null;
  13787. }
  13788. };
  13789. }
  13790. function StencilBuffer() {
  13791. let locked = false;
  13792. let currentStencilMask = null;
  13793. let currentStencilFunc = null;
  13794. let currentStencilRef = null;
  13795. let currentStencilFuncMask = null;
  13796. let currentStencilFail = null;
  13797. let currentStencilZFail = null;
  13798. let currentStencilZPass = null;
  13799. let currentStencilClear = null;
  13800. return {
  13801. setTest: function ( stencilTest ) {
  13802. if ( ! locked ) {
  13803. if ( stencilTest ) {
  13804. enable( gl.STENCIL_TEST );
  13805. } else {
  13806. disable( gl.STENCIL_TEST );
  13807. }
  13808. }
  13809. },
  13810. setMask: function ( stencilMask ) {
  13811. if ( currentStencilMask !== stencilMask && ! locked ) {
  13812. gl.stencilMask( stencilMask );
  13813. currentStencilMask = stencilMask;
  13814. }
  13815. },
  13816. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13817. if ( currentStencilFunc !== stencilFunc ||
  13818. currentStencilRef !== stencilRef ||
  13819. currentStencilFuncMask !== stencilMask ) {
  13820. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13821. currentStencilFunc = stencilFunc;
  13822. currentStencilRef = stencilRef;
  13823. currentStencilFuncMask = stencilMask;
  13824. }
  13825. },
  13826. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13827. if ( currentStencilFail !== stencilFail ||
  13828. currentStencilZFail !== stencilZFail ||
  13829. currentStencilZPass !== stencilZPass ) {
  13830. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13831. currentStencilFail = stencilFail;
  13832. currentStencilZFail = stencilZFail;
  13833. currentStencilZPass = stencilZPass;
  13834. }
  13835. },
  13836. setLocked: function ( lock ) {
  13837. locked = lock;
  13838. },
  13839. setClear: function ( stencil ) {
  13840. if ( currentStencilClear !== stencil ) {
  13841. gl.clearStencil( stencil );
  13842. currentStencilClear = stencil;
  13843. }
  13844. },
  13845. reset: function () {
  13846. locked = false;
  13847. currentStencilMask = null;
  13848. currentStencilFunc = null;
  13849. currentStencilRef = null;
  13850. currentStencilFuncMask = null;
  13851. currentStencilFail = null;
  13852. currentStencilZFail = null;
  13853. currentStencilZPass = null;
  13854. currentStencilClear = null;
  13855. }
  13856. };
  13857. }
  13858. //
  13859. const colorBuffer = new ColorBuffer();
  13860. const depthBuffer = new DepthBuffer();
  13861. const stencilBuffer = new StencilBuffer();
  13862. const uboBindings = new WeakMap();
  13863. const uboProgramMap = new WeakMap();
  13864. let enabledCapabilities = {};
  13865. let currentBoundFramebuffers = {};
  13866. let currentDrawbuffers = new WeakMap();
  13867. let defaultDrawbuffers = [];
  13868. let currentProgram = null;
  13869. let currentBlendingEnabled = false;
  13870. let currentBlending = null;
  13871. let currentBlendEquation = null;
  13872. let currentBlendSrc = null;
  13873. let currentBlendDst = null;
  13874. let currentBlendEquationAlpha = null;
  13875. let currentBlendSrcAlpha = null;
  13876. let currentBlendDstAlpha = null;
  13877. let currentBlendColor = new Color( 0, 0, 0 );
  13878. let currentBlendAlpha = 0;
  13879. let currentPremultipledAlpha = false;
  13880. let currentFlipSided = null;
  13881. let currentCullFace = null;
  13882. let currentLineWidth = null;
  13883. let currentPolygonOffsetFactor = null;
  13884. let currentPolygonOffsetUnits = null;
  13885. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13886. let lineWidthAvailable = false;
  13887. let version = 0;
  13888. const glVersion = gl.getParameter( gl.VERSION );
  13889. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13890. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13891. lineWidthAvailable = ( version >= 1.0 );
  13892. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13893. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13894. lineWidthAvailable = ( version >= 2.0 );
  13895. }
  13896. let currentTextureSlot = null;
  13897. let currentBoundTextures = {};
  13898. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13899. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13900. const currentScissor = new Vector4().fromArray( scissorParam );
  13901. const currentViewport = new Vector4().fromArray( viewportParam );
  13902. function createTexture( type, target, count, dimensions ) {
  13903. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13904. const texture = gl.createTexture();
  13905. gl.bindTexture( type, texture );
  13906. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13907. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13908. for ( let i = 0; i < count; i ++ ) {
  13909. if ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) {
  13910. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13911. } else {
  13912. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13913. }
  13914. }
  13915. return texture;
  13916. }
  13917. const emptyTextures = {};
  13918. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13919. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13920. if ( isWebGL2 ) {
  13921. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13922. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13923. }
  13924. // init
  13925. colorBuffer.setClear( 0, 0, 0, 1 );
  13926. depthBuffer.setClear( 1 );
  13927. stencilBuffer.setClear( 0 );
  13928. enable( gl.DEPTH_TEST );
  13929. depthBuffer.setFunc( LessEqualDepth );
  13930. setFlipSided( false );
  13931. setCullFace( CullFaceBack );
  13932. enable( gl.CULL_FACE );
  13933. setBlending( NoBlending );
  13934. //
  13935. function enable( id ) {
  13936. if ( enabledCapabilities[ id ] !== true ) {
  13937. gl.enable( id );
  13938. enabledCapabilities[ id ] = true;
  13939. }
  13940. }
  13941. function disable( id ) {
  13942. if ( enabledCapabilities[ id ] !== false ) {
  13943. gl.disable( id );
  13944. enabledCapabilities[ id ] = false;
  13945. }
  13946. }
  13947. function bindFramebuffer( target, framebuffer ) {
  13948. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13949. gl.bindFramebuffer( target, framebuffer );
  13950. currentBoundFramebuffers[ target ] = framebuffer;
  13951. if ( isWebGL2 ) {
  13952. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13953. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13954. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13955. }
  13956. if ( target === gl.FRAMEBUFFER ) {
  13957. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13958. }
  13959. }
  13960. return true;
  13961. }
  13962. return false;
  13963. }
  13964. function drawBuffers( renderTarget, framebuffer ) {
  13965. let drawBuffers = defaultDrawbuffers;
  13966. let needsUpdate = false;
  13967. if ( renderTarget ) {
  13968. drawBuffers = currentDrawbuffers.get( framebuffer );
  13969. if ( drawBuffers === undefined ) {
  13970. drawBuffers = [];
  13971. currentDrawbuffers.set( framebuffer, drawBuffers );
  13972. }
  13973. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13974. const textures = renderTarget.texture;
  13975. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13976. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13977. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13978. }
  13979. drawBuffers.length = textures.length;
  13980. needsUpdate = true;
  13981. }
  13982. } else {
  13983. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13984. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13985. needsUpdate = true;
  13986. }
  13987. }
  13988. } else {
  13989. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13990. drawBuffers[ 0 ] = gl.BACK;
  13991. needsUpdate = true;
  13992. }
  13993. }
  13994. if ( needsUpdate ) {
  13995. if ( capabilities.isWebGL2 ) {
  13996. gl.drawBuffers( drawBuffers );
  13997. } else {
  13998. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13999. }
  14000. }
  14001. }
  14002. function useProgram( program ) {
  14003. if ( currentProgram !== program ) {
  14004. gl.useProgram( program );
  14005. currentProgram = program;
  14006. return true;
  14007. }
  14008. return false;
  14009. }
  14010. const equationToGL = {
  14011. [ AddEquation ]: gl.FUNC_ADD,
  14012. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  14013. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  14014. };
  14015. if ( isWebGL2 ) {
  14016. equationToGL[ MinEquation ] = gl.MIN;
  14017. equationToGL[ MaxEquation ] = gl.MAX;
  14018. } else {
  14019. const extension = extensions.get( 'EXT_blend_minmax' );
  14020. if ( extension !== null ) {
  14021. equationToGL[ MinEquation ] = extension.MIN_EXT;
  14022. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  14023. }
  14024. }
  14025. const factorToGL = {
  14026. [ ZeroFactor ]: gl.ZERO,
  14027. [ OneFactor ]: gl.ONE,
  14028. [ SrcColorFactor ]: gl.SRC_COLOR,
  14029. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  14030. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  14031. [ DstColorFactor ]: gl.DST_COLOR,
  14032. [ DstAlphaFactor ]: gl.DST_ALPHA,
  14033. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  14034. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  14035. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  14036. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  14037. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  14038. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  14039. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  14040. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  14041. };
  14042. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  14043. if ( blending === NoBlending ) {
  14044. if ( currentBlendingEnabled === true ) {
  14045. disable( gl.BLEND );
  14046. currentBlendingEnabled = false;
  14047. }
  14048. return;
  14049. }
  14050. if ( currentBlendingEnabled === false ) {
  14051. enable( gl.BLEND );
  14052. currentBlendingEnabled = true;
  14053. }
  14054. if ( blending !== CustomBlending ) {
  14055. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  14056. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  14057. gl.blendEquation( gl.FUNC_ADD );
  14058. currentBlendEquation = AddEquation;
  14059. currentBlendEquationAlpha = AddEquation;
  14060. }
  14061. if ( premultipliedAlpha ) {
  14062. switch ( blending ) {
  14063. case NormalBlending:
  14064. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14065. break;
  14066. case AdditiveBlending:
  14067. gl.blendFunc( gl.ONE, gl.ONE );
  14068. break;
  14069. case SubtractiveBlending:
  14070. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  14071. break;
  14072. case MultiplyBlending:
  14073. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  14074. break;
  14075. default:
  14076. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14077. break;
  14078. }
  14079. } else {
  14080. switch ( blending ) {
  14081. case NormalBlending:
  14082. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14083. break;
  14084. case AdditiveBlending:
  14085. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14086. break;
  14087. case SubtractiveBlending:
  14088. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  14089. break;
  14090. case MultiplyBlending:
  14091. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14092. break;
  14093. default:
  14094. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14095. break;
  14096. }
  14097. }
  14098. currentBlendSrc = null;
  14099. currentBlendDst = null;
  14100. currentBlendSrcAlpha = null;
  14101. currentBlendDstAlpha = null;
  14102. currentBlendColor.set( 0, 0, 0 );
  14103. currentBlendAlpha = 0;
  14104. currentBlending = blending;
  14105. currentPremultipledAlpha = premultipliedAlpha;
  14106. }
  14107. return;
  14108. }
  14109. // custom blending
  14110. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14111. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14112. blendDstAlpha = blendDstAlpha || blendDst;
  14113. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14114. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  14115. currentBlendEquation = blendEquation;
  14116. currentBlendEquationAlpha = blendEquationAlpha;
  14117. }
  14118. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14119. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  14120. currentBlendSrc = blendSrc;
  14121. currentBlendDst = blendDst;
  14122. currentBlendSrcAlpha = blendSrcAlpha;
  14123. currentBlendDstAlpha = blendDstAlpha;
  14124. }
  14125. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  14126. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  14127. currentBlendColor.copy( blendColor );
  14128. currentBlendAlpha = blendAlpha;
  14129. }
  14130. currentBlending = blending;
  14131. currentPremultipledAlpha = false;
  14132. }
  14133. function setMaterial( material, frontFaceCW ) {
  14134. material.side === DoubleSide
  14135. ? disable( gl.CULL_FACE )
  14136. : enable( gl.CULL_FACE );
  14137. let flipSided = ( material.side === BackSide );
  14138. if ( frontFaceCW ) flipSided = ! flipSided;
  14139. setFlipSided( flipSided );
  14140. ( material.blending === NormalBlending && material.transparent === false )
  14141. ? setBlending( NoBlending )
  14142. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  14143. depthBuffer.setFunc( material.depthFunc );
  14144. depthBuffer.setTest( material.depthTest );
  14145. depthBuffer.setMask( material.depthWrite );
  14146. colorBuffer.setMask( material.colorWrite );
  14147. const stencilWrite = material.stencilWrite;
  14148. stencilBuffer.setTest( stencilWrite );
  14149. if ( stencilWrite ) {
  14150. stencilBuffer.setMask( material.stencilWriteMask );
  14151. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  14152. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  14153. }
  14154. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14155. material.alphaToCoverage === true
  14156. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  14157. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14158. }
  14159. //
  14160. function setFlipSided( flipSided ) {
  14161. if ( currentFlipSided !== flipSided ) {
  14162. if ( flipSided ) {
  14163. gl.frontFace( gl.CW );
  14164. } else {
  14165. gl.frontFace( gl.CCW );
  14166. }
  14167. currentFlipSided = flipSided;
  14168. }
  14169. }
  14170. function setCullFace( cullFace ) {
  14171. if ( cullFace !== CullFaceNone ) {
  14172. enable( gl.CULL_FACE );
  14173. if ( cullFace !== currentCullFace ) {
  14174. if ( cullFace === CullFaceBack ) {
  14175. gl.cullFace( gl.BACK );
  14176. } else if ( cullFace === CullFaceFront ) {
  14177. gl.cullFace( gl.FRONT );
  14178. } else {
  14179. gl.cullFace( gl.FRONT_AND_BACK );
  14180. }
  14181. }
  14182. } else {
  14183. disable( gl.CULL_FACE );
  14184. }
  14185. currentCullFace = cullFace;
  14186. }
  14187. function setLineWidth( width ) {
  14188. if ( width !== currentLineWidth ) {
  14189. if ( lineWidthAvailable ) gl.lineWidth( width );
  14190. currentLineWidth = width;
  14191. }
  14192. }
  14193. function setPolygonOffset( polygonOffset, factor, units ) {
  14194. if ( polygonOffset ) {
  14195. enable( gl.POLYGON_OFFSET_FILL );
  14196. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14197. gl.polygonOffset( factor, units );
  14198. currentPolygonOffsetFactor = factor;
  14199. currentPolygonOffsetUnits = units;
  14200. }
  14201. } else {
  14202. disable( gl.POLYGON_OFFSET_FILL );
  14203. }
  14204. }
  14205. function setScissorTest( scissorTest ) {
  14206. if ( scissorTest ) {
  14207. enable( gl.SCISSOR_TEST );
  14208. } else {
  14209. disable( gl.SCISSOR_TEST );
  14210. }
  14211. }
  14212. // texture
  14213. function activeTexture( webglSlot ) {
  14214. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14215. if ( currentTextureSlot !== webglSlot ) {
  14216. gl.activeTexture( webglSlot );
  14217. currentTextureSlot = webglSlot;
  14218. }
  14219. }
  14220. function bindTexture( webglType, webglTexture, webglSlot ) {
  14221. if ( webglSlot === undefined ) {
  14222. if ( currentTextureSlot === null ) {
  14223. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14224. } else {
  14225. webglSlot = currentTextureSlot;
  14226. }
  14227. }
  14228. let boundTexture = currentBoundTextures[ webglSlot ];
  14229. if ( boundTexture === undefined ) {
  14230. boundTexture = { type: undefined, texture: undefined };
  14231. currentBoundTextures[ webglSlot ] = boundTexture;
  14232. }
  14233. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14234. if ( currentTextureSlot !== webglSlot ) {
  14235. gl.activeTexture( webglSlot );
  14236. currentTextureSlot = webglSlot;
  14237. }
  14238. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14239. boundTexture.type = webglType;
  14240. boundTexture.texture = webglTexture;
  14241. }
  14242. }
  14243. function unbindTexture() {
  14244. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14245. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14246. gl.bindTexture( boundTexture.type, null );
  14247. boundTexture.type = undefined;
  14248. boundTexture.texture = undefined;
  14249. }
  14250. }
  14251. function compressedTexImage2D() {
  14252. try {
  14253. gl.compressedTexImage2D.apply( gl, arguments );
  14254. } catch ( error ) {
  14255. console.error( 'THREE.WebGLState:', error );
  14256. }
  14257. }
  14258. function compressedTexImage3D() {
  14259. try {
  14260. gl.compressedTexImage3D.apply( gl, arguments );
  14261. } catch ( error ) {
  14262. console.error( 'THREE.WebGLState:', error );
  14263. }
  14264. }
  14265. function texSubImage2D() {
  14266. try {
  14267. gl.texSubImage2D.apply( gl, arguments );
  14268. } catch ( error ) {
  14269. console.error( 'THREE.WebGLState:', error );
  14270. }
  14271. }
  14272. function texSubImage3D() {
  14273. try {
  14274. gl.texSubImage3D.apply( gl, arguments );
  14275. } catch ( error ) {
  14276. console.error( 'THREE.WebGLState:', error );
  14277. }
  14278. }
  14279. function compressedTexSubImage2D() {
  14280. try {
  14281. gl.compressedTexSubImage2D.apply( gl, arguments );
  14282. } catch ( error ) {
  14283. console.error( 'THREE.WebGLState:', error );
  14284. }
  14285. }
  14286. function compressedTexSubImage3D() {
  14287. try {
  14288. gl.compressedTexSubImage3D.apply( gl, arguments );
  14289. } catch ( error ) {
  14290. console.error( 'THREE.WebGLState:', error );
  14291. }
  14292. }
  14293. function texStorage2D() {
  14294. try {
  14295. gl.texStorage2D.apply( gl, arguments );
  14296. } catch ( error ) {
  14297. console.error( 'THREE.WebGLState:', error );
  14298. }
  14299. }
  14300. function texStorage3D() {
  14301. try {
  14302. gl.texStorage3D.apply( gl, arguments );
  14303. } catch ( error ) {
  14304. console.error( 'THREE.WebGLState:', error );
  14305. }
  14306. }
  14307. function texImage2D() {
  14308. try {
  14309. gl.texImage2D.apply( gl, arguments );
  14310. } catch ( error ) {
  14311. console.error( 'THREE.WebGLState:', error );
  14312. }
  14313. }
  14314. function texImage3D() {
  14315. try {
  14316. gl.texImage3D.apply( gl, arguments );
  14317. } catch ( error ) {
  14318. console.error( 'THREE.WebGLState:', error );
  14319. }
  14320. }
  14321. //
  14322. function scissor( scissor ) {
  14323. if ( currentScissor.equals( scissor ) === false ) {
  14324. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14325. currentScissor.copy( scissor );
  14326. }
  14327. }
  14328. function viewport( viewport ) {
  14329. if ( currentViewport.equals( viewport ) === false ) {
  14330. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14331. currentViewport.copy( viewport );
  14332. }
  14333. }
  14334. function updateUBOMapping( uniformsGroup, program ) {
  14335. let mapping = uboProgramMap.get( program );
  14336. if ( mapping === undefined ) {
  14337. mapping = new WeakMap();
  14338. uboProgramMap.set( program, mapping );
  14339. }
  14340. let blockIndex = mapping.get( uniformsGroup );
  14341. if ( blockIndex === undefined ) {
  14342. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14343. mapping.set( uniformsGroup, blockIndex );
  14344. }
  14345. }
  14346. function uniformBlockBinding( uniformsGroup, program ) {
  14347. const mapping = uboProgramMap.get( program );
  14348. const blockIndex = mapping.get( uniformsGroup );
  14349. if ( uboBindings.get( program ) !== blockIndex ) {
  14350. // bind shader specific block index to global block point
  14351. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14352. uboBindings.set( program, blockIndex );
  14353. }
  14354. }
  14355. //
  14356. function reset() {
  14357. // reset state
  14358. gl.disable( gl.BLEND );
  14359. gl.disable( gl.CULL_FACE );
  14360. gl.disable( gl.DEPTH_TEST );
  14361. gl.disable( gl.POLYGON_OFFSET_FILL );
  14362. gl.disable( gl.SCISSOR_TEST );
  14363. gl.disable( gl.STENCIL_TEST );
  14364. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14365. gl.blendEquation( gl.FUNC_ADD );
  14366. gl.blendFunc( gl.ONE, gl.ZERO );
  14367. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14368. gl.blendColor( 0, 0, 0, 0 );
  14369. gl.colorMask( true, true, true, true );
  14370. gl.clearColor( 0, 0, 0, 0 );
  14371. gl.depthMask( true );
  14372. gl.depthFunc( gl.LESS );
  14373. gl.clearDepth( 1 );
  14374. gl.stencilMask( 0xffffffff );
  14375. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14376. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14377. gl.clearStencil( 0 );
  14378. gl.cullFace( gl.BACK );
  14379. gl.frontFace( gl.CCW );
  14380. gl.polygonOffset( 0, 0 );
  14381. gl.activeTexture( gl.TEXTURE0 );
  14382. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14383. if ( isWebGL2 === true ) {
  14384. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14385. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14386. }
  14387. gl.useProgram( null );
  14388. gl.lineWidth( 1 );
  14389. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14390. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14391. // reset internals
  14392. enabledCapabilities = {};
  14393. currentTextureSlot = null;
  14394. currentBoundTextures = {};
  14395. currentBoundFramebuffers = {};
  14396. currentDrawbuffers = new WeakMap();
  14397. defaultDrawbuffers = [];
  14398. currentProgram = null;
  14399. currentBlendingEnabled = false;
  14400. currentBlending = null;
  14401. currentBlendEquation = null;
  14402. currentBlendSrc = null;
  14403. currentBlendDst = null;
  14404. currentBlendEquationAlpha = null;
  14405. currentBlendSrcAlpha = null;
  14406. currentBlendDstAlpha = null;
  14407. currentBlendColor = new Color( 0, 0, 0 );
  14408. currentBlendAlpha = 0;
  14409. currentPremultipledAlpha = false;
  14410. currentFlipSided = null;
  14411. currentCullFace = null;
  14412. currentLineWidth = null;
  14413. currentPolygonOffsetFactor = null;
  14414. currentPolygonOffsetUnits = null;
  14415. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14416. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14417. colorBuffer.reset();
  14418. depthBuffer.reset();
  14419. stencilBuffer.reset();
  14420. }
  14421. return {
  14422. buffers: {
  14423. color: colorBuffer,
  14424. depth: depthBuffer,
  14425. stencil: stencilBuffer
  14426. },
  14427. enable: enable,
  14428. disable: disable,
  14429. bindFramebuffer: bindFramebuffer,
  14430. drawBuffers: drawBuffers,
  14431. useProgram: useProgram,
  14432. setBlending: setBlending,
  14433. setMaterial: setMaterial,
  14434. setFlipSided: setFlipSided,
  14435. setCullFace: setCullFace,
  14436. setLineWidth: setLineWidth,
  14437. setPolygonOffset: setPolygonOffset,
  14438. setScissorTest: setScissorTest,
  14439. activeTexture: activeTexture,
  14440. bindTexture: bindTexture,
  14441. unbindTexture: unbindTexture,
  14442. compressedTexImage2D: compressedTexImage2D,
  14443. compressedTexImage3D: compressedTexImage3D,
  14444. texImage2D: texImage2D,
  14445. texImage3D: texImage3D,
  14446. updateUBOMapping: updateUBOMapping,
  14447. uniformBlockBinding: uniformBlockBinding,
  14448. texStorage2D: texStorage2D,
  14449. texStorage3D: texStorage3D,
  14450. texSubImage2D: texSubImage2D,
  14451. texSubImage3D: texSubImage3D,
  14452. compressedTexSubImage2D: compressedTexSubImage2D,
  14453. compressedTexSubImage3D: compressedTexSubImage3D,
  14454. scissor: scissor,
  14455. viewport: viewport,
  14456. reset: reset
  14457. };
  14458. }
  14459. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14460. const isWebGL2 = capabilities.isWebGL2;
  14461. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14462. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14463. const _videoTextures = new WeakMap();
  14464. let _canvas;
  14465. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14466. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14467. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14468. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14469. let useOffscreenCanvas = false;
  14470. try {
  14471. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14472. // eslint-disable-next-line compat/compat
  14473. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14474. } catch ( err ) {
  14475. // Ignore any errors
  14476. }
  14477. function createCanvas( width, height ) {
  14478. // Use OffscreenCanvas when available. Specially needed in web workers
  14479. return useOffscreenCanvas ?
  14480. // eslint-disable-next-line compat/compat
  14481. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14482. }
  14483. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14484. let scale = 1;
  14485. // handle case if texture exceeds max size
  14486. if ( image.width > maxSize || image.height > maxSize ) {
  14487. scale = maxSize / Math.max( image.width, image.height );
  14488. }
  14489. // only perform resize if necessary
  14490. if ( scale < 1 || needsPowerOfTwo === true ) {
  14491. // only perform resize for certain image types
  14492. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14493. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14494. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14495. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14496. const width = floor( scale * image.width );
  14497. const height = floor( scale * image.height );
  14498. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14499. // cube textures can't reuse the same canvas
  14500. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14501. canvas.width = width;
  14502. canvas.height = height;
  14503. const context = canvas.getContext( '2d' );
  14504. context.drawImage( image, 0, 0, width, height );
  14505. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14506. return canvas;
  14507. } else {
  14508. if ( 'data' in image ) {
  14509. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14510. }
  14511. return image;
  14512. }
  14513. }
  14514. return image;
  14515. }
  14516. function isPowerOfTwo$1( image ) {
  14517. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14518. }
  14519. function textureNeedsPowerOfTwo( texture ) {
  14520. if ( isWebGL2 ) return false;
  14521. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14522. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14523. }
  14524. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14525. return texture.generateMipmaps && supportsMips &&
  14526. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14527. }
  14528. function generateMipmap( target ) {
  14529. _gl.generateMipmap( target );
  14530. }
  14531. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14532. if ( isWebGL2 === false ) return glFormat;
  14533. if ( internalFormatName !== null ) {
  14534. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14535. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14536. }
  14537. let internalFormat = glFormat;
  14538. if ( glFormat === _gl.RED ) {
  14539. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14540. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14541. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14542. }
  14543. if ( glFormat === _gl.RED_INTEGER ) {
  14544. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14545. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14546. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14547. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14548. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14549. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14550. }
  14551. if ( glFormat === _gl.RG ) {
  14552. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14553. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14554. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14555. }
  14556. if ( glFormat === _gl.RGBA ) {
  14557. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14558. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14559. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14560. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14561. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14562. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14563. }
  14564. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14565. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14566. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14567. extensions.get( 'EXT_color_buffer_float' );
  14568. }
  14569. return internalFormat;
  14570. }
  14571. function getMipLevels( texture, image, supportsMips ) {
  14572. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14573. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14574. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14575. // user-defined mipmaps
  14576. return texture.mipmaps.length;
  14577. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14578. return image.mipmaps.length;
  14579. } else {
  14580. // texture without mipmaps (only base level)
  14581. return 1;
  14582. }
  14583. }
  14584. // Fallback filters for non-power-of-2 textures
  14585. function filterFallback( f ) {
  14586. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14587. return _gl.NEAREST;
  14588. }
  14589. return _gl.LINEAR;
  14590. }
  14591. //
  14592. function onTextureDispose( event ) {
  14593. const texture = event.target;
  14594. texture.removeEventListener( 'dispose', onTextureDispose );
  14595. deallocateTexture( texture );
  14596. if ( texture.isVideoTexture ) {
  14597. _videoTextures.delete( texture );
  14598. }
  14599. }
  14600. function onRenderTargetDispose( event ) {
  14601. const renderTarget = event.target;
  14602. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14603. deallocateRenderTarget( renderTarget );
  14604. }
  14605. //
  14606. function deallocateTexture( texture ) {
  14607. const textureProperties = properties.get( texture );
  14608. if ( textureProperties.__webglInit === undefined ) return;
  14609. // check if it's necessary to remove the WebGLTexture object
  14610. const source = texture.source;
  14611. const webglTextures = _sources.get( source );
  14612. if ( webglTextures ) {
  14613. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14614. webglTexture.usedTimes --;
  14615. // the WebGLTexture object is not used anymore, remove it
  14616. if ( webglTexture.usedTimes === 0 ) {
  14617. deleteTexture( texture );
  14618. }
  14619. // remove the weak map entry if no WebGLTexture uses the source anymore
  14620. if ( Object.keys( webglTextures ).length === 0 ) {
  14621. _sources.delete( source );
  14622. }
  14623. }
  14624. properties.remove( texture );
  14625. }
  14626. function deleteTexture( texture ) {
  14627. const textureProperties = properties.get( texture );
  14628. _gl.deleteTexture( textureProperties.__webglTexture );
  14629. const source = texture.source;
  14630. const webglTextures = _sources.get( source );
  14631. delete webglTextures[ textureProperties.__cacheKey ];
  14632. info.memory.textures --;
  14633. }
  14634. function deallocateRenderTarget( renderTarget ) {
  14635. const texture = renderTarget.texture;
  14636. const renderTargetProperties = properties.get( renderTarget );
  14637. const textureProperties = properties.get( texture );
  14638. if ( textureProperties.__webglTexture !== undefined ) {
  14639. _gl.deleteTexture( textureProperties.__webglTexture );
  14640. info.memory.textures --;
  14641. }
  14642. if ( renderTarget.depthTexture ) {
  14643. renderTarget.depthTexture.dispose();
  14644. }
  14645. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14646. for ( let i = 0; i < 6; i ++ ) {
  14647. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14648. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14649. } else {
  14650. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14651. }
  14652. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14653. }
  14654. } else {
  14655. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14656. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14657. } else {
  14658. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14659. }
  14660. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14661. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14662. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14663. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14664. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14665. }
  14666. }
  14667. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14668. }
  14669. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14670. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14671. const attachmentProperties = properties.get( texture[ i ] );
  14672. if ( attachmentProperties.__webglTexture ) {
  14673. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14674. info.memory.textures --;
  14675. }
  14676. properties.remove( texture[ i ] );
  14677. }
  14678. }
  14679. properties.remove( texture );
  14680. properties.remove( renderTarget );
  14681. }
  14682. //
  14683. let textureUnits = 0;
  14684. function resetTextureUnits() {
  14685. textureUnits = 0;
  14686. }
  14687. function allocateTextureUnit() {
  14688. const textureUnit = textureUnits;
  14689. if ( textureUnit >= capabilities.maxTextures ) {
  14690. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  14691. }
  14692. textureUnits += 1;
  14693. return textureUnit;
  14694. }
  14695. function getTextureCacheKey( texture ) {
  14696. const array = [];
  14697. array.push( texture.wrapS );
  14698. array.push( texture.wrapT );
  14699. array.push( texture.wrapR || 0 );
  14700. array.push( texture.magFilter );
  14701. array.push( texture.minFilter );
  14702. array.push( texture.anisotropy );
  14703. array.push( texture.internalFormat );
  14704. array.push( texture.format );
  14705. array.push( texture.type );
  14706. array.push( texture.generateMipmaps );
  14707. array.push( texture.premultiplyAlpha );
  14708. array.push( texture.flipY );
  14709. array.push( texture.unpackAlignment );
  14710. array.push( texture.colorSpace );
  14711. return array.join();
  14712. }
  14713. //
  14714. function setTexture2D( texture, slot ) {
  14715. const textureProperties = properties.get( texture );
  14716. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14717. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14718. const image = texture.image;
  14719. if ( image === null ) {
  14720. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14721. } else if ( image.complete === false ) {
  14722. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14723. } else {
  14724. uploadTexture( textureProperties, texture, slot );
  14725. return;
  14726. }
  14727. }
  14728. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14729. }
  14730. function setTexture2DArray( texture, slot ) {
  14731. const textureProperties = properties.get( texture );
  14732. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14733. uploadTexture( textureProperties, texture, slot );
  14734. return;
  14735. }
  14736. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14737. }
  14738. function setTexture3D( texture, slot ) {
  14739. const textureProperties = properties.get( texture );
  14740. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14741. uploadTexture( textureProperties, texture, slot );
  14742. return;
  14743. }
  14744. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14745. }
  14746. function setTextureCube( texture, slot ) {
  14747. const textureProperties = properties.get( texture );
  14748. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14749. uploadCubeTexture( textureProperties, texture, slot );
  14750. return;
  14751. }
  14752. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14753. }
  14754. const wrappingToGL = {
  14755. [ RepeatWrapping ]: _gl.REPEAT,
  14756. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14757. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14758. };
  14759. const filterToGL = {
  14760. [ NearestFilter ]: _gl.NEAREST,
  14761. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14762. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14763. [ LinearFilter ]: _gl.LINEAR,
  14764. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14765. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14766. };
  14767. const compareToGL = {
  14768. [ NeverCompare ]: _gl.NEVER,
  14769. [ AlwaysCompare ]: _gl.ALWAYS,
  14770. [ LessCompare ]: _gl.LESS,
  14771. [ LessEqualCompare ]: _gl.LEQUAL,
  14772. [ EqualCompare ]: _gl.EQUAL,
  14773. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14774. [ GreaterCompare ]: _gl.GREATER,
  14775. [ NotEqualCompare ]: _gl.NOTEQUAL
  14776. };
  14777. function setTextureParameters( textureType, texture, supportsMips ) {
  14778. if ( supportsMips ) {
  14779. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14780. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14781. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14782. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14783. }
  14784. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14785. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14786. } else {
  14787. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14788. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14789. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14790. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  14791. }
  14792. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14793. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14794. }
  14795. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14796. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14797. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14798. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14799. }
  14800. }
  14801. if ( texture.compareFunction ) {
  14802. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14803. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14804. }
  14805. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14806. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14807. if ( texture.magFilter === NearestFilter ) return;
  14808. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14809. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14810. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14811. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14812. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14813. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14814. }
  14815. }
  14816. }
  14817. function initTexture( textureProperties, texture ) {
  14818. let forceUpload = false;
  14819. if ( textureProperties.__webglInit === undefined ) {
  14820. textureProperties.__webglInit = true;
  14821. texture.addEventListener( 'dispose', onTextureDispose );
  14822. }
  14823. // create Source <-> WebGLTextures mapping if necessary
  14824. const source = texture.source;
  14825. let webglTextures = _sources.get( source );
  14826. if ( webglTextures === undefined ) {
  14827. webglTextures = {};
  14828. _sources.set( source, webglTextures );
  14829. }
  14830. // check if there is already a WebGLTexture object for the given texture parameters
  14831. const textureCacheKey = getTextureCacheKey( texture );
  14832. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14833. // if not, create a new instance of WebGLTexture
  14834. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14835. // create new entry
  14836. webglTextures[ textureCacheKey ] = {
  14837. texture: _gl.createTexture(),
  14838. usedTimes: 0
  14839. };
  14840. info.memory.textures ++;
  14841. // when a new instance of WebGLTexture was created, a texture upload is required
  14842. // even if the image contents are identical
  14843. forceUpload = true;
  14844. }
  14845. webglTextures[ textureCacheKey ].usedTimes ++;
  14846. // every time the texture cache key changes, it's necessary to check if an instance of
  14847. // WebGLTexture can be deleted in order to avoid a memory leak.
  14848. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14849. if ( webglTexture !== undefined ) {
  14850. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14851. if ( webglTexture.usedTimes === 0 ) {
  14852. deleteTexture( texture );
  14853. }
  14854. }
  14855. // store references to cache key and WebGLTexture object
  14856. textureProperties.__cacheKey = textureCacheKey;
  14857. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14858. }
  14859. return forceUpload;
  14860. }
  14861. function uploadTexture( textureProperties, texture, slot ) {
  14862. let textureType = _gl.TEXTURE_2D;
  14863. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14864. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14865. const forceUpload = initTexture( textureProperties, texture );
  14866. const source = texture.source;
  14867. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14868. const sourceProperties = properties.get( source );
  14869. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14870. state.activeTexture( _gl.TEXTURE0 + slot );
  14871. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14872. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14873. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14874. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14875. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14876. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14877. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14878. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14879. let image = resizeImage( texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize );
  14880. image = verifyColorSpace( texture, image );
  14881. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14882. glFormat = utils.convert( texture.format, texture.colorSpace );
  14883. let glType = utils.convert( texture.type ),
  14884. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14885. setTextureParameters( textureType, texture, supportsMips );
  14886. let mipmap;
  14887. const mipmaps = texture.mipmaps;
  14888. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true && glInternalFormat !== RGB_ETC1_Format );
  14889. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14890. const levels = getMipLevels( texture, image, supportsMips );
  14891. if ( texture.isDepthTexture ) {
  14892. // populate depth texture with dummy data
  14893. glInternalFormat = _gl.DEPTH_COMPONENT;
  14894. if ( isWebGL2 ) {
  14895. if ( texture.type === FloatType ) {
  14896. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14897. } else if ( texture.type === UnsignedIntType ) {
  14898. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14899. } else if ( texture.type === UnsignedInt248Type ) {
  14900. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14901. } else {
  14902. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14903. }
  14904. } else {
  14905. if ( texture.type === FloatType ) {
  14906. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14907. }
  14908. }
  14909. // validation checks for WebGL 1
  14910. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14911. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14912. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14913. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14914. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14915. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14916. texture.type = UnsignedIntType;
  14917. glType = utils.convert( texture.type );
  14918. }
  14919. }
  14920. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14921. // Depth stencil textures need the DEPTH_STENCIL internal format
  14922. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14923. glInternalFormat = _gl.DEPTH_STENCIL;
  14924. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14925. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14926. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14927. if ( texture.type !== UnsignedInt248Type ) {
  14928. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14929. texture.type = UnsignedInt248Type;
  14930. glType = utils.convert( texture.type );
  14931. }
  14932. }
  14933. //
  14934. if ( allocateMemory ) {
  14935. if ( useTexStorage ) {
  14936. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14937. } else {
  14938. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14939. }
  14940. }
  14941. } else if ( texture.isDataTexture ) {
  14942. // use manually created mipmaps if available
  14943. // if there are no manual mipmaps
  14944. // set 0 level mipmap and then use GL to generate other mipmap levels
  14945. if ( mipmaps.length > 0 && supportsMips ) {
  14946. if ( useTexStorage && allocateMemory ) {
  14947. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14948. }
  14949. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14950. mipmap = mipmaps[ i ];
  14951. if ( useTexStorage ) {
  14952. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14953. } else {
  14954. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14955. }
  14956. }
  14957. texture.generateMipmaps = false;
  14958. } else {
  14959. if ( useTexStorage ) {
  14960. if ( allocateMemory ) {
  14961. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14962. }
  14963. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14964. } else {
  14965. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14966. }
  14967. }
  14968. } else if ( texture.isCompressedTexture ) {
  14969. if ( texture.isCompressedArrayTexture ) {
  14970. if ( useTexStorage && allocateMemory ) {
  14971. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14972. }
  14973. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14974. mipmap = mipmaps[ i ];
  14975. if ( texture.format !== RGBAFormat ) {
  14976. if ( glFormat !== null ) {
  14977. if ( useTexStorage ) {
  14978. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14979. } else {
  14980. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14981. }
  14982. } else {
  14983. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14984. }
  14985. } else {
  14986. if ( useTexStorage ) {
  14987. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14988. } else {
  14989. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14990. }
  14991. }
  14992. }
  14993. } else {
  14994. if ( useTexStorage && allocateMemory ) {
  14995. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14996. }
  14997. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14998. mipmap = mipmaps[ i ];
  14999. if ( texture.format !== RGBAFormat ) {
  15000. if ( glFormat !== null ) {
  15001. if ( useTexStorage ) {
  15002. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15003. } else {
  15004. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15005. }
  15006. } else {
  15007. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15008. }
  15009. } else {
  15010. if ( useTexStorage ) {
  15011. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15012. } else {
  15013. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15014. }
  15015. }
  15016. }
  15017. }
  15018. } else if ( texture.isDataArrayTexture ) {
  15019. if ( useTexStorage ) {
  15020. if ( allocateMemory ) {
  15021. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  15022. }
  15023. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15024. } else {
  15025. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15026. }
  15027. } else if ( texture.isData3DTexture ) {
  15028. if ( useTexStorage ) {
  15029. if ( allocateMemory ) {
  15030. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  15031. }
  15032. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15033. } else {
  15034. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15035. }
  15036. } else if ( texture.isFramebufferTexture ) {
  15037. if ( allocateMemory ) {
  15038. if ( useTexStorage ) {
  15039. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15040. } else {
  15041. let width = image.width, height = image.height;
  15042. for ( let i = 0; i < levels; i ++ ) {
  15043. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  15044. width >>= 1;
  15045. height >>= 1;
  15046. }
  15047. }
  15048. }
  15049. } else {
  15050. // regular Texture (image, video, canvas)
  15051. // use manually created mipmaps if available
  15052. // if there are no manual mipmaps
  15053. // set 0 level mipmap and then use GL to generate other mipmap levels
  15054. if ( mipmaps.length > 0 && supportsMips ) {
  15055. if ( useTexStorage && allocateMemory ) {
  15056. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  15057. }
  15058. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15059. mipmap = mipmaps[ i ];
  15060. if ( useTexStorage ) {
  15061. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  15062. } else {
  15063. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  15064. }
  15065. }
  15066. texture.generateMipmaps = false;
  15067. } else {
  15068. if ( useTexStorage ) {
  15069. if ( allocateMemory ) {
  15070. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15071. }
  15072. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  15073. } else {
  15074. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  15075. }
  15076. }
  15077. }
  15078. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15079. generateMipmap( textureType );
  15080. }
  15081. sourceProperties.__version = source.version;
  15082. if ( texture.onUpdate ) texture.onUpdate( texture );
  15083. }
  15084. textureProperties.__version = texture.version;
  15085. }
  15086. function uploadCubeTexture( textureProperties, texture, slot ) {
  15087. if ( texture.image.length !== 6 ) return;
  15088. const forceUpload = initTexture( textureProperties, texture );
  15089. const source = texture.source;
  15090. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  15091. const sourceProperties = properties.get( source );
  15092. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  15093. state.activeTexture( _gl.TEXTURE0 + slot );
  15094. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  15095. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  15096. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  15097. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15098. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15099. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15100. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  15101. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  15102. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15103. const cubeImage = [];
  15104. for ( let i = 0; i < 6; i ++ ) {
  15105. if ( ! isCompressed && ! isDataTexture ) {
  15106. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, capabilities.maxCubemapSize );
  15107. } else {
  15108. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15109. }
  15110. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  15111. }
  15112. const image = cubeImage[ 0 ],
  15113. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  15114. glFormat = utils.convert( texture.format, texture.colorSpace ),
  15115. glType = utils.convert( texture.type ),
  15116. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15117. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  15118. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  15119. let levels = getMipLevels( texture, image, supportsMips );
  15120. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  15121. let mipmaps;
  15122. if ( isCompressed ) {
  15123. if ( useTexStorage && allocateMemory ) {
  15124. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  15125. }
  15126. for ( let i = 0; i < 6; i ++ ) {
  15127. mipmaps = cubeImage[ i ].mipmaps;
  15128. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15129. const mipmap = mipmaps[ j ];
  15130. if ( texture.format !== RGBAFormat ) {
  15131. if ( glFormat !== null ) {
  15132. if ( useTexStorage ) {
  15133. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15134. } else {
  15135. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15136. }
  15137. } else {
  15138. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15139. }
  15140. } else {
  15141. if ( useTexStorage ) {
  15142. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15143. } else {
  15144. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15145. }
  15146. }
  15147. }
  15148. }
  15149. } else {
  15150. mipmaps = texture.mipmaps;
  15151. if ( useTexStorage && allocateMemory ) {
  15152. // TODO: Uniformly handle mipmap definitions
  15153. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  15154. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  15155. if ( mipmaps.length > 0 ) levels ++;
  15156. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  15157. }
  15158. for ( let i = 0; i < 6; i ++ ) {
  15159. if ( isDataTexture ) {
  15160. if ( useTexStorage ) {
  15161. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  15162. } else {
  15163. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15164. }
  15165. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15166. const mipmap = mipmaps[ j ];
  15167. const mipmapImage = mipmap.image[ i ].image;
  15168. if ( useTexStorage ) {
  15169. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  15170. } else {
  15171. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  15172. }
  15173. }
  15174. } else {
  15175. if ( useTexStorage ) {
  15176. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  15177. } else {
  15178. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  15179. }
  15180. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15181. const mipmap = mipmaps[ j ];
  15182. if ( useTexStorage ) {
  15183. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  15184. } else {
  15185. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  15186. }
  15187. }
  15188. }
  15189. }
  15190. }
  15191. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15192. // We assume images for cube map have the same size.
  15193. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15194. }
  15195. sourceProperties.__version = source.version;
  15196. if ( texture.onUpdate ) texture.onUpdate( texture );
  15197. }
  15198. textureProperties.__version = texture.version;
  15199. }
  15200. // Render targets
  15201. // Setup storage for target texture and bind it to correct framebuffer
  15202. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  15203. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15204. const glType = utils.convert( texture.type );
  15205. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15206. const renderTargetProperties = properties.get( renderTarget );
  15207. if ( ! renderTargetProperties.__hasExternalTextures ) {
  15208. const width = Math.max( 1, renderTarget.width >> level );
  15209. const height = Math.max( 1, renderTarget.height >> level );
  15210. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  15211. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  15212. } else {
  15213. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  15214. }
  15215. }
  15216. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15217. if ( useMultisampledRTT( renderTarget ) ) {
  15218. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  15219. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  15220. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  15221. }
  15222. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15223. }
  15224. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15225. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  15226. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15227. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15228. let glInternalFormat = ( isWebGL2 === true ) ? _gl.DEPTH_COMPONENT24 : _gl.DEPTH_COMPONENT16;
  15229. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  15230. const depthTexture = renderTarget.depthTexture;
  15231. if ( depthTexture && depthTexture.isDepthTexture ) {
  15232. if ( depthTexture.type === FloatType ) {
  15233. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  15234. } else if ( depthTexture.type === UnsignedIntType ) {
  15235. glInternalFormat = _gl.DEPTH_COMPONENT24;
  15236. }
  15237. }
  15238. const samples = getRenderTargetSamples( renderTarget );
  15239. if ( useMultisampledRTT( renderTarget ) ) {
  15240. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15241. } else {
  15242. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15243. }
  15244. } else {
  15245. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15246. }
  15247. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15248. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15249. const samples = getRenderTargetSamples( renderTarget );
  15250. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15251. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15252. } else if ( useMultisampledRTT( renderTarget ) ) {
  15253. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15254. } else {
  15255. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15256. }
  15257. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15258. } else {
  15259. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  15260. for ( let i = 0; i < textures.length; i ++ ) {
  15261. const texture = textures[ i ];
  15262. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15263. const glType = utils.convert( texture.type );
  15264. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15265. const samples = getRenderTargetSamples( renderTarget );
  15266. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15267. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15268. } else if ( useMultisampledRTT( renderTarget ) ) {
  15269. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15270. } else {
  15271. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15272. }
  15273. }
  15274. }
  15275. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15276. }
  15277. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15278. function setupDepthTexture( framebuffer, renderTarget ) {
  15279. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15280. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15281. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15282. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15283. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15284. }
  15285. // upload an empty depth texture with framebuffer size
  15286. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15287. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15288. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15289. renderTarget.depthTexture.image.width = renderTarget.width;
  15290. renderTarget.depthTexture.image.height = renderTarget.height;
  15291. renderTarget.depthTexture.needsUpdate = true;
  15292. }
  15293. setTexture2D( renderTarget.depthTexture, 0 );
  15294. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15295. const samples = getRenderTargetSamples( renderTarget );
  15296. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15297. if ( useMultisampledRTT( renderTarget ) ) {
  15298. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15299. } else {
  15300. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15301. }
  15302. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15303. if ( useMultisampledRTT( renderTarget ) ) {
  15304. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15305. } else {
  15306. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15307. }
  15308. } else {
  15309. throw new Error( 'Unknown depthTexture format' );
  15310. }
  15311. }
  15312. // Setup GL resources for a non-texture depth buffer
  15313. function setupDepthRenderbuffer( renderTarget ) {
  15314. const renderTargetProperties = properties.get( renderTarget );
  15315. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15316. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15317. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15318. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15319. } else {
  15320. if ( isCube ) {
  15321. renderTargetProperties.__webglDepthbuffer = [];
  15322. for ( let i = 0; i < 6; i ++ ) {
  15323. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15324. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15325. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15326. }
  15327. } else {
  15328. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15329. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15330. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15331. }
  15332. }
  15333. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15334. }
  15335. // rebind framebuffer with external textures
  15336. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15337. const renderTargetProperties = properties.get( renderTarget );
  15338. if ( colorTexture !== undefined ) {
  15339. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15340. }
  15341. if ( depthTexture !== undefined ) {
  15342. setupDepthRenderbuffer( renderTarget );
  15343. }
  15344. }
  15345. // Set up GL resources for the render target
  15346. function setupRenderTarget( renderTarget ) {
  15347. const texture = renderTarget.texture;
  15348. const renderTargetProperties = properties.get( renderTarget );
  15349. const textureProperties = properties.get( texture );
  15350. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15351. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  15352. if ( textureProperties.__webglTexture === undefined ) {
  15353. textureProperties.__webglTexture = _gl.createTexture();
  15354. }
  15355. textureProperties.__version = texture.version;
  15356. info.memory.textures ++;
  15357. }
  15358. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15359. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15360. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15361. // Setup framebuffer
  15362. if ( isCube ) {
  15363. renderTargetProperties.__webglFramebuffer = [];
  15364. for ( let i = 0; i < 6; i ++ ) {
  15365. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15366. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15367. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15368. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15369. }
  15370. } else {
  15371. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15372. }
  15373. }
  15374. } else {
  15375. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15376. renderTargetProperties.__webglFramebuffer = [];
  15377. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15378. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15379. }
  15380. } else {
  15381. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15382. }
  15383. if ( isMultipleRenderTargets ) {
  15384. if ( capabilities.drawBuffers ) {
  15385. const textures = renderTarget.texture;
  15386. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15387. const attachmentProperties = properties.get( textures[ i ] );
  15388. if ( attachmentProperties.__webglTexture === undefined ) {
  15389. attachmentProperties.__webglTexture = _gl.createTexture();
  15390. info.memory.textures ++;
  15391. }
  15392. }
  15393. } else {
  15394. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  15395. }
  15396. }
  15397. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15398. const textures = isMultipleRenderTargets ? texture : [ texture ];
  15399. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15400. renderTargetProperties.__webglColorRenderbuffer = [];
  15401. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15402. for ( let i = 0; i < textures.length; i ++ ) {
  15403. const texture = textures[ i ];
  15404. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15405. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15406. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15407. const glType = utils.convert( texture.type );
  15408. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15409. const samples = getRenderTargetSamples( renderTarget );
  15410. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15411. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15412. }
  15413. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15414. if ( renderTarget.depthBuffer ) {
  15415. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15416. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15417. }
  15418. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15419. }
  15420. }
  15421. // Setup color buffer
  15422. if ( isCube ) {
  15423. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15424. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  15425. for ( let i = 0; i < 6; i ++ ) {
  15426. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15427. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15428. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15429. }
  15430. } else {
  15431. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15432. }
  15433. }
  15434. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15435. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15436. }
  15437. state.unbindTexture();
  15438. } else if ( isMultipleRenderTargets ) {
  15439. const textures = renderTarget.texture;
  15440. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15441. const attachment = textures[ i ];
  15442. const attachmentProperties = properties.get( attachment );
  15443. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15444. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  15445. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15446. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  15447. generateMipmap( _gl.TEXTURE_2D );
  15448. }
  15449. }
  15450. state.unbindTexture();
  15451. } else {
  15452. let glTextureType = _gl.TEXTURE_2D;
  15453. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15454. if ( isWebGL2 ) {
  15455. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15456. } else {
  15457. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  15458. }
  15459. }
  15460. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15461. setTextureParameters( glTextureType, texture, supportsMips );
  15462. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15463. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15464. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15465. }
  15466. } else {
  15467. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15468. }
  15469. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15470. generateMipmap( glTextureType );
  15471. }
  15472. state.unbindTexture();
  15473. }
  15474. // Setup depth and stencil buffers
  15475. if ( renderTarget.depthBuffer ) {
  15476. setupDepthRenderbuffer( renderTarget );
  15477. }
  15478. }
  15479. function updateRenderTargetMipmap( renderTarget ) {
  15480. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15481. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  15482. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15483. const texture = textures[ i ];
  15484. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15485. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15486. const webglTexture = properties.get( texture ).__webglTexture;
  15487. state.bindTexture( target, webglTexture );
  15488. generateMipmap( target );
  15489. state.unbindTexture();
  15490. }
  15491. }
  15492. }
  15493. function updateMultisampleRenderTarget( renderTarget ) {
  15494. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15495. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  15496. const width = renderTarget.width;
  15497. const height = renderTarget.height;
  15498. let mask = _gl.COLOR_BUFFER_BIT;
  15499. const invalidationArray = [];
  15500. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15501. const renderTargetProperties = properties.get( renderTarget );
  15502. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15503. // If MRT we need to remove FBO attachments
  15504. if ( isMultipleRenderTargets ) {
  15505. for ( let i = 0; i < textures.length; i ++ ) {
  15506. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15507. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15508. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15509. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15510. }
  15511. }
  15512. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15513. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15514. for ( let i = 0; i < textures.length; i ++ ) {
  15515. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  15516. if ( renderTarget.depthBuffer ) {
  15517. invalidationArray.push( depthStyle );
  15518. }
  15519. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  15520. if ( ignoreDepthValues === false ) {
  15521. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15522. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15523. }
  15524. if ( isMultipleRenderTargets ) {
  15525. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15526. }
  15527. if ( ignoreDepthValues === true ) {
  15528. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  15529. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15530. }
  15531. if ( isMultipleRenderTargets ) {
  15532. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15533. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15534. }
  15535. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15536. if ( supportsInvalidateFramebuffer ) {
  15537. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  15538. }
  15539. }
  15540. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15541. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15542. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15543. if ( isMultipleRenderTargets ) {
  15544. for ( let i = 0; i < textures.length; i ++ ) {
  15545. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15546. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15547. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15548. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15549. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15550. }
  15551. }
  15552. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15553. }
  15554. }
  15555. function getRenderTargetSamples( renderTarget ) {
  15556. return Math.min( capabilities.maxSamples, renderTarget.samples );
  15557. }
  15558. function useMultisampledRTT( renderTarget ) {
  15559. const renderTargetProperties = properties.get( renderTarget );
  15560. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15561. }
  15562. function updateVideoTexture( texture ) {
  15563. const frame = info.render.frame;
  15564. // Check the last frame we updated the VideoTexture
  15565. if ( _videoTextures.get( texture ) !== frame ) {
  15566. _videoTextures.set( texture, frame );
  15567. texture.update();
  15568. }
  15569. }
  15570. function verifyColorSpace( texture, image ) {
  15571. const colorSpace = texture.colorSpace;
  15572. const format = texture.format;
  15573. const type = texture.type;
  15574. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  15575. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15576. // sRGB
  15577. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15578. if ( isWebGL2 === false ) {
  15579. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  15580. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  15581. texture.format = _SRGBAFormat;
  15582. // it's not possible to generate mips in WebGL 1 with this extension
  15583. texture.minFilter = LinearFilter;
  15584. texture.generateMipmaps = false;
  15585. } else {
  15586. // slow fallback (CPU decode)
  15587. image = ImageUtils.sRGBToLinear( image );
  15588. }
  15589. } else {
  15590. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15591. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15592. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15593. }
  15594. }
  15595. } else {
  15596. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15597. }
  15598. }
  15599. return image;
  15600. }
  15601. //
  15602. this.allocateTextureUnit = allocateTextureUnit;
  15603. this.resetTextureUnits = resetTextureUnits;
  15604. this.setTexture2D = setTexture2D;
  15605. this.setTexture2DArray = setTexture2DArray;
  15606. this.setTexture3D = setTexture3D;
  15607. this.setTextureCube = setTextureCube;
  15608. this.rebindTextures = rebindTextures;
  15609. this.setupRenderTarget = setupRenderTarget;
  15610. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15611. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15612. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15613. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15614. this.useMultisampledRTT = useMultisampledRTT;
  15615. }
  15616. function WebGLUtils( gl, extensions, capabilities ) {
  15617. const isWebGL2 = capabilities.isWebGL2;
  15618. function convert( p, colorSpace = NoColorSpace ) {
  15619. let extension;
  15620. const transfer = ColorManagement.getTransfer( colorSpace );
  15621. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15622. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15623. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15624. if ( p === ByteType ) return gl.BYTE;
  15625. if ( p === ShortType ) return gl.SHORT;
  15626. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15627. if ( p === IntType ) return gl.INT;
  15628. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15629. if ( p === FloatType ) return gl.FLOAT;
  15630. if ( p === HalfFloatType ) {
  15631. if ( isWebGL2 ) return gl.HALF_FLOAT;
  15632. extension = extensions.get( 'OES_texture_half_float' );
  15633. if ( extension !== null ) {
  15634. return extension.HALF_FLOAT_OES;
  15635. } else {
  15636. return null;
  15637. }
  15638. }
  15639. if ( p === AlphaFormat ) return gl.ALPHA;
  15640. if ( p === RGBAFormat ) return gl.RGBA;
  15641. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15642. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15643. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15644. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15645. // WebGL 1 sRGB fallback
  15646. if ( p === _SRGBAFormat ) {
  15647. extension = extensions.get( 'EXT_sRGB' );
  15648. if ( extension !== null ) {
  15649. return extension.SRGB_ALPHA_EXT;
  15650. } else {
  15651. return null;
  15652. }
  15653. }
  15654. // WebGL2 formats.
  15655. if ( p === RedFormat ) return gl.RED;
  15656. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15657. if ( p === RGFormat ) return gl.RG;
  15658. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15659. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15660. // S3TC
  15661. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15662. if ( transfer === SRGBTransfer ) {
  15663. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15664. if ( extension !== null ) {
  15665. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15666. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15667. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15668. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15669. } else {
  15670. return null;
  15671. }
  15672. } else {
  15673. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15674. if ( extension !== null ) {
  15675. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15676. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15677. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15678. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15679. } else {
  15680. return null;
  15681. }
  15682. }
  15683. }
  15684. // PVRTC
  15685. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15686. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15687. if ( extension !== null ) {
  15688. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15689. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15690. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15691. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15692. } else {
  15693. return null;
  15694. }
  15695. }
  15696. // ETC1
  15697. if ( p === RGB_ETC1_Format ) {
  15698. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15699. if ( extension !== null ) {
  15700. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15701. } else {
  15702. return null;
  15703. }
  15704. }
  15705. // ETC2
  15706. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15707. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15708. if ( extension !== null ) {
  15709. if ( p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15710. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15711. } else {
  15712. return null;
  15713. }
  15714. }
  15715. // ASTC
  15716. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15717. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15718. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15719. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15720. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15721. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15722. if ( extension !== null ) {
  15723. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15724. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15725. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15726. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15727. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15728. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15729. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15730. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15731. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15732. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15733. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15734. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15735. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15736. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15737. } else {
  15738. return null;
  15739. }
  15740. }
  15741. // BPTC
  15742. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15743. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15744. if ( extension !== null ) {
  15745. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15746. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15747. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15748. } else {
  15749. return null;
  15750. }
  15751. }
  15752. // RGTC
  15753. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15754. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15755. if ( extension !== null ) {
  15756. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15757. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15758. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15759. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15760. } else {
  15761. return null;
  15762. }
  15763. }
  15764. //
  15765. if ( p === UnsignedInt248Type ) {
  15766. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  15767. extension = extensions.get( 'WEBGL_depth_texture' );
  15768. if ( extension !== null ) {
  15769. return extension.UNSIGNED_INT_24_8_WEBGL;
  15770. } else {
  15771. return null;
  15772. }
  15773. }
  15774. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15775. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15776. }
  15777. return { convert: convert };
  15778. }
  15779. class ArrayCamera extends PerspectiveCamera {
  15780. constructor( array = [] ) {
  15781. super();
  15782. this.isArrayCamera = true;
  15783. this.cameras = array;
  15784. }
  15785. }
  15786. class Group extends Object3D {
  15787. constructor() {
  15788. super();
  15789. this.isGroup = true;
  15790. this.type = 'Group';
  15791. }
  15792. }
  15793. const _moveEvent = { type: 'move' };
  15794. class WebXRController {
  15795. constructor() {
  15796. this._targetRay = null;
  15797. this._grip = null;
  15798. this._hand = null;
  15799. }
  15800. getHandSpace() {
  15801. if ( this._hand === null ) {
  15802. this._hand = new Group();
  15803. this._hand.matrixAutoUpdate = false;
  15804. this._hand.visible = false;
  15805. this._hand.joints = {};
  15806. this._hand.inputState = { pinching: false };
  15807. }
  15808. return this._hand;
  15809. }
  15810. getTargetRaySpace() {
  15811. if ( this._targetRay === null ) {
  15812. this._targetRay = new Group();
  15813. this._targetRay.matrixAutoUpdate = false;
  15814. this._targetRay.visible = false;
  15815. this._targetRay.hasLinearVelocity = false;
  15816. this._targetRay.linearVelocity = new Vector3();
  15817. this._targetRay.hasAngularVelocity = false;
  15818. this._targetRay.angularVelocity = new Vector3();
  15819. }
  15820. return this._targetRay;
  15821. }
  15822. getGripSpace() {
  15823. if ( this._grip === null ) {
  15824. this._grip = new Group();
  15825. this._grip.matrixAutoUpdate = false;
  15826. this._grip.visible = false;
  15827. this._grip.hasLinearVelocity = false;
  15828. this._grip.linearVelocity = new Vector3();
  15829. this._grip.hasAngularVelocity = false;
  15830. this._grip.angularVelocity = new Vector3();
  15831. }
  15832. return this._grip;
  15833. }
  15834. dispatchEvent( event ) {
  15835. if ( this._targetRay !== null ) {
  15836. this._targetRay.dispatchEvent( event );
  15837. }
  15838. if ( this._grip !== null ) {
  15839. this._grip.dispatchEvent( event );
  15840. }
  15841. if ( this._hand !== null ) {
  15842. this._hand.dispatchEvent( event );
  15843. }
  15844. return this;
  15845. }
  15846. connect( inputSource ) {
  15847. if ( inputSource && inputSource.hand ) {
  15848. const hand = this._hand;
  15849. if ( hand ) {
  15850. for ( const inputjoint of inputSource.hand.values() ) {
  15851. // Initialize hand with joints when connected
  15852. this._getHandJoint( hand, inputjoint );
  15853. }
  15854. }
  15855. }
  15856. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15857. return this;
  15858. }
  15859. disconnect( inputSource ) {
  15860. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15861. if ( this._targetRay !== null ) {
  15862. this._targetRay.visible = false;
  15863. }
  15864. if ( this._grip !== null ) {
  15865. this._grip.visible = false;
  15866. }
  15867. if ( this._hand !== null ) {
  15868. this._hand.visible = false;
  15869. }
  15870. return this;
  15871. }
  15872. update( inputSource, frame, referenceSpace ) {
  15873. let inputPose = null;
  15874. let gripPose = null;
  15875. let handPose = null;
  15876. const targetRay = this._targetRay;
  15877. const grip = this._grip;
  15878. const hand = this._hand;
  15879. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15880. if ( hand && inputSource.hand ) {
  15881. handPose = true;
  15882. for ( const inputjoint of inputSource.hand.values() ) {
  15883. // Update the joints groups with the XRJoint poses
  15884. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15885. // The transform of this joint will be updated with the joint pose on each frame
  15886. const joint = this._getHandJoint( hand, inputjoint );
  15887. if ( jointPose !== null ) {
  15888. joint.matrix.fromArray( jointPose.transform.matrix );
  15889. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15890. joint.matrixWorldNeedsUpdate = true;
  15891. joint.jointRadius = jointPose.radius;
  15892. }
  15893. joint.visible = jointPose !== null;
  15894. }
  15895. // Custom events
  15896. // Check pinchz
  15897. const indexTip = hand.joints[ 'index-finger-tip' ];
  15898. const thumbTip = hand.joints[ 'thumb-tip' ];
  15899. const distance = indexTip.position.distanceTo( thumbTip.position );
  15900. const distanceToPinch = 0.02;
  15901. const threshold = 0.005;
  15902. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15903. hand.inputState.pinching = false;
  15904. this.dispatchEvent( {
  15905. type: 'pinchend',
  15906. handedness: inputSource.handedness,
  15907. target: this
  15908. } );
  15909. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15910. hand.inputState.pinching = true;
  15911. this.dispatchEvent( {
  15912. type: 'pinchstart',
  15913. handedness: inputSource.handedness,
  15914. target: this
  15915. } );
  15916. }
  15917. } else {
  15918. if ( grip !== null && inputSource.gripSpace ) {
  15919. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15920. if ( gripPose !== null ) {
  15921. grip.matrix.fromArray( gripPose.transform.matrix );
  15922. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15923. grip.matrixWorldNeedsUpdate = true;
  15924. if ( gripPose.linearVelocity ) {
  15925. grip.hasLinearVelocity = true;
  15926. grip.linearVelocity.copy( gripPose.linearVelocity );
  15927. } else {
  15928. grip.hasLinearVelocity = false;
  15929. }
  15930. if ( gripPose.angularVelocity ) {
  15931. grip.hasAngularVelocity = true;
  15932. grip.angularVelocity.copy( gripPose.angularVelocity );
  15933. } else {
  15934. grip.hasAngularVelocity = false;
  15935. }
  15936. }
  15937. }
  15938. }
  15939. if ( targetRay !== null ) {
  15940. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15941. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15942. if ( inputPose === null && gripPose !== null ) {
  15943. inputPose = gripPose;
  15944. }
  15945. if ( inputPose !== null ) {
  15946. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15947. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15948. targetRay.matrixWorldNeedsUpdate = true;
  15949. if ( inputPose.linearVelocity ) {
  15950. targetRay.hasLinearVelocity = true;
  15951. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15952. } else {
  15953. targetRay.hasLinearVelocity = false;
  15954. }
  15955. if ( inputPose.angularVelocity ) {
  15956. targetRay.hasAngularVelocity = true;
  15957. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15958. } else {
  15959. targetRay.hasAngularVelocity = false;
  15960. }
  15961. this.dispatchEvent( _moveEvent );
  15962. }
  15963. }
  15964. }
  15965. if ( targetRay !== null ) {
  15966. targetRay.visible = ( inputPose !== null );
  15967. }
  15968. if ( grip !== null ) {
  15969. grip.visible = ( gripPose !== null );
  15970. }
  15971. if ( hand !== null ) {
  15972. hand.visible = ( handPose !== null );
  15973. }
  15974. return this;
  15975. }
  15976. // private method
  15977. _getHandJoint( hand, inputjoint ) {
  15978. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15979. const joint = new Group();
  15980. joint.matrixAutoUpdate = false;
  15981. joint.visible = false;
  15982. hand.joints[ inputjoint.jointName ] = joint;
  15983. hand.add( joint );
  15984. }
  15985. return hand.joints[ inputjoint.jointName ];
  15986. }
  15987. }
  15988. class WebXRManager extends EventDispatcher {
  15989. constructor( renderer, gl ) {
  15990. super();
  15991. const scope = this;
  15992. let session = null;
  15993. let framebufferScaleFactor = 1.0;
  15994. let referenceSpace = null;
  15995. let referenceSpaceType = 'local-floor';
  15996. // Set default foveation to maximum.
  15997. let foveation = 1.0;
  15998. let customReferenceSpace = null;
  15999. let pose = null;
  16000. let glBinding = null;
  16001. let glProjLayer = null;
  16002. let glBaseLayer = null;
  16003. let xrFrame = null;
  16004. const attributes = gl.getContextAttributes();
  16005. let initialRenderTarget = null;
  16006. let newRenderTarget = null;
  16007. const controllers = [];
  16008. const controllerInputSources = [];
  16009. const currentSize = new Vector2();
  16010. let currentPixelRatio = null;
  16011. //
  16012. const cameraL = new PerspectiveCamera();
  16013. cameraL.layers.enable( 1 );
  16014. cameraL.viewport = new Vector4();
  16015. const cameraR = new PerspectiveCamera();
  16016. cameraR.layers.enable( 2 );
  16017. cameraR.viewport = new Vector4();
  16018. const cameras = [ cameraL, cameraR ];
  16019. const cameraXR = new ArrayCamera();
  16020. cameraXR.layers.enable( 1 );
  16021. cameraXR.layers.enable( 2 );
  16022. let _currentDepthNear = null;
  16023. let _currentDepthFar = null;
  16024. //
  16025. this.cameraAutoUpdate = true;
  16026. this.enabled = false;
  16027. this.isPresenting = false;
  16028. this.getController = function ( index ) {
  16029. let controller = controllers[ index ];
  16030. if ( controller === undefined ) {
  16031. controller = new WebXRController();
  16032. controllers[ index ] = controller;
  16033. }
  16034. return controller.getTargetRaySpace();
  16035. };
  16036. this.getControllerGrip = function ( index ) {
  16037. let controller = controllers[ index ];
  16038. if ( controller === undefined ) {
  16039. controller = new WebXRController();
  16040. controllers[ index ] = controller;
  16041. }
  16042. return controller.getGripSpace();
  16043. };
  16044. this.getHand = function ( index ) {
  16045. let controller = controllers[ index ];
  16046. if ( controller === undefined ) {
  16047. controller = new WebXRController();
  16048. controllers[ index ] = controller;
  16049. }
  16050. return controller.getHandSpace();
  16051. };
  16052. //
  16053. function onSessionEvent( event ) {
  16054. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  16055. if ( controllerIndex === - 1 ) {
  16056. return;
  16057. }
  16058. const controller = controllers[ controllerIndex ];
  16059. if ( controller !== undefined ) {
  16060. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  16061. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  16062. }
  16063. }
  16064. function onSessionEnd() {
  16065. session.removeEventListener( 'select', onSessionEvent );
  16066. session.removeEventListener( 'selectstart', onSessionEvent );
  16067. session.removeEventListener( 'selectend', onSessionEvent );
  16068. session.removeEventListener( 'squeeze', onSessionEvent );
  16069. session.removeEventListener( 'squeezestart', onSessionEvent );
  16070. session.removeEventListener( 'squeezeend', onSessionEvent );
  16071. session.removeEventListener( 'end', onSessionEnd );
  16072. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  16073. for ( let i = 0; i < controllers.length; i ++ ) {
  16074. const inputSource = controllerInputSources[ i ];
  16075. if ( inputSource === null ) continue;
  16076. controllerInputSources[ i ] = null;
  16077. controllers[ i ].disconnect( inputSource );
  16078. }
  16079. _currentDepthNear = null;
  16080. _currentDepthFar = null;
  16081. // restore framebuffer/rendering state
  16082. renderer.setRenderTarget( initialRenderTarget );
  16083. glBaseLayer = null;
  16084. glProjLayer = null;
  16085. glBinding = null;
  16086. session = null;
  16087. newRenderTarget = null;
  16088. //
  16089. animation.stop();
  16090. scope.isPresenting = false;
  16091. renderer.setPixelRatio( currentPixelRatio );
  16092. renderer.setSize( currentSize.width, currentSize.height, false );
  16093. scope.dispatchEvent( { type: 'sessionend' } );
  16094. }
  16095. this.setFramebufferScaleFactor = function ( value ) {
  16096. framebufferScaleFactor = value;
  16097. if ( scope.isPresenting === true ) {
  16098. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  16099. }
  16100. };
  16101. this.setReferenceSpaceType = function ( value ) {
  16102. referenceSpaceType = value;
  16103. if ( scope.isPresenting === true ) {
  16104. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  16105. }
  16106. };
  16107. this.getReferenceSpace = function () {
  16108. return customReferenceSpace || referenceSpace;
  16109. };
  16110. this.setReferenceSpace = function ( space ) {
  16111. customReferenceSpace = space;
  16112. };
  16113. this.getBaseLayer = function () {
  16114. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  16115. };
  16116. this.getBinding = function () {
  16117. return glBinding;
  16118. };
  16119. this.getFrame = function () {
  16120. return xrFrame;
  16121. };
  16122. this.getSession = function () {
  16123. return session;
  16124. };
  16125. this.setSession = async function ( value ) {
  16126. session = value;
  16127. if ( session !== null ) {
  16128. initialRenderTarget = renderer.getRenderTarget();
  16129. session.addEventListener( 'select', onSessionEvent );
  16130. session.addEventListener( 'selectstart', onSessionEvent );
  16131. session.addEventListener( 'selectend', onSessionEvent );
  16132. session.addEventListener( 'squeeze', onSessionEvent );
  16133. session.addEventListener( 'squeezestart', onSessionEvent );
  16134. session.addEventListener( 'squeezeend', onSessionEvent );
  16135. session.addEventListener( 'end', onSessionEnd );
  16136. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  16137. if ( attributes.xrCompatible !== true ) {
  16138. await gl.makeXRCompatible();
  16139. }
  16140. currentPixelRatio = renderer.getPixelRatio();
  16141. renderer.getSize( currentSize );
  16142. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  16143. const layerInit = {
  16144. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  16145. alpha: true,
  16146. depth: attributes.depth,
  16147. stencil: attributes.stencil,
  16148. framebufferScaleFactor: framebufferScaleFactor
  16149. };
  16150. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  16151. session.updateRenderState( { baseLayer: glBaseLayer } );
  16152. renderer.setPixelRatio( 1 );
  16153. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  16154. newRenderTarget = new WebGLRenderTarget(
  16155. glBaseLayer.framebufferWidth,
  16156. glBaseLayer.framebufferHeight,
  16157. {
  16158. format: RGBAFormat,
  16159. type: UnsignedByteType,
  16160. colorSpace: renderer.outputColorSpace,
  16161. stencilBuffer: attributes.stencil
  16162. }
  16163. );
  16164. } else {
  16165. let depthFormat = null;
  16166. let depthType = null;
  16167. let glDepthFormat = null;
  16168. if ( attributes.depth ) {
  16169. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  16170. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  16171. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  16172. }
  16173. const projectionlayerInit = {
  16174. colorFormat: gl.RGBA8,
  16175. depthFormat: glDepthFormat,
  16176. scaleFactor: framebufferScaleFactor
  16177. };
  16178. glBinding = new XRWebGLBinding( session, gl );
  16179. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  16180. session.updateRenderState( { layers: [ glProjLayer ] } );
  16181. renderer.setPixelRatio( 1 );
  16182. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  16183. newRenderTarget = new WebGLRenderTarget(
  16184. glProjLayer.textureWidth,
  16185. glProjLayer.textureHeight,
  16186. {
  16187. format: RGBAFormat,
  16188. type: UnsignedByteType,
  16189. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  16190. stencilBuffer: attributes.stencil,
  16191. colorSpace: renderer.outputColorSpace,
  16192. samples: attributes.antialias ? 4 : 0
  16193. } );
  16194. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  16195. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  16196. }
  16197. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  16198. this.setFoveation( foveation );
  16199. customReferenceSpace = null;
  16200. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  16201. animation.setContext( session );
  16202. animation.start();
  16203. scope.isPresenting = true;
  16204. scope.dispatchEvent( { type: 'sessionstart' } );
  16205. }
  16206. };
  16207. this.getEnvironmentBlendMode = function () {
  16208. if ( session !== null ) {
  16209. return session.environmentBlendMode;
  16210. }
  16211. };
  16212. function onInputSourcesChange( event ) {
  16213. // Notify disconnected
  16214. for ( let i = 0; i < event.removed.length; i ++ ) {
  16215. const inputSource = event.removed[ i ];
  16216. const index = controllerInputSources.indexOf( inputSource );
  16217. if ( index >= 0 ) {
  16218. controllerInputSources[ index ] = null;
  16219. controllers[ index ].disconnect( inputSource );
  16220. }
  16221. }
  16222. // Notify connected
  16223. for ( let i = 0; i < event.added.length; i ++ ) {
  16224. const inputSource = event.added[ i ];
  16225. let controllerIndex = controllerInputSources.indexOf( inputSource );
  16226. if ( controllerIndex === - 1 ) {
  16227. // Assign input source a controller that currently has no input source
  16228. for ( let i = 0; i < controllers.length; i ++ ) {
  16229. if ( i >= controllerInputSources.length ) {
  16230. controllerInputSources.push( inputSource );
  16231. controllerIndex = i;
  16232. break;
  16233. } else if ( controllerInputSources[ i ] === null ) {
  16234. controllerInputSources[ i ] = inputSource;
  16235. controllerIndex = i;
  16236. break;
  16237. }
  16238. }
  16239. // If all controllers do currently receive input we ignore new ones
  16240. if ( controllerIndex === - 1 ) break;
  16241. }
  16242. const controller = controllers[ controllerIndex ];
  16243. if ( controller ) {
  16244. controller.connect( inputSource );
  16245. }
  16246. }
  16247. }
  16248. //
  16249. const cameraLPos = new Vector3();
  16250. const cameraRPos = new Vector3();
  16251. /**
  16252. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16253. * the cameras' projection and world matrices have already been set.
  16254. * And that near and far planes are identical for both cameras.
  16255. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16256. */
  16257. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16258. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16259. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16260. const ipd = cameraLPos.distanceTo( cameraRPos );
  16261. const projL = cameraL.projectionMatrix.elements;
  16262. const projR = cameraR.projectionMatrix.elements;
  16263. // VR systems will have identical far and near planes, and
  16264. // most likely identical top and bottom frustum extents.
  16265. // Use the left camera for these values.
  16266. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16267. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16268. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16269. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16270. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16271. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16272. const left = near * leftFov;
  16273. const right = near * rightFov;
  16274. // Calculate the new camera's position offset from the
  16275. // left camera. xOffset should be roughly half `ipd`.
  16276. const zOffset = ipd / ( - leftFov + rightFov );
  16277. const xOffset = zOffset * - leftFov;
  16278. // TODO: Better way to apply this offset?
  16279. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16280. camera.translateX( xOffset );
  16281. camera.translateZ( zOffset );
  16282. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16283. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16284. // Find the union of the frustum values of the cameras and scale
  16285. // the values so that the near plane's position does not change in world space,
  16286. // although must now be relative to the new union camera.
  16287. const near2 = near + zOffset;
  16288. const far2 = far + zOffset;
  16289. const left2 = left - xOffset;
  16290. const right2 = right + ( ipd - xOffset );
  16291. const top2 = topFov * far / far2 * near2;
  16292. const bottom2 = bottomFov * far / far2 * near2;
  16293. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16294. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16295. }
  16296. function updateCamera( camera, parent ) {
  16297. if ( parent === null ) {
  16298. camera.matrixWorld.copy( camera.matrix );
  16299. } else {
  16300. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16301. }
  16302. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16303. }
  16304. this.updateCamera = function ( camera ) {
  16305. if ( session === null ) return;
  16306. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  16307. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  16308. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16309. // Note that the new renderState won't apply until the next frame. See #18320
  16310. session.updateRenderState( {
  16311. depthNear: cameraXR.near,
  16312. depthFar: cameraXR.far
  16313. } );
  16314. _currentDepthNear = cameraXR.near;
  16315. _currentDepthFar = cameraXR.far;
  16316. }
  16317. const parent = camera.parent;
  16318. const cameras = cameraXR.cameras;
  16319. updateCamera( cameraXR, parent );
  16320. for ( let i = 0; i < cameras.length; i ++ ) {
  16321. updateCamera( cameras[ i ], parent );
  16322. }
  16323. // update projection matrix for proper view frustum culling
  16324. if ( cameras.length === 2 ) {
  16325. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16326. } else {
  16327. // assume single camera setup (AR)
  16328. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16329. }
  16330. // update user camera and its children
  16331. updateUserCamera( camera, cameraXR, parent );
  16332. };
  16333. function updateUserCamera( camera, cameraXR, parent ) {
  16334. if ( parent === null ) {
  16335. camera.matrix.copy( cameraXR.matrixWorld );
  16336. } else {
  16337. camera.matrix.copy( parent.matrixWorld );
  16338. camera.matrix.invert();
  16339. camera.matrix.multiply( cameraXR.matrixWorld );
  16340. }
  16341. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16342. camera.updateMatrixWorld( true );
  16343. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16344. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16345. if ( camera.isPerspectiveCamera ) {
  16346. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16347. camera.zoom = 1;
  16348. }
  16349. }
  16350. this.getCamera = function () {
  16351. return cameraXR;
  16352. };
  16353. this.getFoveation = function () {
  16354. if ( glProjLayer === null && glBaseLayer === null ) {
  16355. return undefined;
  16356. }
  16357. return foveation;
  16358. };
  16359. this.setFoveation = function ( value ) {
  16360. // 0 = no foveation = full resolution
  16361. // 1 = maximum foveation = the edges render at lower resolution
  16362. foveation = value;
  16363. if ( glProjLayer !== null ) {
  16364. glProjLayer.fixedFoveation = value;
  16365. }
  16366. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16367. glBaseLayer.fixedFoveation = value;
  16368. }
  16369. };
  16370. // Animation Loop
  16371. let onAnimationFrameCallback = null;
  16372. function onAnimationFrame( time, frame ) {
  16373. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16374. xrFrame = frame;
  16375. if ( pose !== null ) {
  16376. const views = pose.views;
  16377. if ( glBaseLayer !== null ) {
  16378. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16379. renderer.setRenderTarget( newRenderTarget );
  16380. }
  16381. let cameraXRNeedsUpdate = false;
  16382. // check if it's necessary to rebuild cameraXR's camera list
  16383. if ( views.length !== cameraXR.cameras.length ) {
  16384. cameraXR.cameras.length = 0;
  16385. cameraXRNeedsUpdate = true;
  16386. }
  16387. for ( let i = 0; i < views.length; i ++ ) {
  16388. const view = views[ i ];
  16389. let viewport = null;
  16390. if ( glBaseLayer !== null ) {
  16391. viewport = glBaseLayer.getViewport( view );
  16392. } else {
  16393. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16394. viewport = glSubImage.viewport;
  16395. // For side-by-side projection, we only produce a single texture for both eyes.
  16396. if ( i === 0 ) {
  16397. renderer.setRenderTargetTextures(
  16398. newRenderTarget,
  16399. glSubImage.colorTexture,
  16400. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16401. renderer.setRenderTarget( newRenderTarget );
  16402. }
  16403. }
  16404. let camera = cameras[ i ];
  16405. if ( camera === undefined ) {
  16406. camera = new PerspectiveCamera();
  16407. camera.layers.enable( i );
  16408. camera.viewport = new Vector4();
  16409. cameras[ i ] = camera;
  16410. }
  16411. camera.matrix.fromArray( view.transform.matrix );
  16412. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16413. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16414. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16415. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16416. if ( i === 0 ) {
  16417. cameraXR.matrix.copy( camera.matrix );
  16418. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16419. }
  16420. if ( cameraXRNeedsUpdate === true ) {
  16421. cameraXR.cameras.push( camera );
  16422. }
  16423. }
  16424. }
  16425. //
  16426. for ( let i = 0; i < controllers.length; i ++ ) {
  16427. const inputSource = controllerInputSources[ i ];
  16428. const controller = controllers[ i ];
  16429. if ( inputSource !== null && controller !== undefined ) {
  16430. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16431. }
  16432. }
  16433. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16434. if ( frame.detectedPlanes ) {
  16435. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16436. }
  16437. xrFrame = null;
  16438. }
  16439. const animation = new WebGLAnimation();
  16440. animation.setAnimationLoop( onAnimationFrame );
  16441. this.setAnimationLoop = function ( callback ) {
  16442. onAnimationFrameCallback = callback;
  16443. };
  16444. this.dispose = function () {};
  16445. }
  16446. }
  16447. function WebGLMaterials( renderer, properties ) {
  16448. function refreshTransformUniform( map, uniform ) {
  16449. if ( map.matrixAutoUpdate === true ) {
  16450. map.updateMatrix();
  16451. }
  16452. uniform.value.copy( map.matrix );
  16453. }
  16454. function refreshFogUniforms( uniforms, fog ) {
  16455. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16456. if ( fog.isFog ) {
  16457. uniforms.fogNear.value = fog.near;
  16458. uniforms.fogFar.value = fog.far;
  16459. } else if ( fog.isFogExp2 ) {
  16460. uniforms.fogDensity.value = fog.density;
  16461. }
  16462. }
  16463. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16464. if ( material.isMeshBasicMaterial ) {
  16465. refreshUniformsCommon( uniforms, material );
  16466. } else if ( material.isMeshLambertMaterial ) {
  16467. refreshUniformsCommon( uniforms, material );
  16468. } else if ( material.isMeshToonMaterial ) {
  16469. refreshUniformsCommon( uniforms, material );
  16470. refreshUniformsToon( uniforms, material );
  16471. } else if ( material.isMeshPhongMaterial ) {
  16472. refreshUniformsCommon( uniforms, material );
  16473. refreshUniformsPhong( uniforms, material );
  16474. } else if ( material.isMeshStandardMaterial ) {
  16475. refreshUniformsCommon( uniforms, material );
  16476. refreshUniformsStandard( uniforms, material );
  16477. if ( material.isMeshPhysicalMaterial ) {
  16478. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16479. }
  16480. } else if ( material.isMeshMatcapMaterial ) {
  16481. refreshUniformsCommon( uniforms, material );
  16482. refreshUniformsMatcap( uniforms, material );
  16483. } else if ( material.isMeshDepthMaterial ) {
  16484. refreshUniformsCommon( uniforms, material );
  16485. } else if ( material.isMeshDistanceMaterial ) {
  16486. refreshUniformsCommon( uniforms, material );
  16487. refreshUniformsDistance( uniforms, material );
  16488. } else if ( material.isMeshNormalMaterial ) {
  16489. refreshUniformsCommon( uniforms, material );
  16490. } else if ( material.isLineBasicMaterial ) {
  16491. refreshUniformsLine( uniforms, material );
  16492. if ( material.isLineDashedMaterial ) {
  16493. refreshUniformsDash( uniforms, material );
  16494. }
  16495. } else if ( material.isPointsMaterial ) {
  16496. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16497. } else if ( material.isSpriteMaterial ) {
  16498. refreshUniformsSprites( uniforms, material );
  16499. } else if ( material.isShadowMaterial ) {
  16500. uniforms.color.value.copy( material.color );
  16501. uniforms.opacity.value = material.opacity;
  16502. } else if ( material.isShaderMaterial ) {
  16503. material.uniformsNeedUpdate = false; // #15581
  16504. }
  16505. }
  16506. function refreshUniformsCommon( uniforms, material ) {
  16507. uniforms.opacity.value = material.opacity;
  16508. if ( material.color ) {
  16509. uniforms.diffuse.value.copy( material.color );
  16510. }
  16511. if ( material.emissive ) {
  16512. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16513. }
  16514. if ( material.map ) {
  16515. uniforms.map.value = material.map;
  16516. refreshTransformUniform( material.map, uniforms.mapTransform );
  16517. }
  16518. if ( material.alphaMap ) {
  16519. uniforms.alphaMap.value = material.alphaMap;
  16520. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16521. }
  16522. if ( material.bumpMap ) {
  16523. uniforms.bumpMap.value = material.bumpMap;
  16524. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16525. uniforms.bumpScale.value = material.bumpScale;
  16526. if ( material.side === BackSide ) {
  16527. uniforms.bumpScale.value *= - 1;
  16528. }
  16529. }
  16530. if ( material.normalMap ) {
  16531. uniforms.normalMap.value = material.normalMap;
  16532. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16533. uniforms.normalScale.value.copy( material.normalScale );
  16534. if ( material.side === BackSide ) {
  16535. uniforms.normalScale.value.negate();
  16536. }
  16537. }
  16538. if ( material.displacementMap ) {
  16539. uniforms.displacementMap.value = material.displacementMap;
  16540. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16541. uniforms.displacementScale.value = material.displacementScale;
  16542. uniforms.displacementBias.value = material.displacementBias;
  16543. }
  16544. if ( material.emissiveMap ) {
  16545. uniforms.emissiveMap.value = material.emissiveMap;
  16546. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16547. }
  16548. if ( material.specularMap ) {
  16549. uniforms.specularMap.value = material.specularMap;
  16550. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16551. }
  16552. if ( material.alphaTest > 0 ) {
  16553. uniforms.alphaTest.value = material.alphaTest;
  16554. }
  16555. const envMap = properties.get( material ).envMap;
  16556. if ( envMap ) {
  16557. uniforms.envMap.value = envMap;
  16558. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16559. uniforms.reflectivity.value = material.reflectivity;
  16560. uniforms.ior.value = material.ior;
  16561. uniforms.refractionRatio.value = material.refractionRatio;
  16562. }
  16563. if ( material.lightMap ) {
  16564. uniforms.lightMap.value = material.lightMap;
  16565. // artist-friendly light intensity scaling factor
  16566. const scaleFactor = ( renderer._useLegacyLights === true ) ? Math.PI : 1;
  16567. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16568. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16569. }
  16570. if ( material.aoMap ) {
  16571. uniforms.aoMap.value = material.aoMap;
  16572. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16573. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16574. }
  16575. }
  16576. function refreshUniformsLine( uniforms, material ) {
  16577. uniforms.diffuse.value.copy( material.color );
  16578. uniforms.opacity.value = material.opacity;
  16579. if ( material.map ) {
  16580. uniforms.map.value = material.map;
  16581. refreshTransformUniform( material.map, uniforms.mapTransform );
  16582. }
  16583. }
  16584. function refreshUniformsDash( uniforms, material ) {
  16585. uniforms.dashSize.value = material.dashSize;
  16586. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16587. uniforms.scale.value = material.scale;
  16588. }
  16589. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16590. uniforms.diffuse.value.copy( material.color );
  16591. uniforms.opacity.value = material.opacity;
  16592. uniforms.size.value = material.size * pixelRatio;
  16593. uniforms.scale.value = height * 0.5;
  16594. if ( material.map ) {
  16595. uniforms.map.value = material.map;
  16596. refreshTransformUniform( material.map, uniforms.uvTransform );
  16597. }
  16598. if ( material.alphaMap ) {
  16599. uniforms.alphaMap.value = material.alphaMap;
  16600. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16601. }
  16602. if ( material.alphaTest > 0 ) {
  16603. uniforms.alphaTest.value = material.alphaTest;
  16604. }
  16605. }
  16606. function refreshUniformsSprites( uniforms, material ) {
  16607. uniforms.diffuse.value.copy( material.color );
  16608. uniforms.opacity.value = material.opacity;
  16609. uniforms.rotation.value = material.rotation;
  16610. if ( material.map ) {
  16611. uniforms.map.value = material.map;
  16612. refreshTransformUniform( material.map, uniforms.mapTransform );
  16613. }
  16614. if ( material.alphaMap ) {
  16615. uniforms.alphaMap.value = material.alphaMap;
  16616. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16617. }
  16618. if ( material.alphaTest > 0 ) {
  16619. uniforms.alphaTest.value = material.alphaTest;
  16620. }
  16621. }
  16622. function refreshUniformsPhong( uniforms, material ) {
  16623. uniforms.specular.value.copy( material.specular );
  16624. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16625. }
  16626. function refreshUniformsToon( uniforms, material ) {
  16627. if ( material.gradientMap ) {
  16628. uniforms.gradientMap.value = material.gradientMap;
  16629. }
  16630. }
  16631. function refreshUniformsStandard( uniforms, material ) {
  16632. uniforms.metalness.value = material.metalness;
  16633. if ( material.metalnessMap ) {
  16634. uniforms.metalnessMap.value = material.metalnessMap;
  16635. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16636. }
  16637. uniforms.roughness.value = material.roughness;
  16638. if ( material.roughnessMap ) {
  16639. uniforms.roughnessMap.value = material.roughnessMap;
  16640. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16641. }
  16642. const envMap = properties.get( material ).envMap;
  16643. if ( envMap ) {
  16644. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16645. uniforms.envMapIntensity.value = material.envMapIntensity;
  16646. }
  16647. }
  16648. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16649. uniforms.ior.value = material.ior; // also part of uniforms common
  16650. if ( material.sheen > 0 ) {
  16651. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16652. uniforms.sheenRoughness.value = material.sheenRoughness;
  16653. if ( material.sheenColorMap ) {
  16654. uniforms.sheenColorMap.value = material.sheenColorMap;
  16655. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16656. }
  16657. if ( material.sheenRoughnessMap ) {
  16658. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16659. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16660. }
  16661. }
  16662. if ( material.clearcoat > 0 ) {
  16663. uniforms.clearcoat.value = material.clearcoat;
  16664. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16665. if ( material.clearcoatMap ) {
  16666. uniforms.clearcoatMap.value = material.clearcoatMap;
  16667. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16668. }
  16669. if ( material.clearcoatRoughnessMap ) {
  16670. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16671. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16672. }
  16673. if ( material.clearcoatNormalMap ) {
  16674. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16675. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16676. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16677. if ( material.side === BackSide ) {
  16678. uniforms.clearcoatNormalScale.value.negate();
  16679. }
  16680. }
  16681. }
  16682. if ( material.iridescence > 0 ) {
  16683. uniforms.iridescence.value = material.iridescence;
  16684. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16685. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16686. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16687. if ( material.iridescenceMap ) {
  16688. uniforms.iridescenceMap.value = material.iridescenceMap;
  16689. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16690. }
  16691. if ( material.iridescenceThicknessMap ) {
  16692. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16693. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16694. }
  16695. }
  16696. if ( material.transmission > 0 ) {
  16697. uniforms.transmission.value = material.transmission;
  16698. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16699. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16700. if ( material.transmissionMap ) {
  16701. uniforms.transmissionMap.value = material.transmissionMap;
  16702. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16703. }
  16704. uniforms.thickness.value = material.thickness;
  16705. if ( material.thicknessMap ) {
  16706. uniforms.thicknessMap.value = material.thicknessMap;
  16707. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16708. }
  16709. uniforms.attenuationDistance.value = material.attenuationDistance;
  16710. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16711. }
  16712. if ( material.anisotropy > 0 ) {
  16713. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16714. if ( material.anisotropyMap ) {
  16715. uniforms.anisotropyMap.value = material.anisotropyMap;
  16716. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16717. }
  16718. }
  16719. uniforms.specularIntensity.value = material.specularIntensity;
  16720. uniforms.specularColor.value.copy( material.specularColor );
  16721. if ( material.specularColorMap ) {
  16722. uniforms.specularColorMap.value = material.specularColorMap;
  16723. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16724. }
  16725. if ( material.specularIntensityMap ) {
  16726. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16727. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16728. }
  16729. }
  16730. function refreshUniformsMatcap( uniforms, material ) {
  16731. if ( material.matcap ) {
  16732. uniforms.matcap.value = material.matcap;
  16733. }
  16734. }
  16735. function refreshUniformsDistance( uniforms, material ) {
  16736. const light = properties.get( material ).light;
  16737. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16738. uniforms.nearDistance.value = light.shadow.camera.near;
  16739. uniforms.farDistance.value = light.shadow.camera.far;
  16740. }
  16741. return {
  16742. refreshFogUniforms: refreshFogUniforms,
  16743. refreshMaterialUniforms: refreshMaterialUniforms
  16744. };
  16745. }
  16746. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16747. let buffers = {};
  16748. let updateList = {};
  16749. let allocatedBindingPoints = [];
  16750. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  16751. function bind( uniformsGroup, program ) {
  16752. const webglProgram = program.program;
  16753. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16754. }
  16755. function update( uniformsGroup, program ) {
  16756. let buffer = buffers[ uniformsGroup.id ];
  16757. if ( buffer === undefined ) {
  16758. prepareUniformsGroup( uniformsGroup );
  16759. buffer = createBuffer( uniformsGroup );
  16760. buffers[ uniformsGroup.id ] = buffer;
  16761. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16762. }
  16763. // ensure to update the binding points/block indices mapping for this program
  16764. const webglProgram = program.program;
  16765. state.updateUBOMapping( uniformsGroup, webglProgram );
  16766. // update UBO once per frame
  16767. const frame = info.render.frame;
  16768. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16769. updateBufferData( uniformsGroup );
  16770. updateList[ uniformsGroup.id ] = frame;
  16771. }
  16772. }
  16773. function createBuffer( uniformsGroup ) {
  16774. // the setup of an UBO is independent of a particular shader program but global
  16775. const bindingPointIndex = allocateBindingPointIndex();
  16776. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16777. const buffer = gl.createBuffer();
  16778. const size = uniformsGroup.__size;
  16779. const usage = uniformsGroup.usage;
  16780. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16781. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16782. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16783. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16784. return buffer;
  16785. }
  16786. function allocateBindingPointIndex() {
  16787. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16788. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16789. allocatedBindingPoints.push( i );
  16790. return i;
  16791. }
  16792. }
  16793. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16794. return 0;
  16795. }
  16796. function updateBufferData( uniformsGroup ) {
  16797. const buffer = buffers[ uniformsGroup.id ];
  16798. const uniforms = uniformsGroup.uniforms;
  16799. const cache = uniformsGroup.__cache;
  16800. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16801. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16802. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16803. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16804. const uniform = uniformArray[ j ];
  16805. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  16806. const offset = uniform.__offset;
  16807. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16808. let arrayOffset = 0;
  16809. for ( let k = 0; k < values.length; k ++ ) {
  16810. const value = values[ k ];
  16811. const info = getUniformSize( value );
  16812. // TODO add integer and struct support
  16813. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16814. uniform.__data[ 0 ] = value;
  16815. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16816. } else if ( value.isMatrix3 ) {
  16817. // manually converting 3x3 to 3x4
  16818. uniform.__data[ 0 ] = value.elements[ 0 ];
  16819. uniform.__data[ 1 ] = value.elements[ 1 ];
  16820. uniform.__data[ 2 ] = value.elements[ 2 ];
  16821. uniform.__data[ 3 ] = 0;
  16822. uniform.__data[ 4 ] = value.elements[ 3 ];
  16823. uniform.__data[ 5 ] = value.elements[ 4 ];
  16824. uniform.__data[ 6 ] = value.elements[ 5 ];
  16825. uniform.__data[ 7 ] = 0;
  16826. uniform.__data[ 8 ] = value.elements[ 6 ];
  16827. uniform.__data[ 9 ] = value.elements[ 7 ];
  16828. uniform.__data[ 10 ] = value.elements[ 8 ];
  16829. uniform.__data[ 11 ] = 0;
  16830. } else {
  16831. value.toArray( uniform.__data, arrayOffset );
  16832. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16833. }
  16834. }
  16835. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16836. }
  16837. }
  16838. }
  16839. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16840. }
  16841. function hasUniformChanged( uniform, index, indexArray, cache ) {
  16842. const value = uniform.value;
  16843. const indexString = index + '_' + indexArray;
  16844. if ( cache[ indexString ] === undefined ) {
  16845. // cache entry does not exist so far
  16846. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16847. cache[ indexString ] = value;
  16848. } else {
  16849. cache[ indexString ] = value.clone();
  16850. }
  16851. return true;
  16852. } else {
  16853. const cachedObject = cache[ indexString ];
  16854. // compare current value with cached entry
  16855. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16856. if ( cachedObject !== value ) {
  16857. cache[ indexString ] = value;
  16858. return true;
  16859. }
  16860. } else {
  16861. if ( cachedObject.equals( value ) === false ) {
  16862. cachedObject.copy( value );
  16863. return true;
  16864. }
  16865. }
  16866. }
  16867. return false;
  16868. }
  16869. function prepareUniformsGroup( uniformsGroup ) {
  16870. // determine total buffer size according to the STD140 layout
  16871. // Hint: STD140 is the only supported layout in WebGL 2
  16872. const uniforms = uniformsGroup.uniforms;
  16873. let offset = 0; // global buffer offset in bytes
  16874. const chunkSize = 16; // size of a chunk in bytes
  16875. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16876. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16877. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16878. const uniform = uniformArray[ j ];
  16879. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16880. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  16881. const value = values[ k ];
  16882. const info = getUniformSize( value );
  16883. // Calculate the chunk offset
  16884. const chunkOffsetUniform = offset % chunkSize;
  16885. // Check for chunk overflow
  16886. if ( chunkOffsetUniform !== 0 && ( chunkSize - chunkOffsetUniform ) < info.boundary ) {
  16887. // Add padding and adjust offset
  16888. offset += ( chunkSize - chunkOffsetUniform );
  16889. }
  16890. // the following two properties will be used for partial buffer updates
  16891. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  16892. uniform.__offset = offset;
  16893. // Update the global offset
  16894. offset += info.storage;
  16895. }
  16896. }
  16897. }
  16898. // ensure correct final padding
  16899. const chunkOffset = offset % chunkSize;
  16900. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16901. //
  16902. uniformsGroup.__size = offset;
  16903. uniformsGroup.__cache = {};
  16904. return this;
  16905. }
  16906. function getUniformSize( value ) {
  16907. const info = {
  16908. boundary: 0, // bytes
  16909. storage: 0 // bytes
  16910. };
  16911. // determine sizes according to STD140
  16912. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16913. // float/int/bool
  16914. info.boundary = 4;
  16915. info.storage = 4;
  16916. } else if ( value.isVector2 ) {
  16917. // vec2
  16918. info.boundary = 8;
  16919. info.storage = 8;
  16920. } else if ( value.isVector3 || value.isColor ) {
  16921. // vec3
  16922. info.boundary = 16;
  16923. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16924. } else if ( value.isVector4 ) {
  16925. // vec4
  16926. info.boundary = 16;
  16927. info.storage = 16;
  16928. } else if ( value.isMatrix3 ) {
  16929. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16930. info.boundary = 48;
  16931. info.storage = 48;
  16932. } else if ( value.isMatrix4 ) {
  16933. // mat4
  16934. info.boundary = 64;
  16935. info.storage = 64;
  16936. } else if ( value.isTexture ) {
  16937. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16938. } else {
  16939. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16940. }
  16941. return info;
  16942. }
  16943. function onUniformsGroupsDispose( event ) {
  16944. const uniformsGroup = event.target;
  16945. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16946. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16947. allocatedBindingPoints.splice( index, 1 );
  16948. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16949. delete buffers[ uniformsGroup.id ];
  16950. delete updateList[ uniformsGroup.id ];
  16951. }
  16952. function dispose() {
  16953. for ( const id in buffers ) {
  16954. gl.deleteBuffer( buffers[ id ] );
  16955. }
  16956. allocatedBindingPoints = [];
  16957. buffers = {};
  16958. updateList = {};
  16959. }
  16960. return {
  16961. bind: bind,
  16962. update: update,
  16963. dispose: dispose
  16964. };
  16965. }
  16966. class WebGLRenderer {
  16967. constructor( parameters = {} ) {
  16968. const {
  16969. canvas = createCanvasElement(),
  16970. context = null,
  16971. depth = true,
  16972. stencil = true,
  16973. alpha = false,
  16974. antialias = false,
  16975. premultipliedAlpha = true,
  16976. preserveDrawingBuffer = false,
  16977. powerPreference = 'default',
  16978. failIfMajorPerformanceCaveat = false,
  16979. } = parameters;
  16980. this.isWebGLRenderer = true;
  16981. let _alpha;
  16982. if ( context !== null ) {
  16983. _alpha = context.getContextAttributes().alpha;
  16984. } else {
  16985. _alpha = alpha;
  16986. }
  16987. const uintClearColor = new Uint32Array( 4 );
  16988. const intClearColor = new Int32Array( 4 );
  16989. let currentRenderList = null;
  16990. let currentRenderState = null;
  16991. // render() can be called from within a callback triggered by another render.
  16992. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16993. const renderListStack = [];
  16994. const renderStateStack = [];
  16995. // public properties
  16996. this.domElement = canvas;
  16997. // Debug configuration container
  16998. this.debug = {
  16999. /**
  17000. * Enables error checking and reporting when shader programs are being compiled
  17001. * @type {boolean}
  17002. */
  17003. checkShaderErrors: true,
  17004. /**
  17005. * Callback for custom error reporting.
  17006. * @type {?Function}
  17007. */
  17008. onShaderError: null
  17009. };
  17010. // clearing
  17011. this.autoClear = true;
  17012. this.autoClearColor = true;
  17013. this.autoClearDepth = true;
  17014. this.autoClearStencil = true;
  17015. // scene graph
  17016. this.sortObjects = true;
  17017. // user-defined clipping
  17018. this.clippingPlanes = [];
  17019. this.localClippingEnabled = false;
  17020. // physically based shading
  17021. this._outputColorSpace = SRGBColorSpace;
  17022. // physical lights
  17023. this._useLegacyLights = false;
  17024. // tone mapping
  17025. this.toneMapping = NoToneMapping;
  17026. this.toneMappingExposure = 1.0;
  17027. // internal properties
  17028. const _this = this;
  17029. let _isContextLost = false;
  17030. // internal state cache
  17031. let _currentActiveCubeFace = 0;
  17032. let _currentActiveMipmapLevel = 0;
  17033. let _currentRenderTarget = null;
  17034. let _currentMaterialId = - 1;
  17035. let _currentCamera = null;
  17036. const _currentViewport = new Vector4();
  17037. const _currentScissor = new Vector4();
  17038. let _currentScissorTest = null;
  17039. const _currentClearColor = new Color( 0x000000 );
  17040. let _currentClearAlpha = 0;
  17041. //
  17042. let _width = canvas.width;
  17043. let _height = canvas.height;
  17044. let _pixelRatio = 1;
  17045. let _opaqueSort = null;
  17046. let _transparentSort = null;
  17047. const _viewport = new Vector4( 0, 0, _width, _height );
  17048. const _scissor = new Vector4( 0, 0, _width, _height );
  17049. let _scissorTest = false;
  17050. // frustum
  17051. const _frustum = new Frustum();
  17052. // clipping
  17053. let _clippingEnabled = false;
  17054. let _localClippingEnabled = false;
  17055. // transmission
  17056. let _transmissionRenderTarget = null;
  17057. // camera matrices cache
  17058. const _projScreenMatrix = new Matrix4();
  17059. const _vector2 = new Vector2();
  17060. const _vector3 = new Vector3();
  17061. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  17062. function getTargetPixelRatio() {
  17063. return _currentRenderTarget === null ? _pixelRatio : 1;
  17064. }
  17065. // initialize
  17066. let _gl = context;
  17067. function getContext( contextNames, contextAttributes ) {
  17068. for ( let i = 0; i < contextNames.length; i ++ ) {
  17069. const contextName = contextNames[ i ];
  17070. const context = canvas.getContext( contextName, contextAttributes );
  17071. if ( context !== null ) return context;
  17072. }
  17073. return null;
  17074. }
  17075. try {
  17076. const contextAttributes = {
  17077. alpha: true,
  17078. depth,
  17079. stencil,
  17080. antialias,
  17081. premultipliedAlpha,
  17082. preserveDrawingBuffer,
  17083. powerPreference,
  17084. failIfMajorPerformanceCaveat,
  17085. };
  17086. // OffscreenCanvas does not have setAttribute, see #22811
  17087. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  17088. // event listeners must be registered before WebGL context is created, see #12753
  17089. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17090. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17091. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17092. if ( _gl === null ) {
  17093. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  17094. if ( _this.isWebGL1Renderer === true ) {
  17095. contextNames.shift();
  17096. }
  17097. _gl = getContext( contextNames, contextAttributes );
  17098. if ( _gl === null ) {
  17099. if ( getContext( contextNames ) ) {
  17100. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17101. } else {
  17102. throw new Error( 'Error creating WebGL context.' );
  17103. }
  17104. }
  17105. }
  17106. if ( typeof WebGLRenderingContext !== 'undefined' && _gl instanceof WebGLRenderingContext ) { // @deprecated, r153
  17107. console.warn( 'THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163.' );
  17108. }
  17109. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  17110. if ( _gl.getShaderPrecisionFormat === undefined ) {
  17111. _gl.getShaderPrecisionFormat = function () {
  17112. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  17113. };
  17114. }
  17115. } catch ( error ) {
  17116. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17117. throw error;
  17118. }
  17119. let extensions, capabilities, state, info;
  17120. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  17121. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  17122. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17123. let utils, bindingStates, uniformsGroups;
  17124. function initGLContext() {
  17125. extensions = new WebGLExtensions( _gl );
  17126. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  17127. extensions.init( capabilities );
  17128. utils = new WebGLUtils( _gl, extensions, capabilities );
  17129. state = new WebGLState( _gl, extensions, capabilities );
  17130. info = new WebGLInfo( _gl );
  17131. properties = new WebGLProperties();
  17132. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  17133. cubemaps = new WebGLCubeMaps( _this );
  17134. cubeuvmaps = new WebGLCubeUVMaps( _this );
  17135. attributes = new WebGLAttributes( _gl, capabilities );
  17136. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  17137. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  17138. objects = new WebGLObjects( _gl, geometries, attributes, info );
  17139. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  17140. clipping = new WebGLClipping( properties );
  17141. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  17142. materials = new WebGLMaterials( _this, properties );
  17143. renderLists = new WebGLRenderLists();
  17144. renderStates = new WebGLRenderStates( extensions, capabilities );
  17145. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  17146. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  17147. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  17148. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  17149. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  17150. info.programs = programCache.programs;
  17151. _this.capabilities = capabilities;
  17152. _this.extensions = extensions;
  17153. _this.properties = properties;
  17154. _this.renderLists = renderLists;
  17155. _this.shadowMap = shadowMap;
  17156. _this.state = state;
  17157. _this.info = info;
  17158. }
  17159. initGLContext();
  17160. // xr
  17161. const xr = new WebXRManager( _this, _gl );
  17162. this.xr = xr;
  17163. // API
  17164. this.getContext = function () {
  17165. return _gl;
  17166. };
  17167. this.getContextAttributes = function () {
  17168. return _gl.getContextAttributes();
  17169. };
  17170. this.forceContextLoss = function () {
  17171. const extension = extensions.get( 'WEBGL_lose_context' );
  17172. if ( extension ) extension.loseContext();
  17173. };
  17174. this.forceContextRestore = function () {
  17175. const extension = extensions.get( 'WEBGL_lose_context' );
  17176. if ( extension ) extension.restoreContext();
  17177. };
  17178. this.getPixelRatio = function () {
  17179. return _pixelRatio;
  17180. };
  17181. this.setPixelRatio = function ( value ) {
  17182. if ( value === undefined ) return;
  17183. _pixelRatio = value;
  17184. this.setSize( _width, _height, false );
  17185. };
  17186. this.getSize = function ( target ) {
  17187. return target.set( _width, _height );
  17188. };
  17189. this.setSize = function ( width, height, updateStyle = true ) {
  17190. if ( xr.isPresenting ) {
  17191. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17192. return;
  17193. }
  17194. _width = width;
  17195. _height = height;
  17196. canvas.width = Math.floor( width * _pixelRatio );
  17197. canvas.height = Math.floor( height * _pixelRatio );
  17198. if ( updateStyle === true ) {
  17199. canvas.style.width = width + 'px';
  17200. canvas.style.height = height + 'px';
  17201. }
  17202. this.setViewport( 0, 0, width, height );
  17203. };
  17204. this.getDrawingBufferSize = function ( target ) {
  17205. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  17206. };
  17207. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17208. _width = width;
  17209. _height = height;
  17210. _pixelRatio = pixelRatio;
  17211. canvas.width = Math.floor( width * pixelRatio );
  17212. canvas.height = Math.floor( height * pixelRatio );
  17213. this.setViewport( 0, 0, width, height );
  17214. };
  17215. this.getCurrentViewport = function ( target ) {
  17216. return target.copy( _currentViewport );
  17217. };
  17218. this.getViewport = function ( target ) {
  17219. return target.copy( _viewport );
  17220. };
  17221. this.setViewport = function ( x, y, width, height ) {
  17222. if ( x.isVector4 ) {
  17223. _viewport.set( x.x, x.y, x.z, x.w );
  17224. } else {
  17225. _viewport.set( x, y, width, height );
  17226. }
  17227. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  17228. };
  17229. this.getScissor = function ( target ) {
  17230. return target.copy( _scissor );
  17231. };
  17232. this.setScissor = function ( x, y, width, height ) {
  17233. if ( x.isVector4 ) {
  17234. _scissor.set( x.x, x.y, x.z, x.w );
  17235. } else {
  17236. _scissor.set( x, y, width, height );
  17237. }
  17238. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  17239. };
  17240. this.getScissorTest = function () {
  17241. return _scissorTest;
  17242. };
  17243. this.setScissorTest = function ( boolean ) {
  17244. state.setScissorTest( _scissorTest = boolean );
  17245. };
  17246. this.setOpaqueSort = function ( method ) {
  17247. _opaqueSort = method;
  17248. };
  17249. this.setTransparentSort = function ( method ) {
  17250. _transparentSort = method;
  17251. };
  17252. // Clearing
  17253. this.getClearColor = function ( target ) {
  17254. return target.copy( background.getClearColor() );
  17255. };
  17256. this.setClearColor = function () {
  17257. background.setClearColor.apply( background, arguments );
  17258. };
  17259. this.getClearAlpha = function () {
  17260. return background.getClearAlpha();
  17261. };
  17262. this.setClearAlpha = function () {
  17263. background.setClearAlpha.apply( background, arguments );
  17264. };
  17265. this.clear = function ( color = true, depth = true, stencil = true ) {
  17266. let bits = 0;
  17267. if ( color ) {
  17268. // check if we're trying to clear an integer target
  17269. let isIntegerFormat = false;
  17270. if ( _currentRenderTarget !== null ) {
  17271. const targetFormat = _currentRenderTarget.texture.format;
  17272. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17273. targetFormat === RGIntegerFormat ||
  17274. targetFormat === RedIntegerFormat;
  17275. }
  17276. // use the appropriate clear functions to clear the target if it's a signed
  17277. // or unsigned integer target
  17278. if ( isIntegerFormat ) {
  17279. const targetType = _currentRenderTarget.texture.type;
  17280. const isUnsignedType = targetType === UnsignedByteType ||
  17281. targetType === UnsignedIntType ||
  17282. targetType === UnsignedShortType ||
  17283. targetType === UnsignedInt248Type ||
  17284. targetType === UnsignedShort4444Type ||
  17285. targetType === UnsignedShort5551Type;
  17286. const clearColor = background.getClearColor();
  17287. const a = background.getClearAlpha();
  17288. const r = clearColor.r;
  17289. const g = clearColor.g;
  17290. const b = clearColor.b;
  17291. if ( isUnsignedType ) {
  17292. uintClearColor[ 0 ] = r;
  17293. uintClearColor[ 1 ] = g;
  17294. uintClearColor[ 2 ] = b;
  17295. uintClearColor[ 3 ] = a;
  17296. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17297. } else {
  17298. intClearColor[ 0 ] = r;
  17299. intClearColor[ 1 ] = g;
  17300. intClearColor[ 2 ] = b;
  17301. intClearColor[ 3 ] = a;
  17302. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17303. }
  17304. } else {
  17305. bits |= _gl.COLOR_BUFFER_BIT;
  17306. }
  17307. }
  17308. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17309. if ( stencil ) {
  17310. bits |= _gl.STENCIL_BUFFER_BIT;
  17311. this.state.buffers.stencil.setMask( 0xffffffff );
  17312. }
  17313. _gl.clear( bits );
  17314. };
  17315. this.clearColor = function () {
  17316. this.clear( true, false, false );
  17317. };
  17318. this.clearDepth = function () {
  17319. this.clear( false, true, false );
  17320. };
  17321. this.clearStencil = function () {
  17322. this.clear( false, false, true );
  17323. };
  17324. //
  17325. this.dispose = function () {
  17326. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17327. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17328. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17329. renderLists.dispose();
  17330. renderStates.dispose();
  17331. properties.dispose();
  17332. cubemaps.dispose();
  17333. cubeuvmaps.dispose();
  17334. objects.dispose();
  17335. bindingStates.dispose();
  17336. uniformsGroups.dispose();
  17337. programCache.dispose();
  17338. xr.dispose();
  17339. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17340. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17341. if ( _transmissionRenderTarget ) {
  17342. _transmissionRenderTarget.dispose();
  17343. _transmissionRenderTarget = null;
  17344. }
  17345. animation.stop();
  17346. };
  17347. // Events
  17348. function onContextLost( event ) {
  17349. event.preventDefault();
  17350. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17351. _isContextLost = true;
  17352. }
  17353. function onContextRestore( /* event */ ) {
  17354. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17355. _isContextLost = false;
  17356. const infoAutoReset = info.autoReset;
  17357. const shadowMapEnabled = shadowMap.enabled;
  17358. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17359. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17360. const shadowMapType = shadowMap.type;
  17361. initGLContext();
  17362. info.autoReset = infoAutoReset;
  17363. shadowMap.enabled = shadowMapEnabled;
  17364. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17365. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17366. shadowMap.type = shadowMapType;
  17367. }
  17368. function onContextCreationError( event ) {
  17369. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17370. }
  17371. function onMaterialDispose( event ) {
  17372. const material = event.target;
  17373. material.removeEventListener( 'dispose', onMaterialDispose );
  17374. deallocateMaterial( material );
  17375. }
  17376. // Buffer deallocation
  17377. function deallocateMaterial( material ) {
  17378. releaseMaterialProgramReferences( material );
  17379. properties.remove( material );
  17380. }
  17381. function releaseMaterialProgramReferences( material ) {
  17382. const programs = properties.get( material ).programs;
  17383. if ( programs !== undefined ) {
  17384. programs.forEach( function ( program ) {
  17385. programCache.releaseProgram( program );
  17386. } );
  17387. if ( material.isShaderMaterial ) {
  17388. programCache.releaseShaderCache( material );
  17389. }
  17390. }
  17391. }
  17392. // Buffer rendering
  17393. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17394. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17395. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17396. const program = setProgram( camera, scene, geometry, material, object );
  17397. state.setMaterial( material, frontFaceCW );
  17398. //
  17399. let index = geometry.index;
  17400. let rangeFactor = 1;
  17401. if ( material.wireframe === true ) {
  17402. index = geometries.getWireframeAttribute( geometry );
  17403. if ( index === undefined ) return;
  17404. rangeFactor = 2;
  17405. }
  17406. //
  17407. const drawRange = geometry.drawRange;
  17408. const position = geometry.attributes.position;
  17409. let drawStart = drawRange.start * rangeFactor;
  17410. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17411. if ( group !== null ) {
  17412. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17413. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17414. }
  17415. if ( index !== null ) {
  17416. drawStart = Math.max( drawStart, 0 );
  17417. drawEnd = Math.min( drawEnd, index.count );
  17418. } else if ( position !== undefined && position !== null ) {
  17419. drawStart = Math.max( drawStart, 0 );
  17420. drawEnd = Math.min( drawEnd, position.count );
  17421. }
  17422. const drawCount = drawEnd - drawStart;
  17423. if ( drawCount < 0 || drawCount === Infinity ) return;
  17424. //
  17425. bindingStates.setup( object, material, program, geometry, index );
  17426. let attribute;
  17427. let renderer = bufferRenderer;
  17428. if ( index !== null ) {
  17429. attribute = attributes.get( index );
  17430. renderer = indexedBufferRenderer;
  17431. renderer.setIndex( attribute );
  17432. }
  17433. //
  17434. if ( object.isMesh ) {
  17435. if ( material.wireframe === true ) {
  17436. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17437. renderer.setMode( _gl.LINES );
  17438. } else {
  17439. renderer.setMode( _gl.TRIANGLES );
  17440. }
  17441. } else if ( object.isLine ) {
  17442. let lineWidth = material.linewidth;
  17443. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17444. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17445. if ( object.isLineSegments ) {
  17446. renderer.setMode( _gl.LINES );
  17447. } else if ( object.isLineLoop ) {
  17448. renderer.setMode( _gl.LINE_LOOP );
  17449. } else {
  17450. renderer.setMode( _gl.LINE_STRIP );
  17451. }
  17452. } else if ( object.isPoints ) {
  17453. renderer.setMode( _gl.POINTS );
  17454. } else if ( object.isSprite ) {
  17455. renderer.setMode( _gl.TRIANGLES );
  17456. }
  17457. if ( object.isBatchedMesh ) {
  17458. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  17459. } else if ( object.isInstancedMesh ) {
  17460. renderer.renderInstances( drawStart, drawCount, object.count );
  17461. } else if ( geometry.isInstancedBufferGeometry ) {
  17462. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17463. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17464. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17465. } else {
  17466. renderer.render( drawStart, drawCount );
  17467. }
  17468. };
  17469. // Compile
  17470. function prepareMaterial( material, scene, object ) {
  17471. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17472. material.side = BackSide;
  17473. material.needsUpdate = true;
  17474. getProgram( material, scene, object );
  17475. material.side = FrontSide;
  17476. material.needsUpdate = true;
  17477. getProgram( material, scene, object );
  17478. material.side = DoubleSide;
  17479. } else {
  17480. getProgram( material, scene, object );
  17481. }
  17482. }
  17483. this.compile = function ( scene, camera, targetScene = null ) {
  17484. if ( targetScene === null ) targetScene = scene;
  17485. currentRenderState = renderStates.get( targetScene );
  17486. currentRenderState.init();
  17487. renderStateStack.push( currentRenderState );
  17488. // gather lights from both the target scene and the new object that will be added to the scene.
  17489. targetScene.traverseVisible( function ( object ) {
  17490. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17491. currentRenderState.pushLight( object );
  17492. if ( object.castShadow ) {
  17493. currentRenderState.pushShadow( object );
  17494. }
  17495. }
  17496. } );
  17497. if ( scene !== targetScene ) {
  17498. scene.traverseVisible( function ( object ) {
  17499. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17500. currentRenderState.pushLight( object );
  17501. if ( object.castShadow ) {
  17502. currentRenderState.pushShadow( object );
  17503. }
  17504. }
  17505. } );
  17506. }
  17507. currentRenderState.setupLights( _this._useLegacyLights );
  17508. // Only initialize materials in the new scene, not the targetScene.
  17509. const materials = new Set();
  17510. scene.traverse( function ( object ) {
  17511. const material = object.material;
  17512. if ( material ) {
  17513. if ( Array.isArray( material ) ) {
  17514. for ( let i = 0; i < material.length; i ++ ) {
  17515. const material2 = material[ i ];
  17516. prepareMaterial( material2, targetScene, object );
  17517. materials.add( material2 );
  17518. }
  17519. } else {
  17520. prepareMaterial( material, targetScene, object );
  17521. materials.add( material );
  17522. }
  17523. }
  17524. } );
  17525. renderStateStack.pop();
  17526. currentRenderState = null;
  17527. return materials;
  17528. };
  17529. // compileAsync
  17530. this.compileAsync = function ( scene, camera, targetScene = null ) {
  17531. const materials = this.compile( scene, camera, targetScene );
  17532. // Wait for all the materials in the new object to indicate that they're
  17533. // ready to be used before resolving the promise.
  17534. return new Promise( ( resolve ) => {
  17535. function checkMaterialsReady() {
  17536. materials.forEach( function ( material ) {
  17537. const materialProperties = properties.get( material );
  17538. const program = materialProperties.currentProgram;
  17539. if ( program.isReady() ) {
  17540. // remove any programs that report they're ready to use from the list
  17541. materials.delete( material );
  17542. }
  17543. } );
  17544. // once the list of compiling materials is empty, call the callback
  17545. if ( materials.size === 0 ) {
  17546. resolve( scene );
  17547. return;
  17548. }
  17549. // if some materials are still not ready, wait a bit and check again
  17550. setTimeout( checkMaterialsReady, 10 );
  17551. }
  17552. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  17553. // If we can check the compilation status of the materials without
  17554. // blocking then do so right away.
  17555. checkMaterialsReady();
  17556. } else {
  17557. // Otherwise start by waiting a bit to give the materials we just
  17558. // initialized a chance to finish.
  17559. setTimeout( checkMaterialsReady, 10 );
  17560. }
  17561. } );
  17562. };
  17563. // Animation Loop
  17564. let onAnimationFrameCallback = null;
  17565. function onAnimationFrame( time ) {
  17566. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17567. }
  17568. function onXRSessionStart() {
  17569. animation.stop();
  17570. }
  17571. function onXRSessionEnd() {
  17572. animation.start();
  17573. }
  17574. const animation = new WebGLAnimation();
  17575. animation.setAnimationLoop( onAnimationFrame );
  17576. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17577. this.setAnimationLoop = function ( callback ) {
  17578. onAnimationFrameCallback = callback;
  17579. xr.setAnimationLoop( callback );
  17580. ( callback === null ) ? animation.stop() : animation.start();
  17581. };
  17582. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17583. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17584. // Rendering
  17585. this.render = function ( scene, camera ) {
  17586. if ( camera !== undefined && camera.isCamera !== true ) {
  17587. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17588. return;
  17589. }
  17590. if ( _isContextLost === true ) return;
  17591. // update scene graph
  17592. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17593. // update camera matrices and frustum
  17594. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17595. if ( xr.enabled === true && xr.isPresenting === true ) {
  17596. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17597. camera = xr.getCamera(); // use XR camera for rendering
  17598. }
  17599. //
  17600. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17601. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17602. currentRenderState.init();
  17603. renderStateStack.push( currentRenderState );
  17604. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17605. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17606. _localClippingEnabled = this.localClippingEnabled;
  17607. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17608. currentRenderList = renderLists.get( scene, renderListStack.length );
  17609. currentRenderList.init();
  17610. renderListStack.push( currentRenderList );
  17611. projectObject( scene, camera, 0, _this.sortObjects );
  17612. currentRenderList.finish();
  17613. if ( _this.sortObjects === true ) {
  17614. currentRenderList.sort( _opaqueSort, _transparentSort );
  17615. }
  17616. //
  17617. this.info.render.frame ++;
  17618. if ( _clippingEnabled === true ) clipping.beginShadows();
  17619. const shadowsArray = currentRenderState.state.shadowsArray;
  17620. shadowMap.render( shadowsArray, scene, camera );
  17621. if ( _clippingEnabled === true ) clipping.endShadows();
  17622. //
  17623. if ( this.info.autoReset === true ) this.info.reset();
  17624. //
  17625. background.render( currentRenderList, scene );
  17626. // render scene
  17627. currentRenderState.setupLights( _this._useLegacyLights );
  17628. if ( camera.isArrayCamera ) {
  17629. const cameras = camera.cameras;
  17630. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17631. const camera2 = cameras[ i ];
  17632. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17633. }
  17634. } else {
  17635. renderScene( currentRenderList, scene, camera );
  17636. }
  17637. //
  17638. if ( _currentRenderTarget !== null ) {
  17639. // resolve multisample renderbuffers to a single-sample texture if necessary
  17640. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17641. // Generate mipmap if we're using any kind of mipmap filtering
  17642. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17643. }
  17644. //
  17645. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17646. // _gl.finish();
  17647. bindingStates.resetDefaultState();
  17648. _currentMaterialId = - 1;
  17649. _currentCamera = null;
  17650. renderStateStack.pop();
  17651. if ( renderStateStack.length > 0 ) {
  17652. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17653. } else {
  17654. currentRenderState = null;
  17655. }
  17656. renderListStack.pop();
  17657. if ( renderListStack.length > 0 ) {
  17658. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17659. } else {
  17660. currentRenderList = null;
  17661. }
  17662. };
  17663. function projectObject( object, camera, groupOrder, sortObjects ) {
  17664. if ( object.visible === false ) return;
  17665. const visible = object.layers.test( camera.layers );
  17666. if ( visible ) {
  17667. if ( object.isGroup ) {
  17668. groupOrder = object.renderOrder;
  17669. } else if ( object.isLOD ) {
  17670. if ( object.autoUpdate === true ) object.update( camera );
  17671. } else if ( object.isLight ) {
  17672. currentRenderState.pushLight( object );
  17673. if ( object.castShadow ) {
  17674. currentRenderState.pushShadow( object );
  17675. }
  17676. } else if ( object.isSprite ) {
  17677. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17678. if ( sortObjects ) {
  17679. _vector3.setFromMatrixPosition( object.matrixWorld )
  17680. .applyMatrix4( _projScreenMatrix );
  17681. }
  17682. const geometry = objects.update( object );
  17683. const material = object.material;
  17684. if ( material.visible ) {
  17685. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17686. }
  17687. }
  17688. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17689. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17690. const geometry = objects.update( object );
  17691. const material = object.material;
  17692. if ( sortObjects ) {
  17693. if ( object.boundingSphere !== undefined ) {
  17694. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17695. _vector3.copy( object.boundingSphere.center );
  17696. } else {
  17697. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17698. _vector3.copy( geometry.boundingSphere.center );
  17699. }
  17700. _vector3
  17701. .applyMatrix4( object.matrixWorld )
  17702. .applyMatrix4( _projScreenMatrix );
  17703. }
  17704. if ( Array.isArray( material ) ) {
  17705. const groups = geometry.groups;
  17706. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17707. const group = groups[ i ];
  17708. const groupMaterial = material[ group.materialIndex ];
  17709. if ( groupMaterial && groupMaterial.visible ) {
  17710. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17711. }
  17712. }
  17713. } else if ( material.visible ) {
  17714. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17715. }
  17716. }
  17717. }
  17718. }
  17719. const children = object.children;
  17720. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17721. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17722. }
  17723. }
  17724. function renderScene( currentRenderList, scene, camera, viewport ) {
  17725. const opaqueObjects = currentRenderList.opaque;
  17726. const transmissiveObjects = currentRenderList.transmissive;
  17727. const transparentObjects = currentRenderList.transparent;
  17728. currentRenderState.setupLightsView( camera );
  17729. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17730. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17731. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17732. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17733. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17734. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17735. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17736. state.buffers.depth.setTest( true );
  17737. state.buffers.depth.setMask( true );
  17738. state.buffers.color.setMask( true );
  17739. state.setPolygonOffset( false );
  17740. }
  17741. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17742. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17743. if ( overrideMaterial !== null ) {
  17744. return;
  17745. }
  17746. const isWebGL2 = capabilities.isWebGL2;
  17747. if ( _transmissionRenderTarget === null ) {
  17748. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  17749. generateMipmaps: true,
  17750. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17751. minFilter: LinearMipmapLinearFilter,
  17752. samples: ( isWebGL2 ) ? 4 : 0
  17753. } );
  17754. // debug
  17755. /*
  17756. const geometry = new PlaneGeometry();
  17757. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17758. const mesh = new Mesh( geometry, material );
  17759. scene.add( mesh );
  17760. */
  17761. }
  17762. _this.getDrawingBufferSize( _vector2 );
  17763. if ( isWebGL2 ) {
  17764. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  17765. } else {
  17766. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  17767. }
  17768. //
  17769. const currentRenderTarget = _this.getRenderTarget();
  17770. _this.setRenderTarget( _transmissionRenderTarget );
  17771. _this.getClearColor( _currentClearColor );
  17772. _currentClearAlpha = _this.getClearAlpha();
  17773. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17774. _this.clear();
  17775. // Turn off the features which can affect the frag color for opaque objects pass.
  17776. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17777. const currentToneMapping = _this.toneMapping;
  17778. _this.toneMapping = NoToneMapping;
  17779. renderObjects( opaqueObjects, scene, camera );
  17780. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17781. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17782. let renderTargetNeedsUpdate = false;
  17783. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17784. const renderItem = transmissiveObjects[ i ];
  17785. const object = renderItem.object;
  17786. const geometry = renderItem.geometry;
  17787. const material = renderItem.material;
  17788. const group = renderItem.group;
  17789. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17790. const currentSide = material.side;
  17791. material.side = BackSide;
  17792. material.needsUpdate = true;
  17793. renderObject( object, scene, camera, geometry, material, group );
  17794. material.side = currentSide;
  17795. material.needsUpdate = true;
  17796. renderTargetNeedsUpdate = true;
  17797. }
  17798. }
  17799. if ( renderTargetNeedsUpdate === true ) {
  17800. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17801. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17802. }
  17803. _this.setRenderTarget( currentRenderTarget );
  17804. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17805. _this.toneMapping = currentToneMapping;
  17806. }
  17807. function renderObjects( renderList, scene, camera ) {
  17808. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17809. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17810. const renderItem = renderList[ i ];
  17811. const object = renderItem.object;
  17812. const geometry = renderItem.geometry;
  17813. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17814. const group = renderItem.group;
  17815. if ( object.layers.test( camera.layers ) ) {
  17816. renderObject( object, scene, camera, geometry, material, group );
  17817. }
  17818. }
  17819. }
  17820. function renderObject( object, scene, camera, geometry, material, group ) {
  17821. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17822. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17823. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17824. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17825. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17826. material.side = BackSide;
  17827. material.needsUpdate = true;
  17828. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17829. material.side = FrontSide;
  17830. material.needsUpdate = true;
  17831. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17832. material.side = DoubleSide;
  17833. } else {
  17834. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17835. }
  17836. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17837. }
  17838. function getProgram( material, scene, object ) {
  17839. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17840. const materialProperties = properties.get( material );
  17841. const lights = currentRenderState.state.lights;
  17842. const shadowsArray = currentRenderState.state.shadowsArray;
  17843. const lightsStateVersion = lights.state.version;
  17844. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17845. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17846. let programs = materialProperties.programs;
  17847. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17848. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17849. materialProperties.fog = scene.fog;
  17850. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17851. if ( programs === undefined ) {
  17852. // new material
  17853. material.addEventListener( 'dispose', onMaterialDispose );
  17854. programs = new Map();
  17855. materialProperties.programs = programs;
  17856. }
  17857. let program = programs.get( programCacheKey );
  17858. if ( program !== undefined ) {
  17859. // early out if program and light state is identical
  17860. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17861. updateCommonMaterialProperties( material, parameters );
  17862. return program;
  17863. }
  17864. } else {
  17865. parameters.uniforms = programCache.getUniforms( material );
  17866. material.onBuild( object, parameters, _this );
  17867. material.onBeforeCompile( parameters, _this );
  17868. program = programCache.acquireProgram( parameters, programCacheKey );
  17869. programs.set( programCacheKey, program );
  17870. materialProperties.uniforms = parameters.uniforms;
  17871. }
  17872. const uniforms = materialProperties.uniforms;
  17873. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17874. uniforms.clippingPlanes = clipping.uniform;
  17875. }
  17876. updateCommonMaterialProperties( material, parameters );
  17877. // store the light setup it was created for
  17878. materialProperties.needsLights = materialNeedsLights( material );
  17879. materialProperties.lightsStateVersion = lightsStateVersion;
  17880. if ( materialProperties.needsLights ) {
  17881. // wire up the material to this renderer's lighting state
  17882. uniforms.ambientLightColor.value = lights.state.ambient;
  17883. uniforms.lightProbe.value = lights.state.probe;
  17884. uniforms.directionalLights.value = lights.state.directional;
  17885. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17886. uniforms.spotLights.value = lights.state.spot;
  17887. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17888. uniforms.rectAreaLights.value = lights.state.rectArea;
  17889. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17890. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17891. uniforms.pointLights.value = lights.state.point;
  17892. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17893. uniforms.hemisphereLights.value = lights.state.hemi;
  17894. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17895. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17896. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17897. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17898. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17899. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17900. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17901. // TODO (abelnation): add area lights shadow info to uniforms
  17902. }
  17903. materialProperties.currentProgram = program;
  17904. materialProperties.uniformsList = null;
  17905. return program;
  17906. }
  17907. function getUniformList( materialProperties ) {
  17908. if ( materialProperties.uniformsList === null ) {
  17909. const progUniforms = materialProperties.currentProgram.getUniforms();
  17910. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  17911. }
  17912. return materialProperties.uniformsList;
  17913. }
  17914. function updateCommonMaterialProperties( material, parameters ) {
  17915. const materialProperties = properties.get( material );
  17916. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17917. materialProperties.batching = parameters.batching;
  17918. materialProperties.instancing = parameters.instancing;
  17919. materialProperties.instancingColor = parameters.instancingColor;
  17920. materialProperties.skinning = parameters.skinning;
  17921. materialProperties.morphTargets = parameters.morphTargets;
  17922. materialProperties.morphNormals = parameters.morphNormals;
  17923. materialProperties.morphColors = parameters.morphColors;
  17924. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17925. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17926. materialProperties.numIntersection = parameters.numClipIntersection;
  17927. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17928. materialProperties.vertexTangents = parameters.vertexTangents;
  17929. materialProperties.toneMapping = parameters.toneMapping;
  17930. }
  17931. function setProgram( camera, scene, geometry, material, object ) {
  17932. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17933. textures.resetTextureUnits();
  17934. const fog = scene.fog;
  17935. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17936. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17937. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17938. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17939. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  17940. const morphTargets = !! geometry.morphAttributes.position;
  17941. const morphNormals = !! geometry.morphAttributes.normal;
  17942. const morphColors = !! geometry.morphAttributes.color;
  17943. let toneMapping = NoToneMapping;
  17944. if ( material.toneMapped ) {
  17945. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  17946. toneMapping = _this.toneMapping;
  17947. }
  17948. }
  17949. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17950. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17951. const materialProperties = properties.get( material );
  17952. const lights = currentRenderState.state.lights;
  17953. if ( _clippingEnabled === true ) {
  17954. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17955. const useCache =
  17956. camera === _currentCamera &&
  17957. material.id === _currentMaterialId;
  17958. // we might want to call this function with some ClippingGroup
  17959. // object instead of the material, once it becomes feasible
  17960. // (#8465, #8379)
  17961. clipping.setState( material, camera, useCache );
  17962. }
  17963. }
  17964. //
  17965. let needsProgramChange = false;
  17966. if ( material.version === materialProperties.__version ) {
  17967. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17968. needsProgramChange = true;
  17969. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17970. needsProgramChange = true;
  17971. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  17972. needsProgramChange = true;
  17973. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  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 ( materialProperties.envMap !== envMap ) {
  17988. needsProgramChange = true;
  17989. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17990. needsProgramChange = true;
  17991. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17992. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17993. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17994. needsProgramChange = true;
  17995. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17996. needsProgramChange = true;
  17997. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17998. needsProgramChange = true;
  17999. } else if ( materialProperties.morphTargets !== morphTargets ) {
  18000. needsProgramChange = true;
  18001. } else if ( materialProperties.morphNormals !== morphNormals ) {
  18002. needsProgramChange = true;
  18003. } else if ( materialProperties.morphColors !== morphColors ) {
  18004. needsProgramChange = true;
  18005. } else if ( materialProperties.toneMapping !== toneMapping ) {
  18006. needsProgramChange = true;
  18007. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  18008. needsProgramChange = true;
  18009. }
  18010. } else {
  18011. needsProgramChange = true;
  18012. materialProperties.__version = material.version;
  18013. }
  18014. //
  18015. let program = materialProperties.currentProgram;
  18016. if ( needsProgramChange === true ) {
  18017. program = getProgram( material, scene, object );
  18018. }
  18019. let refreshProgram = false;
  18020. let refreshMaterial = false;
  18021. let refreshLights = false;
  18022. const p_uniforms = program.getUniforms(),
  18023. m_uniforms = materialProperties.uniforms;
  18024. if ( state.useProgram( program.program ) ) {
  18025. refreshProgram = true;
  18026. refreshMaterial = true;
  18027. refreshLights = true;
  18028. }
  18029. if ( material.id !== _currentMaterialId ) {
  18030. _currentMaterialId = material.id;
  18031. refreshMaterial = true;
  18032. }
  18033. if ( refreshProgram || _currentCamera !== camera ) {
  18034. // common camera uniforms
  18035. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  18036. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  18037. const uCamPos = p_uniforms.map.cameraPosition;
  18038. if ( uCamPos !== undefined ) {
  18039. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  18040. }
  18041. if ( capabilities.logarithmicDepthBuffer ) {
  18042. p_uniforms.setValue( _gl, 'logDepthBufFC',
  18043. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  18044. }
  18045. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  18046. if ( material.isMeshPhongMaterial ||
  18047. material.isMeshToonMaterial ||
  18048. material.isMeshLambertMaterial ||
  18049. material.isMeshBasicMaterial ||
  18050. material.isMeshStandardMaterial ||
  18051. material.isShaderMaterial ) {
  18052. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  18053. }
  18054. if ( _currentCamera !== camera ) {
  18055. _currentCamera = camera;
  18056. // lighting uniforms depend on the camera so enforce an update
  18057. // now, in case this material supports lights - or later, when
  18058. // the next material that does gets activated:
  18059. refreshMaterial = true; // set to true on material change
  18060. refreshLights = true; // remains set until update done
  18061. }
  18062. }
  18063. // skinning and morph target uniforms must be set even if material didn't change
  18064. // auto-setting of texture unit for bone and morph texture must go before other textures
  18065. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  18066. if ( object.isSkinnedMesh ) {
  18067. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  18068. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  18069. const skeleton = object.skeleton;
  18070. if ( skeleton ) {
  18071. if ( capabilities.floatVertexTextures ) {
  18072. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  18073. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  18074. } else {
  18075. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  18076. }
  18077. }
  18078. }
  18079. if ( object.isBatchedMesh ) {
  18080. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  18081. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  18082. }
  18083. const morphAttributes = geometry.morphAttributes;
  18084. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  18085. morphtargets.update( object, geometry, program );
  18086. }
  18087. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  18088. materialProperties.receiveShadow = object.receiveShadow;
  18089. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  18090. }
  18091. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  18092. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  18093. m_uniforms.envMap.value = envMap;
  18094. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  18095. }
  18096. if ( refreshMaterial ) {
  18097. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  18098. if ( materialProperties.needsLights ) {
  18099. // the current material requires lighting info
  18100. // note: all lighting uniforms are always set correctly
  18101. // they simply reference the renderer's state for their
  18102. // values
  18103. //
  18104. // use the current material's .needsUpdate flags to set
  18105. // the GL state when required
  18106. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18107. }
  18108. // refresh uniforms common to several materials
  18109. if ( fog && material.fog === true ) {
  18110. materials.refreshFogUniforms( m_uniforms, fog );
  18111. }
  18112. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  18113. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18114. }
  18115. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  18116. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18117. material.uniformsNeedUpdate = false;
  18118. }
  18119. if ( material.isSpriteMaterial ) {
  18120. p_uniforms.setValue( _gl, 'center', object.center );
  18121. }
  18122. // common matrices
  18123. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18124. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18125. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18126. // UBOs
  18127. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  18128. const groups = material.uniformsGroups;
  18129. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  18130. if ( capabilities.isWebGL2 ) {
  18131. const group = groups[ i ];
  18132. uniformsGroups.update( group, program );
  18133. uniformsGroups.bind( group, program );
  18134. } else {
  18135. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  18136. }
  18137. }
  18138. }
  18139. return program;
  18140. }
  18141. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18142. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18143. uniforms.ambientLightColor.needsUpdate = value;
  18144. uniforms.lightProbe.needsUpdate = value;
  18145. uniforms.directionalLights.needsUpdate = value;
  18146. uniforms.directionalLightShadows.needsUpdate = value;
  18147. uniforms.pointLights.needsUpdate = value;
  18148. uniforms.pointLightShadows.needsUpdate = value;
  18149. uniforms.spotLights.needsUpdate = value;
  18150. uniforms.spotLightShadows.needsUpdate = value;
  18151. uniforms.rectAreaLights.needsUpdate = value;
  18152. uniforms.hemisphereLights.needsUpdate = value;
  18153. }
  18154. function materialNeedsLights( material ) {
  18155. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  18156. material.isMeshStandardMaterial || material.isShadowMaterial ||
  18157. ( material.isShaderMaterial && material.lights === true );
  18158. }
  18159. this.getActiveCubeFace = function () {
  18160. return _currentActiveCubeFace;
  18161. };
  18162. this.getActiveMipmapLevel = function () {
  18163. return _currentActiveMipmapLevel;
  18164. };
  18165. this.getRenderTarget = function () {
  18166. return _currentRenderTarget;
  18167. };
  18168. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  18169. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  18170. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  18171. const renderTargetProperties = properties.get( renderTarget );
  18172. renderTargetProperties.__hasExternalTextures = true;
  18173. if ( renderTargetProperties.__hasExternalTextures ) {
  18174. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  18175. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  18176. // The multisample_render_to_texture extension doesn't work properly if there
  18177. // are midframe flushes and an external depth buffer. Disable use of the extension.
  18178. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  18179. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  18180. renderTargetProperties.__useRenderToTexture = false;
  18181. }
  18182. }
  18183. }
  18184. };
  18185. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  18186. const renderTargetProperties = properties.get( renderTarget );
  18187. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  18188. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  18189. };
  18190. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  18191. _currentRenderTarget = renderTarget;
  18192. _currentActiveCubeFace = activeCubeFace;
  18193. _currentActiveMipmapLevel = activeMipmapLevel;
  18194. let useDefaultFramebuffer = true;
  18195. let framebuffer = null;
  18196. let isCube = false;
  18197. let isRenderTarget3D = false;
  18198. if ( renderTarget ) {
  18199. const renderTargetProperties = properties.get( renderTarget );
  18200. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  18201. // We need to make sure to rebind the framebuffer.
  18202. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  18203. useDefaultFramebuffer = false;
  18204. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  18205. textures.setupRenderTarget( renderTarget );
  18206. } else if ( renderTargetProperties.__hasExternalTextures ) {
  18207. // Color and depth texture must be rebound in order for the swapchain to update.
  18208. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  18209. }
  18210. const texture = renderTarget.texture;
  18211. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18212. isRenderTarget3D = true;
  18213. }
  18214. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18215. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18216. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  18217. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  18218. } else {
  18219. framebuffer = __webglFramebuffer[ activeCubeFace ];
  18220. }
  18221. isCube = true;
  18222. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  18223. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  18224. } else {
  18225. if ( Array.isArray( __webglFramebuffer ) ) {
  18226. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  18227. } else {
  18228. framebuffer = __webglFramebuffer;
  18229. }
  18230. }
  18231. _currentViewport.copy( renderTarget.viewport );
  18232. _currentScissor.copy( renderTarget.scissor );
  18233. _currentScissorTest = renderTarget.scissorTest;
  18234. } else {
  18235. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  18236. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  18237. _currentScissorTest = _scissorTest;
  18238. }
  18239. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18240. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  18241. state.drawBuffers( renderTarget, framebuffer );
  18242. }
  18243. state.viewport( _currentViewport );
  18244. state.scissor( _currentScissor );
  18245. state.setScissorTest( _currentScissorTest );
  18246. if ( isCube ) {
  18247. const textureProperties = properties.get( renderTarget.texture );
  18248. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  18249. } else if ( isRenderTarget3D ) {
  18250. const textureProperties = properties.get( renderTarget.texture );
  18251. const layer = activeCubeFace || 0;
  18252. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  18253. }
  18254. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  18255. };
  18256. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18257. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18258. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18259. return;
  18260. }
  18261. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18262. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18263. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18264. }
  18265. if ( framebuffer ) {
  18266. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18267. try {
  18268. const texture = renderTarget.texture;
  18269. const textureFormat = texture.format;
  18270. const textureType = texture.type;
  18271. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18272. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18273. return;
  18274. }
  18275. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  18276. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  18277. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  18278. ! halfFloatSupportedByExt ) {
  18279. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18280. return;
  18281. }
  18282. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18283. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18284. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18285. }
  18286. } finally {
  18287. // restore framebuffer of current render target if necessary
  18288. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18289. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18290. }
  18291. }
  18292. };
  18293. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  18294. const levelScale = Math.pow( 2, - level );
  18295. const width = Math.floor( texture.image.width * levelScale );
  18296. const height = Math.floor( texture.image.height * levelScale );
  18297. textures.setTexture2D( texture, 0 );
  18298. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  18299. state.unbindTexture();
  18300. };
  18301. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  18302. const width = srcTexture.image.width;
  18303. const height = srcTexture.image.height;
  18304. const glFormat = utils.convert( dstTexture.format );
  18305. const glType = utils.convert( dstTexture.type );
  18306. textures.setTexture2D( dstTexture, 0 );
  18307. // As another texture upload may have changed pixelStorei
  18308. // parameters, make sure they are correct for the dstTexture
  18309. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18310. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18311. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18312. if ( srcTexture.isDataTexture ) {
  18313. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  18314. } else {
  18315. if ( srcTexture.isCompressedTexture ) {
  18316. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  18317. } else {
  18318. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  18319. }
  18320. }
  18321. // Generate mipmaps only when copying level 0
  18322. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18323. state.unbindTexture();
  18324. };
  18325. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  18326. if ( _this.isWebGL1Renderer ) {
  18327. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  18328. return;
  18329. }
  18330. const width = sourceBox.max.x - sourceBox.min.x + 1;
  18331. const height = sourceBox.max.y - sourceBox.min.y + 1;
  18332. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  18333. const glFormat = utils.convert( dstTexture.format );
  18334. const glType = utils.convert( dstTexture.type );
  18335. let glTarget;
  18336. if ( dstTexture.isData3DTexture ) {
  18337. textures.setTexture3D( dstTexture, 0 );
  18338. glTarget = _gl.TEXTURE_3D;
  18339. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  18340. textures.setTexture2DArray( dstTexture, 0 );
  18341. glTarget = _gl.TEXTURE_2D_ARRAY;
  18342. } else {
  18343. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18344. return;
  18345. }
  18346. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18347. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18348. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18349. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18350. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18351. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18352. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18353. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18354. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18355. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18356. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18357. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  18358. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  18359. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  18360. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18361. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  18362. } else {
  18363. if ( srcTexture.isCompressedArrayTexture ) {
  18364. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  18365. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  18366. } else {
  18367. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  18368. }
  18369. }
  18370. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  18371. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  18372. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  18373. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  18374. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  18375. // Generate mipmaps only when copying level 0
  18376. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18377. state.unbindTexture();
  18378. };
  18379. this.initTexture = function ( texture ) {
  18380. if ( texture.isCubeTexture ) {
  18381. textures.setTextureCube( texture, 0 );
  18382. } else if ( texture.isData3DTexture ) {
  18383. textures.setTexture3D( texture, 0 );
  18384. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18385. textures.setTexture2DArray( texture, 0 );
  18386. } else {
  18387. textures.setTexture2D( texture, 0 );
  18388. }
  18389. state.unbindTexture();
  18390. };
  18391. this.resetState = function () {
  18392. _currentActiveCubeFace = 0;
  18393. _currentActiveMipmapLevel = 0;
  18394. _currentRenderTarget = null;
  18395. state.reset();
  18396. bindingStates.reset();
  18397. };
  18398. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18399. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18400. }
  18401. }
  18402. get coordinateSystem() {
  18403. return WebGLCoordinateSystem;
  18404. }
  18405. get outputColorSpace() {
  18406. return this._outputColorSpace;
  18407. }
  18408. set outputColorSpace( colorSpace ) {
  18409. this._outputColorSpace = colorSpace;
  18410. const gl = this.getContext();
  18411. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18412. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18413. }
  18414. get outputEncoding() { // @deprecated, r152
  18415. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18416. return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  18417. }
  18418. set outputEncoding( encoding ) { // @deprecated, r152
  18419. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18420. this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  18421. }
  18422. get useLegacyLights() { // @deprecated, r155
  18423. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  18424. return this._useLegacyLights;
  18425. }
  18426. set useLegacyLights( value ) { // @deprecated, r155
  18427. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  18428. this._useLegacyLights = value;
  18429. }
  18430. }
  18431. class WebGL1Renderer extends WebGLRenderer {}
  18432. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  18433. class FogExp2 {
  18434. constructor( color, density = 0.00025 ) {
  18435. this.isFogExp2 = true;
  18436. this.name = '';
  18437. this.color = new Color( color );
  18438. this.density = density;
  18439. }
  18440. clone() {
  18441. return new FogExp2( this.color, this.density );
  18442. }
  18443. toJSON( /* meta */ ) {
  18444. return {
  18445. type: 'FogExp2',
  18446. name: this.name,
  18447. color: this.color.getHex(),
  18448. density: this.density
  18449. };
  18450. }
  18451. }
  18452. class Fog {
  18453. constructor( color, near = 1, far = 1000 ) {
  18454. this.isFog = true;
  18455. this.name = '';
  18456. this.color = new Color( color );
  18457. this.near = near;
  18458. this.far = far;
  18459. }
  18460. clone() {
  18461. return new Fog( this.color, this.near, this.far );
  18462. }
  18463. toJSON( /* meta */ ) {
  18464. return {
  18465. type: 'Fog',
  18466. name: this.name,
  18467. color: this.color.getHex(),
  18468. near: this.near,
  18469. far: this.far
  18470. };
  18471. }
  18472. }
  18473. class Scene extends Object3D {
  18474. constructor() {
  18475. super();
  18476. this.isScene = true;
  18477. this.type = 'Scene';
  18478. this.background = null;
  18479. this.environment = null;
  18480. this.fog = null;
  18481. this.backgroundBlurriness = 0;
  18482. this.backgroundIntensity = 1;
  18483. this.overrideMaterial = null;
  18484. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18485. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18486. }
  18487. }
  18488. copy( source, recursive ) {
  18489. super.copy( source, recursive );
  18490. if ( source.background !== null ) this.background = source.background.clone();
  18491. if ( source.environment !== null ) this.environment = source.environment.clone();
  18492. if ( source.fog !== null ) this.fog = source.fog.clone();
  18493. this.backgroundBlurriness = source.backgroundBlurriness;
  18494. this.backgroundIntensity = source.backgroundIntensity;
  18495. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18496. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18497. return this;
  18498. }
  18499. toJSON( meta ) {
  18500. const data = super.toJSON( meta );
  18501. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18502. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18503. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18504. return data;
  18505. }
  18506. }
  18507. class InterleavedBuffer {
  18508. constructor( array, stride ) {
  18509. this.isInterleavedBuffer = true;
  18510. this.array = array;
  18511. this.stride = stride;
  18512. this.count = array !== undefined ? array.length / stride : 0;
  18513. this.usage = StaticDrawUsage;
  18514. this._updateRange = { offset: 0, count: - 1 };
  18515. this.updateRanges = [];
  18516. this.version = 0;
  18517. this.uuid = generateUUID();
  18518. }
  18519. onUploadCallback() {}
  18520. set needsUpdate( value ) {
  18521. if ( value === true ) this.version ++;
  18522. }
  18523. get updateRange() {
  18524. console.warn( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  18525. return this._updateRange;
  18526. }
  18527. setUsage( value ) {
  18528. this.usage = value;
  18529. return this;
  18530. }
  18531. addUpdateRange( start, count ) {
  18532. this.updateRanges.push( { start, count } );
  18533. }
  18534. clearUpdateRanges() {
  18535. this.updateRanges.length = 0;
  18536. }
  18537. copy( source ) {
  18538. this.array = new source.array.constructor( source.array );
  18539. this.count = source.count;
  18540. this.stride = source.stride;
  18541. this.usage = source.usage;
  18542. return this;
  18543. }
  18544. copyAt( index1, attribute, index2 ) {
  18545. index1 *= this.stride;
  18546. index2 *= attribute.stride;
  18547. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18548. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18549. }
  18550. return this;
  18551. }
  18552. set( value, offset = 0 ) {
  18553. this.array.set( value, offset );
  18554. return this;
  18555. }
  18556. clone( data ) {
  18557. if ( data.arrayBuffers === undefined ) {
  18558. data.arrayBuffers = {};
  18559. }
  18560. if ( this.array.buffer._uuid === undefined ) {
  18561. this.array.buffer._uuid = generateUUID();
  18562. }
  18563. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18564. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18565. }
  18566. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18567. const ib = new this.constructor( array, this.stride );
  18568. ib.setUsage( this.usage );
  18569. return ib;
  18570. }
  18571. onUpload( callback ) {
  18572. this.onUploadCallback = callback;
  18573. return this;
  18574. }
  18575. toJSON( data ) {
  18576. if ( data.arrayBuffers === undefined ) {
  18577. data.arrayBuffers = {};
  18578. }
  18579. // generate UUID for array buffer if necessary
  18580. if ( this.array.buffer._uuid === undefined ) {
  18581. this.array.buffer._uuid = generateUUID();
  18582. }
  18583. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18584. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18585. }
  18586. //
  18587. return {
  18588. uuid: this.uuid,
  18589. buffer: this.array.buffer._uuid,
  18590. type: this.array.constructor.name,
  18591. stride: this.stride
  18592. };
  18593. }
  18594. }
  18595. const _vector$6 = /*@__PURE__*/ new Vector3();
  18596. class InterleavedBufferAttribute {
  18597. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18598. this.isInterleavedBufferAttribute = true;
  18599. this.name = '';
  18600. this.data = interleavedBuffer;
  18601. this.itemSize = itemSize;
  18602. this.offset = offset;
  18603. this.normalized = normalized;
  18604. }
  18605. get count() {
  18606. return this.data.count;
  18607. }
  18608. get array() {
  18609. return this.data.array;
  18610. }
  18611. set needsUpdate( value ) {
  18612. this.data.needsUpdate = value;
  18613. }
  18614. applyMatrix4( m ) {
  18615. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18616. _vector$6.fromBufferAttribute( this, i );
  18617. _vector$6.applyMatrix4( m );
  18618. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18619. }
  18620. return this;
  18621. }
  18622. applyNormalMatrix( m ) {
  18623. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18624. _vector$6.fromBufferAttribute( this, i );
  18625. _vector$6.applyNormalMatrix( m );
  18626. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18627. }
  18628. return this;
  18629. }
  18630. transformDirection( m ) {
  18631. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18632. _vector$6.fromBufferAttribute( this, i );
  18633. _vector$6.transformDirection( m );
  18634. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18635. }
  18636. return this;
  18637. }
  18638. setX( index, x ) {
  18639. if ( this.normalized ) x = normalize( x, this.array );
  18640. this.data.array[ index * this.data.stride + this.offset ] = x;
  18641. return this;
  18642. }
  18643. setY( index, y ) {
  18644. if ( this.normalized ) y = normalize( y, this.array );
  18645. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18646. return this;
  18647. }
  18648. setZ( index, z ) {
  18649. if ( this.normalized ) z = normalize( z, this.array );
  18650. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18651. return this;
  18652. }
  18653. setW( index, w ) {
  18654. if ( this.normalized ) w = normalize( w, this.array );
  18655. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18656. return this;
  18657. }
  18658. getX( index ) {
  18659. let x = this.data.array[ index * this.data.stride + this.offset ];
  18660. if ( this.normalized ) x = denormalize( x, this.array );
  18661. return x;
  18662. }
  18663. getY( index ) {
  18664. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18665. if ( this.normalized ) y = denormalize( y, this.array );
  18666. return y;
  18667. }
  18668. getZ( index ) {
  18669. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18670. if ( this.normalized ) z = denormalize( z, this.array );
  18671. return z;
  18672. }
  18673. getW( index ) {
  18674. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18675. if ( this.normalized ) w = denormalize( w, this.array );
  18676. return w;
  18677. }
  18678. setXY( index, x, y ) {
  18679. index = index * this.data.stride + this.offset;
  18680. if ( this.normalized ) {
  18681. x = normalize( x, this.array );
  18682. y = normalize( y, this.array );
  18683. }
  18684. this.data.array[ index + 0 ] = x;
  18685. this.data.array[ index + 1 ] = y;
  18686. return this;
  18687. }
  18688. setXYZ( index, x, y, z ) {
  18689. index = index * this.data.stride + this.offset;
  18690. if ( this.normalized ) {
  18691. x = normalize( x, this.array );
  18692. y = normalize( y, this.array );
  18693. z = normalize( z, this.array );
  18694. }
  18695. this.data.array[ index + 0 ] = x;
  18696. this.data.array[ index + 1 ] = y;
  18697. this.data.array[ index + 2 ] = z;
  18698. return this;
  18699. }
  18700. setXYZW( index, x, y, z, w ) {
  18701. index = index * this.data.stride + this.offset;
  18702. if ( this.normalized ) {
  18703. x = normalize( x, this.array );
  18704. y = normalize( y, this.array );
  18705. z = normalize( z, this.array );
  18706. w = normalize( w, this.array );
  18707. }
  18708. this.data.array[ index + 0 ] = x;
  18709. this.data.array[ index + 1 ] = y;
  18710. this.data.array[ index + 2 ] = z;
  18711. this.data.array[ index + 3 ] = w;
  18712. return this;
  18713. }
  18714. clone( data ) {
  18715. if ( data === undefined ) {
  18716. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18717. const array = [];
  18718. for ( let i = 0; i < this.count; i ++ ) {
  18719. const index = i * this.data.stride + this.offset;
  18720. for ( let j = 0; j < this.itemSize; j ++ ) {
  18721. array.push( this.data.array[ index + j ] );
  18722. }
  18723. }
  18724. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18725. } else {
  18726. if ( data.interleavedBuffers === undefined ) {
  18727. data.interleavedBuffers = {};
  18728. }
  18729. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18730. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18731. }
  18732. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18733. }
  18734. }
  18735. toJSON( data ) {
  18736. if ( data === undefined ) {
  18737. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18738. const array = [];
  18739. for ( let i = 0; i < this.count; i ++ ) {
  18740. const index = i * this.data.stride + this.offset;
  18741. for ( let j = 0; j < this.itemSize; j ++ ) {
  18742. array.push( this.data.array[ index + j ] );
  18743. }
  18744. }
  18745. // de-interleave data and save it as an ordinary buffer attribute for now
  18746. return {
  18747. itemSize: this.itemSize,
  18748. type: this.array.constructor.name,
  18749. array: array,
  18750. normalized: this.normalized
  18751. };
  18752. } else {
  18753. // save as true interleaved attribute
  18754. if ( data.interleavedBuffers === undefined ) {
  18755. data.interleavedBuffers = {};
  18756. }
  18757. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18758. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18759. }
  18760. return {
  18761. isInterleavedBufferAttribute: true,
  18762. itemSize: this.itemSize,
  18763. data: this.data.uuid,
  18764. offset: this.offset,
  18765. normalized: this.normalized
  18766. };
  18767. }
  18768. }
  18769. }
  18770. class SpriteMaterial extends Material {
  18771. constructor( parameters ) {
  18772. super();
  18773. this.isSpriteMaterial = true;
  18774. this.type = 'SpriteMaterial';
  18775. this.color = new Color( 0xffffff );
  18776. this.map = null;
  18777. this.alphaMap = null;
  18778. this.rotation = 0;
  18779. this.sizeAttenuation = true;
  18780. this.transparent = true;
  18781. this.fog = true;
  18782. this.setValues( parameters );
  18783. }
  18784. copy( source ) {
  18785. super.copy( source );
  18786. this.color.copy( source.color );
  18787. this.map = source.map;
  18788. this.alphaMap = source.alphaMap;
  18789. this.rotation = source.rotation;
  18790. this.sizeAttenuation = source.sizeAttenuation;
  18791. this.fog = source.fog;
  18792. return this;
  18793. }
  18794. }
  18795. let _geometry;
  18796. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18797. const _worldScale = /*@__PURE__*/ new Vector3();
  18798. const _mvPosition = /*@__PURE__*/ new Vector3();
  18799. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18800. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18801. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18802. const _vA = /*@__PURE__*/ new Vector3();
  18803. const _vB = /*@__PURE__*/ new Vector3();
  18804. const _vC = /*@__PURE__*/ new Vector3();
  18805. const _uvA = /*@__PURE__*/ new Vector2();
  18806. const _uvB = /*@__PURE__*/ new Vector2();
  18807. const _uvC = /*@__PURE__*/ new Vector2();
  18808. class Sprite extends Object3D {
  18809. constructor( material = new SpriteMaterial() ) {
  18810. super();
  18811. this.isSprite = true;
  18812. this.type = 'Sprite';
  18813. if ( _geometry === undefined ) {
  18814. _geometry = new BufferGeometry();
  18815. const float32Array = new Float32Array( [
  18816. - 0.5, - 0.5, 0, 0, 0,
  18817. 0.5, - 0.5, 0, 1, 0,
  18818. 0.5, 0.5, 0, 1, 1,
  18819. - 0.5, 0.5, 0, 0, 1
  18820. ] );
  18821. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18822. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18823. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18824. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18825. }
  18826. this.geometry = _geometry;
  18827. this.material = material;
  18828. this.center = new Vector2( 0.5, 0.5 );
  18829. }
  18830. raycast( raycaster, intersects ) {
  18831. if ( raycaster.camera === null ) {
  18832. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18833. }
  18834. _worldScale.setFromMatrixScale( this.matrixWorld );
  18835. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18836. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18837. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18838. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18839. _worldScale.multiplyScalar( - _mvPosition.z );
  18840. }
  18841. const rotation = this.material.rotation;
  18842. let sin, cos;
  18843. if ( rotation !== 0 ) {
  18844. cos = Math.cos( rotation );
  18845. sin = Math.sin( rotation );
  18846. }
  18847. const center = this.center;
  18848. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18849. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18850. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18851. _uvA.set( 0, 0 );
  18852. _uvB.set( 1, 0 );
  18853. _uvC.set( 1, 1 );
  18854. // check first triangle
  18855. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18856. if ( intersect === null ) {
  18857. // check second triangle
  18858. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18859. _uvB.set( 0, 1 );
  18860. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18861. if ( intersect === null ) {
  18862. return;
  18863. }
  18864. }
  18865. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18866. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18867. intersects.push( {
  18868. distance: distance,
  18869. point: _intersectPoint.clone(),
  18870. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18871. face: null,
  18872. object: this
  18873. } );
  18874. }
  18875. copy( source, recursive ) {
  18876. super.copy( source, recursive );
  18877. if ( source.center !== undefined ) this.center.copy( source.center );
  18878. this.material = source.material;
  18879. return this;
  18880. }
  18881. }
  18882. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18883. // compute position in camera space
  18884. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18885. // to check if rotation is not zero
  18886. if ( sin !== undefined ) {
  18887. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18888. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18889. } else {
  18890. _rotatedPosition.copy( _alignedPosition );
  18891. }
  18892. vertexPosition.copy( mvPosition );
  18893. vertexPosition.x += _rotatedPosition.x;
  18894. vertexPosition.y += _rotatedPosition.y;
  18895. // transform to world space
  18896. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18897. }
  18898. const _v1$2 = /*@__PURE__*/ new Vector3();
  18899. const _v2$1 = /*@__PURE__*/ new Vector3();
  18900. class LOD extends Object3D {
  18901. constructor() {
  18902. super();
  18903. this._currentLevel = 0;
  18904. this.type = 'LOD';
  18905. Object.defineProperties( this, {
  18906. levels: {
  18907. enumerable: true,
  18908. value: []
  18909. },
  18910. isLOD: {
  18911. value: true,
  18912. }
  18913. } );
  18914. this.autoUpdate = true;
  18915. }
  18916. copy( source ) {
  18917. super.copy( source, false );
  18918. const levels = source.levels;
  18919. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18920. const level = levels[ i ];
  18921. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18922. }
  18923. this.autoUpdate = source.autoUpdate;
  18924. return this;
  18925. }
  18926. addLevel( object, distance = 0, hysteresis = 0 ) {
  18927. distance = Math.abs( distance );
  18928. const levels = this.levels;
  18929. let l;
  18930. for ( l = 0; l < levels.length; l ++ ) {
  18931. if ( distance < levels[ l ].distance ) {
  18932. break;
  18933. }
  18934. }
  18935. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18936. this.add( object );
  18937. return this;
  18938. }
  18939. getCurrentLevel() {
  18940. return this._currentLevel;
  18941. }
  18942. getObjectForDistance( distance ) {
  18943. const levels = this.levels;
  18944. if ( levels.length > 0 ) {
  18945. let i, l;
  18946. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18947. let levelDistance = levels[ i ].distance;
  18948. if ( levels[ i ].object.visible ) {
  18949. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18950. }
  18951. if ( distance < levelDistance ) {
  18952. break;
  18953. }
  18954. }
  18955. return levels[ i - 1 ].object;
  18956. }
  18957. return null;
  18958. }
  18959. raycast( raycaster, intersects ) {
  18960. const levels = this.levels;
  18961. if ( levels.length > 0 ) {
  18962. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18963. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18964. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18965. }
  18966. }
  18967. update( camera ) {
  18968. const levels = this.levels;
  18969. if ( levels.length > 1 ) {
  18970. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18971. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18972. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18973. levels[ 0 ].object.visible = true;
  18974. let i, l;
  18975. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18976. let levelDistance = levels[ i ].distance;
  18977. if ( levels[ i ].object.visible ) {
  18978. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18979. }
  18980. if ( distance >= levelDistance ) {
  18981. levels[ i - 1 ].object.visible = false;
  18982. levels[ i ].object.visible = true;
  18983. } else {
  18984. break;
  18985. }
  18986. }
  18987. this._currentLevel = i - 1;
  18988. for ( ; i < l; i ++ ) {
  18989. levels[ i ].object.visible = false;
  18990. }
  18991. }
  18992. }
  18993. toJSON( meta ) {
  18994. const data = super.toJSON( meta );
  18995. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18996. data.object.levels = [];
  18997. const levels = this.levels;
  18998. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18999. const level = levels[ i ];
  19000. data.object.levels.push( {
  19001. object: level.object.uuid,
  19002. distance: level.distance,
  19003. hysteresis: level.hysteresis
  19004. } );
  19005. }
  19006. return data;
  19007. }
  19008. }
  19009. const _basePosition = /*@__PURE__*/ new Vector3();
  19010. const _skinIndex = /*@__PURE__*/ new Vector4();
  19011. const _skinWeight = /*@__PURE__*/ new Vector4();
  19012. const _vector3 = /*@__PURE__*/ new Vector3();
  19013. const _matrix4 = /*@__PURE__*/ new Matrix4();
  19014. const _vertex = /*@__PURE__*/ new Vector3();
  19015. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19016. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  19017. const _ray$2 = /*@__PURE__*/ new Ray();
  19018. class SkinnedMesh extends Mesh {
  19019. constructor( geometry, material ) {
  19020. super( geometry, material );
  19021. this.isSkinnedMesh = true;
  19022. this.type = 'SkinnedMesh';
  19023. this.bindMode = AttachedBindMode;
  19024. this.bindMatrix = new Matrix4();
  19025. this.bindMatrixInverse = new Matrix4();
  19026. this.boundingBox = null;
  19027. this.boundingSphere = null;
  19028. }
  19029. computeBoundingBox() {
  19030. const geometry = this.geometry;
  19031. if ( this.boundingBox === null ) {
  19032. this.boundingBox = new Box3();
  19033. }
  19034. this.boundingBox.makeEmpty();
  19035. const positionAttribute = geometry.getAttribute( 'position' );
  19036. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19037. this.getVertexPosition( i, _vertex );
  19038. this.boundingBox.expandByPoint( _vertex );
  19039. }
  19040. }
  19041. computeBoundingSphere() {
  19042. const geometry = this.geometry;
  19043. if ( this.boundingSphere === null ) {
  19044. this.boundingSphere = new Sphere();
  19045. }
  19046. this.boundingSphere.makeEmpty();
  19047. const positionAttribute = geometry.getAttribute( 'position' );
  19048. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19049. this.getVertexPosition( i, _vertex );
  19050. this.boundingSphere.expandByPoint( _vertex );
  19051. }
  19052. }
  19053. copy( source, recursive ) {
  19054. super.copy( source, recursive );
  19055. this.bindMode = source.bindMode;
  19056. this.bindMatrix.copy( source.bindMatrix );
  19057. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  19058. this.skeleton = source.skeleton;
  19059. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19060. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19061. return this;
  19062. }
  19063. raycast( raycaster, intersects ) {
  19064. const material = this.material;
  19065. const matrixWorld = this.matrixWorld;
  19066. if ( material === undefined ) return;
  19067. // test with bounding sphere in world space
  19068. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19069. _sphere$4.copy( this.boundingSphere );
  19070. _sphere$4.applyMatrix4( matrixWorld );
  19071. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19072. // convert ray to local space of skinned mesh
  19073. _inverseMatrix$2.copy( matrixWorld ).invert();
  19074. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  19075. // test with bounding box in local space
  19076. if ( this.boundingBox !== null ) {
  19077. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  19078. }
  19079. // test for intersections with geometry
  19080. this._computeIntersections( raycaster, intersects, _ray$2 );
  19081. }
  19082. getVertexPosition( index, target ) {
  19083. super.getVertexPosition( index, target );
  19084. this.applyBoneTransform( index, target );
  19085. return target;
  19086. }
  19087. bind( skeleton, bindMatrix ) {
  19088. this.skeleton = skeleton;
  19089. if ( bindMatrix === undefined ) {
  19090. this.updateMatrixWorld( true );
  19091. this.skeleton.calculateInverses();
  19092. bindMatrix = this.matrixWorld;
  19093. }
  19094. this.bindMatrix.copy( bindMatrix );
  19095. this.bindMatrixInverse.copy( bindMatrix ).invert();
  19096. }
  19097. pose() {
  19098. this.skeleton.pose();
  19099. }
  19100. normalizeSkinWeights() {
  19101. const vector = new Vector4();
  19102. const skinWeight = this.geometry.attributes.skinWeight;
  19103. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  19104. vector.fromBufferAttribute( skinWeight, i );
  19105. const scale = 1.0 / vector.manhattanLength();
  19106. if ( scale !== Infinity ) {
  19107. vector.multiplyScalar( scale );
  19108. } else {
  19109. vector.set( 1, 0, 0, 0 ); // do something reasonable
  19110. }
  19111. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  19112. }
  19113. }
  19114. updateMatrixWorld( force ) {
  19115. super.updateMatrixWorld( force );
  19116. if ( this.bindMode === AttachedBindMode ) {
  19117. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  19118. } else if ( this.bindMode === DetachedBindMode ) {
  19119. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  19120. } else {
  19121. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  19122. }
  19123. }
  19124. applyBoneTransform( index, vector ) {
  19125. const skeleton = this.skeleton;
  19126. const geometry = this.geometry;
  19127. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  19128. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  19129. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  19130. vector.set( 0, 0, 0 );
  19131. for ( let i = 0; i < 4; i ++ ) {
  19132. const weight = _skinWeight.getComponent( i );
  19133. if ( weight !== 0 ) {
  19134. const boneIndex = _skinIndex.getComponent( i );
  19135. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  19136. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  19137. }
  19138. }
  19139. return vector.applyMatrix4( this.bindMatrixInverse );
  19140. }
  19141. boneTransform( index, vector ) { // @deprecated, r151
  19142. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  19143. return this.applyBoneTransform( index, vector );
  19144. }
  19145. }
  19146. class Bone extends Object3D {
  19147. constructor() {
  19148. super();
  19149. this.isBone = true;
  19150. this.type = 'Bone';
  19151. }
  19152. }
  19153. class DataTexture extends Texture {
  19154. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  19155. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19156. this.isDataTexture = true;
  19157. this.image = { data: data, width: width, height: height };
  19158. this.generateMipmaps = false;
  19159. this.flipY = false;
  19160. this.unpackAlignment = 1;
  19161. }
  19162. }
  19163. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  19164. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  19165. class Skeleton {
  19166. constructor( bones = [], boneInverses = [] ) {
  19167. this.uuid = generateUUID();
  19168. this.bones = bones.slice( 0 );
  19169. this.boneInverses = boneInverses;
  19170. this.boneMatrices = null;
  19171. this.boneTexture = null;
  19172. this.init();
  19173. }
  19174. init() {
  19175. const bones = this.bones;
  19176. const boneInverses = this.boneInverses;
  19177. this.boneMatrices = new Float32Array( bones.length * 16 );
  19178. // calculate inverse bone matrices if necessary
  19179. if ( boneInverses.length === 0 ) {
  19180. this.calculateInverses();
  19181. } else {
  19182. // handle special case
  19183. if ( bones.length !== boneInverses.length ) {
  19184. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19185. this.boneInverses = [];
  19186. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19187. this.boneInverses.push( new Matrix4() );
  19188. }
  19189. }
  19190. }
  19191. }
  19192. calculateInverses() {
  19193. this.boneInverses.length = 0;
  19194. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19195. const inverse = new Matrix4();
  19196. if ( this.bones[ i ] ) {
  19197. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19198. }
  19199. this.boneInverses.push( inverse );
  19200. }
  19201. }
  19202. pose() {
  19203. // recover the bind-time world matrices
  19204. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19205. const bone = this.bones[ i ];
  19206. if ( bone ) {
  19207. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19208. }
  19209. }
  19210. // compute the local matrices, positions, rotations and scales
  19211. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19212. const bone = this.bones[ i ];
  19213. if ( bone ) {
  19214. if ( bone.parent && bone.parent.isBone ) {
  19215. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19216. bone.matrix.multiply( bone.matrixWorld );
  19217. } else {
  19218. bone.matrix.copy( bone.matrixWorld );
  19219. }
  19220. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19221. }
  19222. }
  19223. }
  19224. update() {
  19225. const bones = this.bones;
  19226. const boneInverses = this.boneInverses;
  19227. const boneMatrices = this.boneMatrices;
  19228. const boneTexture = this.boneTexture;
  19229. // flatten bone matrices to array
  19230. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19231. // compute the offset between the current and the original transform
  19232. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  19233. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19234. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19235. }
  19236. if ( boneTexture !== null ) {
  19237. boneTexture.needsUpdate = true;
  19238. }
  19239. }
  19240. clone() {
  19241. return new Skeleton( this.bones, this.boneInverses );
  19242. }
  19243. computeBoneTexture() {
  19244. // layout (1 matrix = 4 pixels)
  19245. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19246. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19247. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19248. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19249. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19250. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19251. size = Math.ceil( size / 4 ) * 4;
  19252. size = Math.max( size, 4 );
  19253. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19254. boneMatrices.set( this.boneMatrices ); // copy current values
  19255. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19256. boneTexture.needsUpdate = true;
  19257. this.boneMatrices = boneMatrices;
  19258. this.boneTexture = boneTexture;
  19259. return this;
  19260. }
  19261. getBoneByName( name ) {
  19262. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19263. const bone = this.bones[ i ];
  19264. if ( bone.name === name ) {
  19265. return bone;
  19266. }
  19267. }
  19268. return undefined;
  19269. }
  19270. dispose( ) {
  19271. if ( this.boneTexture !== null ) {
  19272. this.boneTexture.dispose();
  19273. this.boneTexture = null;
  19274. }
  19275. }
  19276. fromJSON( json, bones ) {
  19277. this.uuid = json.uuid;
  19278. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19279. const uuid = json.bones[ i ];
  19280. let bone = bones[ uuid ];
  19281. if ( bone === undefined ) {
  19282. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  19283. bone = new Bone();
  19284. }
  19285. this.bones.push( bone );
  19286. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19287. }
  19288. this.init();
  19289. return this;
  19290. }
  19291. toJSON() {
  19292. const data = {
  19293. metadata: {
  19294. version: 4.6,
  19295. type: 'Skeleton',
  19296. generator: 'Skeleton.toJSON'
  19297. },
  19298. bones: [],
  19299. boneInverses: []
  19300. };
  19301. data.uuid = this.uuid;
  19302. const bones = this.bones;
  19303. const boneInverses = this.boneInverses;
  19304. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19305. const bone = bones[ i ];
  19306. data.bones.push( bone.uuid );
  19307. const boneInverse = boneInverses[ i ];
  19308. data.boneInverses.push( boneInverse.toArray() );
  19309. }
  19310. return data;
  19311. }
  19312. }
  19313. class InstancedBufferAttribute extends BufferAttribute {
  19314. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19315. super( array, itemSize, normalized );
  19316. this.isInstancedBufferAttribute = true;
  19317. this.meshPerAttribute = meshPerAttribute;
  19318. }
  19319. copy( source ) {
  19320. super.copy( source );
  19321. this.meshPerAttribute = source.meshPerAttribute;
  19322. return this;
  19323. }
  19324. toJSON() {
  19325. const data = super.toJSON();
  19326. data.meshPerAttribute = this.meshPerAttribute;
  19327. data.isInstancedBufferAttribute = true;
  19328. return data;
  19329. }
  19330. }
  19331. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19332. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19333. const _instanceIntersects = [];
  19334. const _box3 = /*@__PURE__*/ new Box3();
  19335. const _identity = /*@__PURE__*/ new Matrix4();
  19336. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19337. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19338. class InstancedMesh extends Mesh {
  19339. constructor( geometry, material, count ) {
  19340. super( geometry, material );
  19341. this.isInstancedMesh = true;
  19342. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19343. this.instanceColor = null;
  19344. this.count = count;
  19345. this.boundingBox = null;
  19346. this.boundingSphere = null;
  19347. for ( let i = 0; i < count; i ++ ) {
  19348. this.setMatrixAt( i, _identity );
  19349. }
  19350. }
  19351. computeBoundingBox() {
  19352. const geometry = this.geometry;
  19353. const count = this.count;
  19354. if ( this.boundingBox === null ) {
  19355. this.boundingBox = new Box3();
  19356. }
  19357. if ( geometry.boundingBox === null ) {
  19358. geometry.computeBoundingBox();
  19359. }
  19360. this.boundingBox.makeEmpty();
  19361. for ( let i = 0; i < count; i ++ ) {
  19362. this.getMatrixAt( i, _instanceLocalMatrix );
  19363. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19364. this.boundingBox.union( _box3 );
  19365. }
  19366. }
  19367. computeBoundingSphere() {
  19368. const geometry = this.geometry;
  19369. const count = this.count;
  19370. if ( this.boundingSphere === null ) {
  19371. this.boundingSphere = new Sphere();
  19372. }
  19373. if ( geometry.boundingSphere === null ) {
  19374. geometry.computeBoundingSphere();
  19375. }
  19376. this.boundingSphere.makeEmpty();
  19377. for ( let i = 0; i < count; i ++ ) {
  19378. this.getMatrixAt( i, _instanceLocalMatrix );
  19379. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19380. this.boundingSphere.union( _sphere$3 );
  19381. }
  19382. }
  19383. copy( source, recursive ) {
  19384. super.copy( source, recursive );
  19385. this.instanceMatrix.copy( source.instanceMatrix );
  19386. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19387. this.count = source.count;
  19388. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19389. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19390. return this;
  19391. }
  19392. getColorAt( index, color ) {
  19393. color.fromArray( this.instanceColor.array, index * 3 );
  19394. }
  19395. getMatrixAt( index, matrix ) {
  19396. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19397. }
  19398. raycast( raycaster, intersects ) {
  19399. const matrixWorld = this.matrixWorld;
  19400. const raycastTimes = this.count;
  19401. _mesh$1.geometry = this.geometry;
  19402. _mesh$1.material = this.material;
  19403. if ( _mesh$1.material === undefined ) return;
  19404. // test with bounding sphere first
  19405. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19406. _sphere$3.copy( this.boundingSphere );
  19407. _sphere$3.applyMatrix4( matrixWorld );
  19408. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  19409. // now test each instance
  19410. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19411. // calculate the world matrix for each instance
  19412. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19413. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19414. // the mesh represents this single instance
  19415. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19416. _mesh$1.raycast( raycaster, _instanceIntersects );
  19417. // process the result of raycast
  19418. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19419. const intersect = _instanceIntersects[ i ];
  19420. intersect.instanceId = instanceId;
  19421. intersect.object = this;
  19422. intersects.push( intersect );
  19423. }
  19424. _instanceIntersects.length = 0;
  19425. }
  19426. }
  19427. setColorAt( index, color ) {
  19428. if ( this.instanceColor === null ) {
  19429. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19430. }
  19431. color.toArray( this.instanceColor.array, index * 3 );
  19432. }
  19433. setMatrixAt( index, matrix ) {
  19434. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19435. }
  19436. updateMorphTargets() {
  19437. }
  19438. dispose() {
  19439. this.dispatchEvent( { type: 'dispose' } );
  19440. }
  19441. }
  19442. function sortOpaque( a, b ) {
  19443. return a.z - b.z;
  19444. }
  19445. function sortTransparent( a, b ) {
  19446. return b.z - a.z;
  19447. }
  19448. class MultiDrawRenderList {
  19449. constructor() {
  19450. this.index = 0;
  19451. this.pool = [];
  19452. this.list = [];
  19453. }
  19454. push( drawRange, z ) {
  19455. const pool = this.pool;
  19456. const list = this.list;
  19457. if ( this.index >= pool.length ) {
  19458. pool.push( {
  19459. start: - 1,
  19460. count: - 1,
  19461. z: - 1,
  19462. } );
  19463. }
  19464. const item = pool[ this.index ];
  19465. list.push( item );
  19466. this.index ++;
  19467. item.start = drawRange.start;
  19468. item.count = drawRange.count;
  19469. item.z = z;
  19470. }
  19471. reset() {
  19472. this.list.length = 0;
  19473. this.index = 0;
  19474. }
  19475. }
  19476. const ID_ATTR_NAME = 'batchId';
  19477. const _matrix = /*@__PURE__*/ new Matrix4();
  19478. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  19479. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  19480. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19481. const _frustum = /*@__PURE__*/ new Frustum();
  19482. const _box$1 = /*@__PURE__*/ new Box3();
  19483. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19484. const _vector$5 = /*@__PURE__*/ new Vector3();
  19485. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19486. const _mesh = /*@__PURE__*/ new Mesh();
  19487. const _batchIntersects = [];
  19488. // @TODO: SkinnedMesh support?
  19489. // @TODO: geometry.groups support?
  19490. // @TODO: geometry.drawRange support?
  19491. // @TODO: geometry.morphAttributes support?
  19492. // @TODO: Support uniform parameter per geometry
  19493. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  19494. // copies data from attribute "src" into "target" starting at "targetOffset"
  19495. function copyAttributeData( src, target, targetOffset = 0 ) {
  19496. const itemSize = target.itemSize;
  19497. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19498. // use the component getters and setters if the array data cannot
  19499. // be copied directly
  19500. const vertexCount = src.count;
  19501. for ( let i = 0; i < vertexCount; i ++ ) {
  19502. for ( let c = 0; c < itemSize; c ++ ) {
  19503. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19504. }
  19505. }
  19506. } else {
  19507. // faster copy approach using typed array set function
  19508. target.array.set( src.array, targetOffset * itemSize );
  19509. }
  19510. target.needsUpdate = true;
  19511. }
  19512. class BatchedMesh extends Mesh {
  19513. get maxGeometryCount() {
  19514. return this._maxGeometryCount;
  19515. }
  19516. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19517. super( new BufferGeometry(), material );
  19518. this.isBatchedMesh = true;
  19519. this.perObjectFrustumCulled = true;
  19520. this.sortObjects = true;
  19521. this.boundingBox = null;
  19522. this.boundingSphere = null;
  19523. this.customSort = null;
  19524. this._drawRanges = [];
  19525. this._reservedRanges = [];
  19526. this._visibility = [];
  19527. this._active = [];
  19528. this._bounds = [];
  19529. this._maxGeometryCount = maxGeometryCount;
  19530. this._maxVertexCount = maxVertexCount;
  19531. this._maxIndexCount = maxIndexCount;
  19532. this._geometryInitialized = false;
  19533. this._geometryCount = 0;
  19534. this._multiDrawCounts = new Int32Array( maxGeometryCount );
  19535. this._multiDrawStarts = new Int32Array( maxGeometryCount );
  19536. this._multiDrawCount = 0;
  19537. this._visibilityChanged = true;
  19538. // Local matrix per geometry by using data texture
  19539. this._matricesTexture = null;
  19540. this._initMatricesTexture();
  19541. }
  19542. _initMatricesTexture() {
  19543. // layout (1 matrix = 4 pixels)
  19544. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19545. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19546. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19547. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19548. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19549. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  19550. size = Math.ceil( size / 4 ) * 4;
  19551. size = Math.max( size, 4 );
  19552. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19553. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19554. this._matricesTexture = matricesTexture;
  19555. }
  19556. _initializeGeometry( reference ) {
  19557. const geometry = this.geometry;
  19558. const maxVertexCount = this._maxVertexCount;
  19559. const maxGeometryCount = this._maxGeometryCount;
  19560. const maxIndexCount = this._maxIndexCount;
  19561. if ( this._geometryInitialized === false ) {
  19562. for ( const attributeName in reference.attributes ) {
  19563. const srcAttribute = reference.getAttribute( attributeName );
  19564. const { array, itemSize, normalized } = srcAttribute;
  19565. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19566. const dstAttribute = new srcAttribute.constructor( dstArray, itemSize, normalized );
  19567. dstAttribute.setUsage( srcAttribute.usage );
  19568. geometry.setAttribute( attributeName, dstAttribute );
  19569. }
  19570. if ( reference.getIndex() !== null ) {
  19571. const indexArray = maxVertexCount > 65536
  19572. ? new Uint32Array( maxIndexCount )
  19573. : new Uint16Array( maxIndexCount );
  19574. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19575. }
  19576. const idArray = maxGeometryCount > 65536
  19577. ? new Uint32Array( maxVertexCount )
  19578. : new Uint16Array( maxVertexCount );
  19579. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  19580. this._geometryInitialized = true;
  19581. }
  19582. }
  19583. // Make sure the geometry is compatible with the existing combined geometry atributes
  19584. _validateGeometry( geometry ) {
  19585. // check that the geometry doesn't have a version of our reserved id attribute
  19586. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  19587. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  19588. }
  19589. // check to ensure the geometries are using consistent attributes and indices
  19590. const batchGeometry = this.geometry;
  19591. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19592. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  19593. }
  19594. for ( const attributeName in batchGeometry.attributes ) {
  19595. if ( attributeName === ID_ATTR_NAME ) {
  19596. continue;
  19597. }
  19598. if ( ! geometry.hasAttribute( attributeName ) ) {
  19599. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19600. }
  19601. const srcAttribute = geometry.getAttribute( attributeName );
  19602. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19603. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19604. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19605. }
  19606. }
  19607. }
  19608. setCustomSort( func ) {
  19609. this.customSort = func;
  19610. return this;
  19611. }
  19612. computeBoundingBox() {
  19613. if ( this.boundingBox === null ) {
  19614. this.boundingBox = new Box3();
  19615. }
  19616. const geometryCount = this._geometryCount;
  19617. const boundingBox = this.boundingBox;
  19618. const active = this._active;
  19619. boundingBox.makeEmpty();
  19620. for ( let i = 0; i < geometryCount; i ++ ) {
  19621. if ( active[ i ] === false ) continue;
  19622. this.getMatrixAt( i, _matrix );
  19623. this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix );
  19624. boundingBox.union( _box$1 );
  19625. }
  19626. }
  19627. computeBoundingSphere() {
  19628. if ( this.boundingSphere === null ) {
  19629. this.boundingSphere = new Sphere();
  19630. }
  19631. const geometryCount = this._geometryCount;
  19632. const boundingSphere = this.boundingSphere;
  19633. const active = this._active;
  19634. boundingSphere.makeEmpty();
  19635. for ( let i = 0; i < geometryCount; i ++ ) {
  19636. if ( active[ i ] === false ) continue;
  19637. this.getMatrixAt( i, _matrix );
  19638. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix );
  19639. boundingSphere.union( _sphere$2 );
  19640. }
  19641. }
  19642. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  19643. this._initializeGeometry( geometry );
  19644. this._validateGeometry( geometry );
  19645. // ensure we're not over geometry
  19646. if ( this._geometryCount >= this._maxGeometryCount ) {
  19647. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19648. }
  19649. // get the necessary range fo the geometry
  19650. const reservedRange = {
  19651. vertexStart: - 1,
  19652. vertexCount: - 1,
  19653. indexStart: - 1,
  19654. indexCount: - 1,
  19655. };
  19656. let lastRange = null;
  19657. const reservedRanges = this._reservedRanges;
  19658. const drawRanges = this._drawRanges;
  19659. const bounds = this._bounds;
  19660. if ( this._geometryCount !== 0 ) {
  19661. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  19662. }
  19663. if ( vertexCount === - 1 ) {
  19664. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  19665. } else {
  19666. reservedRange.vertexCount = vertexCount;
  19667. }
  19668. if ( lastRange === null ) {
  19669. reservedRange.vertexStart = 0;
  19670. } else {
  19671. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  19672. }
  19673. const index = geometry.getIndex();
  19674. const hasIndex = index !== null;
  19675. if ( hasIndex ) {
  19676. if ( indexCount === - 1 ) {
  19677. reservedRange.indexCount = index.count;
  19678. } else {
  19679. reservedRange.indexCount = indexCount;
  19680. }
  19681. if ( lastRange === null ) {
  19682. reservedRange.indexStart = 0;
  19683. } else {
  19684. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  19685. }
  19686. }
  19687. if (
  19688. reservedRange.indexStart !== - 1 &&
  19689. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  19690. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  19691. ) {
  19692. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19693. }
  19694. const visibility = this._visibility;
  19695. const active = this._active;
  19696. const matricesTexture = this._matricesTexture;
  19697. const matricesArray = this._matricesTexture.image.data;
  19698. // push new visibility states
  19699. visibility.push( true );
  19700. active.push( true );
  19701. // update id
  19702. const geometryId = this._geometryCount;
  19703. this._geometryCount ++;
  19704. // initialize matrix information
  19705. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  19706. matricesTexture.needsUpdate = true;
  19707. // add the reserved range and draw range objects
  19708. reservedRanges.push( reservedRange );
  19709. drawRanges.push( {
  19710. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  19711. count: - 1
  19712. } );
  19713. bounds.push( {
  19714. boxInitialized: false,
  19715. box: new Box3(),
  19716. sphereInitialized: false,
  19717. sphere: new Sphere()
  19718. } );
  19719. // set the id for the geometry
  19720. const idAttribute = this.geometry.getAttribute( ID_ATTR_NAME );
  19721. for ( let i = 0; i < reservedRange.vertexCount; i ++ ) {
  19722. idAttribute.setX( reservedRange.vertexStart + i, geometryId );
  19723. }
  19724. idAttribute.needsUpdate = true;
  19725. // update the geometry
  19726. this.setGeometryAt( geometryId, geometry );
  19727. return geometryId;
  19728. }
  19729. setGeometryAt( id, geometry ) {
  19730. if ( id >= this._geometryCount ) {
  19731. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19732. }
  19733. this._validateGeometry( geometry );
  19734. const batchGeometry = this.geometry;
  19735. const hasIndex = batchGeometry.getIndex() !== null;
  19736. const dstIndex = batchGeometry.getIndex();
  19737. const srcIndex = geometry.getIndex();
  19738. const reservedRange = this._reservedRanges[ id ];
  19739. if (
  19740. hasIndex &&
  19741. srcIndex.count > reservedRange.indexCount ||
  19742. geometry.attributes.position.count > reservedRange.vertexCount
  19743. ) {
  19744. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  19745. }
  19746. // copy geometry over
  19747. const vertexStart = reservedRange.vertexStart;
  19748. const vertexCount = reservedRange.vertexCount;
  19749. for ( const attributeName in batchGeometry.attributes ) {
  19750. if ( attributeName === ID_ATTR_NAME ) {
  19751. continue;
  19752. }
  19753. // copy attribute data
  19754. const srcAttribute = geometry.getAttribute( attributeName );
  19755. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19756. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19757. // fill the rest in with zeroes
  19758. const itemSize = srcAttribute.itemSize;
  19759. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  19760. const index = vertexStart + i;
  19761. for ( let c = 0; c < itemSize; c ++ ) {
  19762. dstAttribute.setComponent( index, c, 0 );
  19763. }
  19764. }
  19765. dstAttribute.needsUpdate = true;
  19766. }
  19767. // copy index
  19768. if ( hasIndex ) {
  19769. const indexStart = reservedRange.indexStart;
  19770. // copy index data over
  19771. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19772. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19773. }
  19774. // fill the rest in with zeroes
  19775. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  19776. dstIndex.setX( indexStart + i, vertexStart );
  19777. }
  19778. dstIndex.needsUpdate = true;
  19779. }
  19780. // store the bounding boxes
  19781. const bound = this._bounds[ id ];
  19782. if ( geometry.boundingBox !== null ) {
  19783. bound.box.copy( geometry.boundingBox );
  19784. bound.boxInitialized = true;
  19785. } else {
  19786. bound.boxInitialized = false;
  19787. }
  19788. if ( geometry.boundingSphere !== null ) {
  19789. bound.sphere.copy( geometry.boundingSphere );
  19790. bound.sphereInitialized = true;
  19791. } else {
  19792. bound.sphereInitialized = false;
  19793. }
  19794. // set drawRange count
  19795. const drawRange = this._drawRanges[ id ];
  19796. const posAttr = geometry.getAttribute( 'position' );
  19797. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  19798. this._visibilityChanged = true;
  19799. return id;
  19800. }
  19801. deleteGeometry( geometryId ) {
  19802. // Note: User needs to call optimize() afterward to pack the data.
  19803. const active = this._active;
  19804. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  19805. return this;
  19806. }
  19807. active[ geometryId ] = false;
  19808. this._visibilityChanged = true;
  19809. return this;
  19810. }
  19811. // get bounding box and compute it if it doesn't exist
  19812. getBoundingBoxAt( id, target ) {
  19813. const active = this._active;
  19814. if ( active[ id ] === false ) {
  19815. return this;
  19816. }
  19817. // compute bounding box
  19818. const bound = this._bounds[ id ];
  19819. const box = bound.box;
  19820. const geometry = this.geometry;
  19821. if ( bound.boxInitialized === false ) {
  19822. box.makeEmpty();
  19823. const index = geometry.index;
  19824. const position = geometry.attributes.position;
  19825. const drawRange = this._drawRanges[ id ];
  19826. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  19827. let iv = i;
  19828. if ( index ) {
  19829. iv = index.getX( iv );
  19830. }
  19831. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19832. }
  19833. bound.boxInitialized = true;
  19834. }
  19835. target.copy( box );
  19836. return target;
  19837. }
  19838. // get bounding sphere and compute it if it doesn't exist
  19839. getBoundingSphereAt( id, target ) {
  19840. const active = this._active;
  19841. if ( active[ id ] === false ) {
  19842. return this;
  19843. }
  19844. // compute bounding sphere
  19845. const bound = this._bounds[ id ];
  19846. const sphere = bound.sphere;
  19847. const geometry = this.geometry;
  19848. if ( bound.sphereInitialized === false ) {
  19849. sphere.makeEmpty();
  19850. this.getBoundingBoxAt( id, _box$1 );
  19851. _box$1.getCenter( sphere.center );
  19852. const index = geometry.index;
  19853. const position = geometry.attributes.position;
  19854. const drawRange = this._drawRanges[ id ];
  19855. let maxRadiusSq = 0;
  19856. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  19857. let iv = i;
  19858. if ( index ) {
  19859. iv = index.getX( iv );
  19860. }
  19861. _vector$5.fromBufferAttribute( position, iv );
  19862. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19863. }
  19864. sphere.radius = Math.sqrt( maxRadiusSq );
  19865. bound.sphereInitialized = true;
  19866. }
  19867. target.copy( sphere );
  19868. return target;
  19869. }
  19870. setMatrixAt( geometryId, matrix ) {
  19871. // @TODO: Map geometryId to index of the arrays because
  19872. // optimize() can make geometryId mismatch the index
  19873. const active = this._active;
  19874. const matricesTexture = this._matricesTexture;
  19875. const matricesArray = this._matricesTexture.image.data;
  19876. const geometryCount = this._geometryCount;
  19877. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19878. return this;
  19879. }
  19880. matrix.toArray( matricesArray, geometryId * 16 );
  19881. matricesTexture.needsUpdate = true;
  19882. return this;
  19883. }
  19884. getMatrixAt( geometryId, matrix ) {
  19885. const active = this._active;
  19886. const matricesArray = this._matricesTexture.image.data;
  19887. const geometryCount = this._geometryCount;
  19888. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19889. return null;
  19890. }
  19891. return matrix.fromArray( matricesArray, geometryId * 16 );
  19892. }
  19893. setVisibleAt( geometryId, value ) {
  19894. const visibility = this._visibility;
  19895. const active = this._active;
  19896. const geometryCount = this._geometryCount;
  19897. // if the geometry is out of range, not active, or visibility state
  19898. // does not change then return early
  19899. if (
  19900. geometryId >= geometryCount ||
  19901. active[ geometryId ] === false ||
  19902. visibility[ geometryId ] === value
  19903. ) {
  19904. return this;
  19905. }
  19906. visibility[ geometryId ] = value;
  19907. this._visibilityChanged = true;
  19908. return this;
  19909. }
  19910. getVisibleAt( geometryId ) {
  19911. const visibility = this._visibility;
  19912. const active = this._active;
  19913. const geometryCount = this._geometryCount;
  19914. // return early if the geometry is out of range or not active
  19915. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19916. return false;
  19917. }
  19918. return visibility[ geometryId ];
  19919. }
  19920. raycast( raycaster, intersects ) {
  19921. const visibility = this._visibility;
  19922. const active = this._active;
  19923. const drawRanges = this._drawRanges;
  19924. const geometryCount = this._geometryCount;
  19925. const matrixWorld = this.matrixWorld;
  19926. const batchGeometry = this.geometry;
  19927. // iterate over each geometry
  19928. _mesh.material = this.material;
  19929. _mesh.geometry.index = batchGeometry.index;
  19930. _mesh.geometry.attributes = batchGeometry.attributes;
  19931. if ( _mesh.geometry.boundingBox === null ) {
  19932. _mesh.geometry.boundingBox = new Box3();
  19933. }
  19934. if ( _mesh.geometry.boundingSphere === null ) {
  19935. _mesh.geometry.boundingSphere = new Sphere();
  19936. }
  19937. for ( let i = 0; i < geometryCount; i ++ ) {
  19938. if ( ! visibility[ i ] || ! active[ i ] ) {
  19939. continue;
  19940. }
  19941. const drawRange = drawRanges[ i ];
  19942. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  19943. // ge the intersects
  19944. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  19945. this.getBoundingBoxAt( i, _mesh.geometry.boundingBox );
  19946. this.getBoundingSphereAt( i, _mesh.geometry.boundingSphere );
  19947. _mesh.raycast( raycaster, _batchIntersects );
  19948. // add batch id to the intersects
  19949. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  19950. const intersect = _batchIntersects[ j ];
  19951. intersect.object = this;
  19952. intersect.batchId = i;
  19953. intersects.push( intersect );
  19954. }
  19955. _batchIntersects.length = 0;
  19956. }
  19957. _mesh.material = null;
  19958. _mesh.geometry.index = null;
  19959. _mesh.geometry.attributes = {};
  19960. _mesh.geometry.setDrawRange( 0, Infinity );
  19961. }
  19962. copy( source ) {
  19963. super.copy( source );
  19964. this.geometry = source.geometry.clone();
  19965. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  19966. this.sortObjects = source.sortObjects;
  19967. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  19968. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  19969. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  19970. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  19971. this._visibility = source._visibility.slice();
  19972. this._active = source._active.slice();
  19973. this._bounds = source._bounds.map( bound => ( {
  19974. boxInitialized: bound.boxInitialized,
  19975. box: bound.box.clone(),
  19976. sphereInitialized: bound.sphereInitialized,
  19977. sphere: bound.sphere.clone()
  19978. } ) );
  19979. this._maxGeometryCount = source._maxGeometryCount;
  19980. this._maxVertexCount = source._maxVertexCount;
  19981. this._maxIndexCount = source._maxIndexCount;
  19982. this._geometryInitialized = source._geometryInitialized;
  19983. this._geometryCount = source._geometryCount;
  19984. this._multiDrawCounts = source._multiDrawCounts.slice();
  19985. this._multiDrawStarts = source._multiDrawStarts.slice();
  19986. this._matricesTexture = source._matricesTexture.clone();
  19987. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  19988. return this;
  19989. }
  19990. dispose() {
  19991. // Assuming the geometry is not shared with other meshes
  19992. this.geometry.dispose();
  19993. this._matricesTexture.dispose();
  19994. this._matricesTexture = null;
  19995. return this;
  19996. }
  19997. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  19998. // if visibility has not changed and frustum culling and object sorting is not required
  19999. // then skip iterating over all items
  20000. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20001. return;
  20002. }
  20003. // the indexed version of the multi draw function requires specifying the start
  20004. // offset in bytes.
  20005. const index = geometry.getIndex();
  20006. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20007. const visibility = this._visibility;
  20008. const multiDrawStarts = this._multiDrawStarts;
  20009. const multiDrawCounts = this._multiDrawCounts;
  20010. const drawRanges = this._drawRanges;
  20011. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20012. // prepare the frustum in the local frame
  20013. if ( perObjectFrustumCulled ) {
  20014. _projScreenMatrix$2
  20015. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20016. .multiply( this.matrixWorld );
  20017. _frustum.setFromProjectionMatrix(
  20018. _projScreenMatrix$2,
  20019. renderer.isWebGPURenderer ? WebGPUCoordinateSystem : WebGLCoordinateSystem
  20020. );
  20021. }
  20022. let count = 0;
  20023. if ( this.sortObjects ) {
  20024. // get the camera position in the local frame
  20025. _invMatrixWorld.copy( this.matrixWorld ).invert();
  20026. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  20027. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  20028. if ( visibility[ i ] ) {
  20029. // get the bounds in world space
  20030. this.getMatrixAt( i, _matrix );
  20031. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix );
  20032. // determine whether the batched geometry is within the frustum
  20033. let culled = false;
  20034. if ( perObjectFrustumCulled ) {
  20035. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20036. }
  20037. if ( ! culled ) {
  20038. // get the distance from camera used for sorting
  20039. const z = _vector$5.distanceTo( _sphere$2.center );
  20040. _renderList.push( drawRanges[ i ], z );
  20041. }
  20042. }
  20043. }
  20044. // Sort the draw ranges and prep for rendering
  20045. const list = _renderList.list;
  20046. const customSort = this.customSort;
  20047. if ( customSort === null ) {
  20048. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20049. } else {
  20050. customSort.call( this, list, camera );
  20051. }
  20052. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20053. const item = list[ i ];
  20054. multiDrawStarts[ count ] = item.start * bytesPerElement;
  20055. multiDrawCounts[ count ] = item.count;
  20056. count ++;
  20057. }
  20058. _renderList.reset();
  20059. } else {
  20060. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  20061. if ( visibility[ i ] ) {
  20062. // determine whether the batched geometry is within the frustum
  20063. let culled = false;
  20064. if ( perObjectFrustumCulled ) {
  20065. // get the bounds in world space
  20066. this.getMatrixAt( i, _matrix );
  20067. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix );
  20068. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20069. }
  20070. if ( ! culled ) {
  20071. const range = drawRanges[ i ];
  20072. multiDrawStarts[ count ] = range.start * bytesPerElement;
  20073. multiDrawCounts[ count ] = range.count;
  20074. count ++;
  20075. }
  20076. }
  20077. }
  20078. }
  20079. this._multiDrawCount = count;
  20080. this._visibilityChanged = false;
  20081. }
  20082. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20083. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20084. }
  20085. }
  20086. class LineBasicMaterial extends Material {
  20087. constructor( parameters ) {
  20088. super();
  20089. this.isLineBasicMaterial = true;
  20090. this.type = 'LineBasicMaterial';
  20091. this.color = new Color( 0xffffff );
  20092. this.map = null;
  20093. this.linewidth = 1;
  20094. this.linecap = 'round';
  20095. this.linejoin = 'round';
  20096. this.fog = true;
  20097. this.setValues( parameters );
  20098. }
  20099. copy( source ) {
  20100. super.copy( source );
  20101. this.color.copy( source.color );
  20102. this.map = source.map;
  20103. this.linewidth = source.linewidth;
  20104. this.linecap = source.linecap;
  20105. this.linejoin = source.linejoin;
  20106. this.fog = source.fog;
  20107. return this;
  20108. }
  20109. }
  20110. const _start$1 = /*@__PURE__*/ new Vector3();
  20111. const _end$1 = /*@__PURE__*/ new Vector3();
  20112. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20113. const _ray$1 = /*@__PURE__*/ new Ray();
  20114. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20115. class Line extends Object3D {
  20116. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20117. super();
  20118. this.isLine = true;
  20119. this.type = 'Line';
  20120. this.geometry = geometry;
  20121. this.material = material;
  20122. this.updateMorphTargets();
  20123. }
  20124. copy( source, recursive ) {
  20125. super.copy( source, recursive );
  20126. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20127. this.geometry = source.geometry;
  20128. return this;
  20129. }
  20130. computeLineDistances() {
  20131. const geometry = this.geometry;
  20132. // we assume non-indexed geometry
  20133. if ( geometry.index === null ) {
  20134. const positionAttribute = geometry.attributes.position;
  20135. const lineDistances = [ 0 ];
  20136. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20137. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  20138. _end$1.fromBufferAttribute( positionAttribute, i );
  20139. lineDistances[ i ] = lineDistances[ i - 1 ];
  20140. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  20141. }
  20142. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20143. } else {
  20144. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20145. }
  20146. return this;
  20147. }
  20148. raycast( raycaster, intersects ) {
  20149. const geometry = this.geometry;
  20150. const matrixWorld = this.matrixWorld;
  20151. const threshold = raycaster.params.Line.threshold;
  20152. const drawRange = geometry.drawRange;
  20153. // Checking boundingSphere distance to ray
  20154. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20155. _sphere$1.copy( geometry.boundingSphere );
  20156. _sphere$1.applyMatrix4( matrixWorld );
  20157. _sphere$1.radius += threshold;
  20158. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20159. //
  20160. _inverseMatrix$1.copy( matrixWorld ).invert();
  20161. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20162. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20163. const localThresholdSq = localThreshold * localThreshold;
  20164. const vStart = new Vector3();
  20165. const vEnd = new Vector3();
  20166. const interSegment = new Vector3();
  20167. const interRay = new Vector3();
  20168. const step = this.isLineSegments ? 2 : 1;
  20169. const index = geometry.index;
  20170. const attributes = geometry.attributes;
  20171. const positionAttribute = attributes.position;
  20172. if ( index !== null ) {
  20173. const start = Math.max( 0, drawRange.start );
  20174. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20175. for ( let i = start, l = end - 1; i < l; i += step ) {
  20176. const a = index.getX( i );
  20177. const b = index.getX( i + 1 );
  20178. vStart.fromBufferAttribute( positionAttribute, a );
  20179. vEnd.fromBufferAttribute( positionAttribute, b );
  20180. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20181. if ( distSq > localThresholdSq ) continue;
  20182. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20183. const distance = raycaster.ray.origin.distanceTo( interRay );
  20184. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20185. intersects.push( {
  20186. distance: distance,
  20187. // What do we want? intersection point on the ray or on the segment??
  20188. // point: raycaster.ray.at( distance ),
  20189. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20190. index: i,
  20191. face: null,
  20192. faceIndex: null,
  20193. object: this
  20194. } );
  20195. }
  20196. } else {
  20197. const start = Math.max( 0, drawRange.start );
  20198. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20199. for ( let i = start, l = end - 1; i < l; i += step ) {
  20200. vStart.fromBufferAttribute( positionAttribute, i );
  20201. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  20202. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20203. if ( distSq > localThresholdSq ) continue;
  20204. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20205. const distance = raycaster.ray.origin.distanceTo( interRay );
  20206. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20207. intersects.push( {
  20208. distance: distance,
  20209. // What do we want? intersection point on the ray or on the segment??
  20210. // point: raycaster.ray.at( distance ),
  20211. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20212. index: i,
  20213. face: null,
  20214. faceIndex: null,
  20215. object: this
  20216. } );
  20217. }
  20218. }
  20219. }
  20220. updateMorphTargets() {
  20221. const geometry = this.geometry;
  20222. const morphAttributes = geometry.morphAttributes;
  20223. const keys = Object.keys( morphAttributes );
  20224. if ( keys.length > 0 ) {
  20225. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20226. if ( morphAttribute !== undefined ) {
  20227. this.morphTargetInfluences = [];
  20228. this.morphTargetDictionary = {};
  20229. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20230. const name = morphAttribute[ m ].name || String( m );
  20231. this.morphTargetInfluences.push( 0 );
  20232. this.morphTargetDictionary[ name ] = m;
  20233. }
  20234. }
  20235. }
  20236. }
  20237. }
  20238. const _start = /*@__PURE__*/ new Vector3();
  20239. const _end = /*@__PURE__*/ new Vector3();
  20240. class LineSegments extends Line {
  20241. constructor( geometry, material ) {
  20242. super( geometry, material );
  20243. this.isLineSegments = true;
  20244. this.type = 'LineSegments';
  20245. }
  20246. computeLineDistances() {
  20247. const geometry = this.geometry;
  20248. // we assume non-indexed geometry
  20249. if ( geometry.index === null ) {
  20250. const positionAttribute = geometry.attributes.position;
  20251. const lineDistances = [];
  20252. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20253. _start.fromBufferAttribute( positionAttribute, i );
  20254. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20255. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20256. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20257. }
  20258. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20259. } else {
  20260. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20261. }
  20262. return this;
  20263. }
  20264. }
  20265. class LineLoop extends Line {
  20266. constructor( geometry, material ) {
  20267. super( geometry, material );
  20268. this.isLineLoop = true;
  20269. this.type = 'LineLoop';
  20270. }
  20271. }
  20272. class PointsMaterial extends Material {
  20273. constructor( parameters ) {
  20274. super();
  20275. this.isPointsMaterial = true;
  20276. this.type = 'PointsMaterial';
  20277. this.color = new Color( 0xffffff );
  20278. this.map = null;
  20279. this.alphaMap = null;
  20280. this.size = 1;
  20281. this.sizeAttenuation = true;
  20282. this.fog = true;
  20283. this.setValues( parameters );
  20284. }
  20285. copy( source ) {
  20286. super.copy( source );
  20287. this.color.copy( source.color );
  20288. this.map = source.map;
  20289. this.alphaMap = source.alphaMap;
  20290. this.size = source.size;
  20291. this.sizeAttenuation = source.sizeAttenuation;
  20292. this.fog = source.fog;
  20293. return this;
  20294. }
  20295. }
  20296. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20297. const _ray = /*@__PURE__*/ new Ray();
  20298. const _sphere = /*@__PURE__*/ new Sphere();
  20299. const _position$2 = /*@__PURE__*/ new Vector3();
  20300. class Points extends Object3D {
  20301. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20302. super();
  20303. this.isPoints = true;
  20304. this.type = 'Points';
  20305. this.geometry = geometry;
  20306. this.material = material;
  20307. this.updateMorphTargets();
  20308. }
  20309. copy( source, recursive ) {
  20310. super.copy( source, recursive );
  20311. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20312. this.geometry = source.geometry;
  20313. return this;
  20314. }
  20315. raycast( raycaster, intersects ) {
  20316. const geometry = this.geometry;
  20317. const matrixWorld = this.matrixWorld;
  20318. const threshold = raycaster.params.Points.threshold;
  20319. const drawRange = geometry.drawRange;
  20320. // Checking boundingSphere distance to ray
  20321. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20322. _sphere.copy( geometry.boundingSphere );
  20323. _sphere.applyMatrix4( matrixWorld );
  20324. _sphere.radius += threshold;
  20325. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20326. //
  20327. _inverseMatrix.copy( matrixWorld ).invert();
  20328. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20329. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20330. const localThresholdSq = localThreshold * localThreshold;
  20331. const index = geometry.index;
  20332. const attributes = geometry.attributes;
  20333. const positionAttribute = attributes.position;
  20334. if ( index !== null ) {
  20335. const start = Math.max( 0, drawRange.start );
  20336. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20337. for ( let i = start, il = end; i < il; i ++ ) {
  20338. const a = index.getX( i );
  20339. _position$2.fromBufferAttribute( positionAttribute, a );
  20340. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20341. }
  20342. } else {
  20343. const start = Math.max( 0, drawRange.start );
  20344. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20345. for ( let i = start, l = end; i < l; i ++ ) {
  20346. _position$2.fromBufferAttribute( positionAttribute, i );
  20347. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20348. }
  20349. }
  20350. }
  20351. updateMorphTargets() {
  20352. const geometry = this.geometry;
  20353. const morphAttributes = geometry.morphAttributes;
  20354. const keys = Object.keys( morphAttributes );
  20355. if ( keys.length > 0 ) {
  20356. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20357. if ( morphAttribute !== undefined ) {
  20358. this.morphTargetInfluences = [];
  20359. this.morphTargetDictionary = {};
  20360. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20361. const name = morphAttribute[ m ].name || String( m );
  20362. this.morphTargetInfluences.push( 0 );
  20363. this.morphTargetDictionary[ name ] = m;
  20364. }
  20365. }
  20366. }
  20367. }
  20368. }
  20369. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20370. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20371. if ( rayPointDistanceSq < localThresholdSq ) {
  20372. const intersectPoint = new Vector3();
  20373. _ray.closestPointToPoint( point, intersectPoint );
  20374. intersectPoint.applyMatrix4( matrixWorld );
  20375. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20376. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20377. intersects.push( {
  20378. distance: distance,
  20379. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20380. point: intersectPoint,
  20381. index: index,
  20382. face: null,
  20383. object: object
  20384. } );
  20385. }
  20386. }
  20387. class VideoTexture extends Texture {
  20388. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20389. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20390. this.isVideoTexture = true;
  20391. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20392. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20393. this.generateMipmaps = false;
  20394. const scope = this;
  20395. function updateVideo() {
  20396. scope.needsUpdate = true;
  20397. video.requestVideoFrameCallback( updateVideo );
  20398. }
  20399. if ( 'requestVideoFrameCallback' in video ) {
  20400. video.requestVideoFrameCallback( updateVideo );
  20401. }
  20402. }
  20403. clone() {
  20404. return new this.constructor( this.image ).copy( this );
  20405. }
  20406. update() {
  20407. const video = this.image;
  20408. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20409. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20410. this.needsUpdate = true;
  20411. }
  20412. }
  20413. }
  20414. class FramebufferTexture extends Texture {
  20415. constructor( width, height ) {
  20416. super( { width, height } );
  20417. this.isFramebufferTexture = true;
  20418. this.magFilter = NearestFilter;
  20419. this.minFilter = NearestFilter;
  20420. this.generateMipmaps = false;
  20421. this.needsUpdate = true;
  20422. }
  20423. }
  20424. class CompressedTexture extends Texture {
  20425. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20426. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20427. this.isCompressedTexture = true;
  20428. this.image = { width: width, height: height };
  20429. this.mipmaps = mipmaps;
  20430. // no flipping for cube textures
  20431. // (also flipping doesn't work for compressed textures )
  20432. this.flipY = false;
  20433. // can't generate mipmaps for compressed textures
  20434. // mips must be embedded in DDS files
  20435. this.generateMipmaps = false;
  20436. }
  20437. }
  20438. class CompressedArrayTexture extends CompressedTexture {
  20439. constructor( mipmaps, width, height, depth, format, type ) {
  20440. super( mipmaps, width, height, format, type );
  20441. this.isCompressedArrayTexture = true;
  20442. this.image.depth = depth;
  20443. this.wrapR = ClampToEdgeWrapping;
  20444. }
  20445. }
  20446. class CompressedCubeTexture extends CompressedTexture {
  20447. constructor( images, format, type ) {
  20448. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  20449. this.isCompressedCubeTexture = true;
  20450. this.isCubeTexture = true;
  20451. this.image = images;
  20452. }
  20453. }
  20454. class CanvasTexture extends Texture {
  20455. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20456. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20457. this.isCanvasTexture = true;
  20458. this.needsUpdate = true;
  20459. }
  20460. }
  20461. /**
  20462. * Extensible curve object.
  20463. *
  20464. * Some common of curve methods:
  20465. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20466. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20467. * .getPoints(), .getSpacedPoints()
  20468. * .getLength()
  20469. * .updateArcLengths()
  20470. *
  20471. * This following curves inherit from THREE.Curve:
  20472. *
  20473. * -- 2D curves --
  20474. * THREE.ArcCurve
  20475. * THREE.CubicBezierCurve
  20476. * THREE.EllipseCurve
  20477. * THREE.LineCurve
  20478. * THREE.QuadraticBezierCurve
  20479. * THREE.SplineCurve
  20480. *
  20481. * -- 3D curves --
  20482. * THREE.CatmullRomCurve3
  20483. * THREE.CubicBezierCurve3
  20484. * THREE.LineCurve3
  20485. * THREE.QuadraticBezierCurve3
  20486. *
  20487. * A series of curves can be represented as a THREE.CurvePath.
  20488. *
  20489. **/
  20490. class Curve {
  20491. constructor() {
  20492. this.type = 'Curve';
  20493. this.arcLengthDivisions = 200;
  20494. }
  20495. // Virtual base class method to overwrite and implement in subclasses
  20496. // - t [0 .. 1]
  20497. getPoint( /* t, optionalTarget */ ) {
  20498. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20499. return null;
  20500. }
  20501. // Get point at relative position in curve according to arc length
  20502. // - u [0 .. 1]
  20503. getPointAt( u, optionalTarget ) {
  20504. const t = this.getUtoTmapping( u );
  20505. return this.getPoint( t, optionalTarget );
  20506. }
  20507. // Get sequence of points using getPoint( t )
  20508. getPoints( divisions = 5 ) {
  20509. const points = [];
  20510. for ( let d = 0; d <= divisions; d ++ ) {
  20511. points.push( this.getPoint( d / divisions ) );
  20512. }
  20513. return points;
  20514. }
  20515. // Get sequence of points using getPointAt( u )
  20516. getSpacedPoints( divisions = 5 ) {
  20517. const points = [];
  20518. for ( let d = 0; d <= divisions; d ++ ) {
  20519. points.push( this.getPointAt( d / divisions ) );
  20520. }
  20521. return points;
  20522. }
  20523. // Get total curve arc length
  20524. getLength() {
  20525. const lengths = this.getLengths();
  20526. return lengths[ lengths.length - 1 ];
  20527. }
  20528. // Get list of cumulative segment lengths
  20529. getLengths( divisions = this.arcLengthDivisions ) {
  20530. if ( this.cacheArcLengths &&
  20531. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20532. ! this.needsUpdate ) {
  20533. return this.cacheArcLengths;
  20534. }
  20535. this.needsUpdate = false;
  20536. const cache = [];
  20537. let current, last = this.getPoint( 0 );
  20538. let sum = 0;
  20539. cache.push( 0 );
  20540. for ( let p = 1; p <= divisions; p ++ ) {
  20541. current = this.getPoint( p / divisions );
  20542. sum += current.distanceTo( last );
  20543. cache.push( sum );
  20544. last = current;
  20545. }
  20546. this.cacheArcLengths = cache;
  20547. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20548. }
  20549. updateArcLengths() {
  20550. this.needsUpdate = true;
  20551. this.getLengths();
  20552. }
  20553. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20554. getUtoTmapping( u, distance ) {
  20555. const arcLengths = this.getLengths();
  20556. let i = 0;
  20557. const il = arcLengths.length;
  20558. let targetArcLength; // The targeted u distance value to get
  20559. if ( distance ) {
  20560. targetArcLength = distance;
  20561. } else {
  20562. targetArcLength = u * arcLengths[ il - 1 ];
  20563. }
  20564. // binary search for the index with largest value smaller than target u distance
  20565. let low = 0, high = il - 1, comparison;
  20566. while ( low <= high ) {
  20567. 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
  20568. comparison = arcLengths[ i ] - targetArcLength;
  20569. if ( comparison < 0 ) {
  20570. low = i + 1;
  20571. } else if ( comparison > 0 ) {
  20572. high = i - 1;
  20573. } else {
  20574. high = i;
  20575. break;
  20576. // DONE
  20577. }
  20578. }
  20579. i = high;
  20580. if ( arcLengths[ i ] === targetArcLength ) {
  20581. return i / ( il - 1 );
  20582. }
  20583. // we could get finer grain at lengths, or use simple interpolation between two points
  20584. const lengthBefore = arcLengths[ i ];
  20585. const lengthAfter = arcLengths[ i + 1 ];
  20586. const segmentLength = lengthAfter - lengthBefore;
  20587. // determine where we are between the 'before' and 'after' points
  20588. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20589. // add that fractional amount to t
  20590. const t = ( i + segmentFraction ) / ( il - 1 );
  20591. return t;
  20592. }
  20593. // Returns a unit vector tangent at t
  20594. // In case any sub curve does not implement its tangent derivation,
  20595. // 2 points a small delta apart will be used to find its gradient
  20596. // which seems to give a reasonable approximation
  20597. getTangent( t, optionalTarget ) {
  20598. const delta = 0.0001;
  20599. let t1 = t - delta;
  20600. let t2 = t + delta;
  20601. // Capping in case of danger
  20602. if ( t1 < 0 ) t1 = 0;
  20603. if ( t2 > 1 ) t2 = 1;
  20604. const pt1 = this.getPoint( t1 );
  20605. const pt2 = this.getPoint( t2 );
  20606. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  20607. tangent.copy( pt2 ).sub( pt1 ).normalize();
  20608. return tangent;
  20609. }
  20610. getTangentAt( u, optionalTarget ) {
  20611. const t = this.getUtoTmapping( u );
  20612. return this.getTangent( t, optionalTarget );
  20613. }
  20614. computeFrenetFrames( segments, closed ) {
  20615. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20616. const normal = new Vector3();
  20617. const tangents = [];
  20618. const normals = [];
  20619. const binormals = [];
  20620. const vec = new Vector3();
  20621. const mat = new Matrix4();
  20622. // compute the tangent vectors for each segment on the curve
  20623. for ( let i = 0; i <= segments; i ++ ) {
  20624. const u = i / segments;
  20625. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  20626. }
  20627. // select an initial normal vector perpendicular to the first tangent vector,
  20628. // and in the direction of the minimum tangent xyz component
  20629. normals[ 0 ] = new Vector3();
  20630. binormals[ 0 ] = new Vector3();
  20631. let min = Number.MAX_VALUE;
  20632. const tx = Math.abs( tangents[ 0 ].x );
  20633. const ty = Math.abs( tangents[ 0 ].y );
  20634. const tz = Math.abs( tangents[ 0 ].z );
  20635. if ( tx <= min ) {
  20636. min = tx;
  20637. normal.set( 1, 0, 0 );
  20638. }
  20639. if ( ty <= min ) {
  20640. min = ty;
  20641. normal.set( 0, 1, 0 );
  20642. }
  20643. if ( tz <= min ) {
  20644. normal.set( 0, 0, 1 );
  20645. }
  20646. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20647. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20648. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20649. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20650. for ( let i = 1; i <= segments; i ++ ) {
  20651. normals[ i ] = normals[ i - 1 ].clone();
  20652. binormals[ i ] = binormals[ i - 1 ].clone();
  20653. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20654. if ( vec.length() > Number.EPSILON ) {
  20655. vec.normalize();
  20656. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20657. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20658. }
  20659. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20660. }
  20661. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20662. if ( closed === true ) {
  20663. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20664. theta /= segments;
  20665. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20666. theta = - theta;
  20667. }
  20668. for ( let i = 1; i <= segments; i ++ ) {
  20669. // twist a little...
  20670. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20671. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20672. }
  20673. }
  20674. return {
  20675. tangents: tangents,
  20676. normals: normals,
  20677. binormals: binormals
  20678. };
  20679. }
  20680. clone() {
  20681. return new this.constructor().copy( this );
  20682. }
  20683. copy( source ) {
  20684. this.arcLengthDivisions = source.arcLengthDivisions;
  20685. return this;
  20686. }
  20687. toJSON() {
  20688. const data = {
  20689. metadata: {
  20690. version: 4.6,
  20691. type: 'Curve',
  20692. generator: 'Curve.toJSON'
  20693. }
  20694. };
  20695. data.arcLengthDivisions = this.arcLengthDivisions;
  20696. data.type = this.type;
  20697. return data;
  20698. }
  20699. fromJSON( json ) {
  20700. this.arcLengthDivisions = json.arcLengthDivisions;
  20701. return this;
  20702. }
  20703. }
  20704. class EllipseCurve extends Curve {
  20705. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  20706. super();
  20707. this.isEllipseCurve = true;
  20708. this.type = 'EllipseCurve';
  20709. this.aX = aX;
  20710. this.aY = aY;
  20711. this.xRadius = xRadius;
  20712. this.yRadius = yRadius;
  20713. this.aStartAngle = aStartAngle;
  20714. this.aEndAngle = aEndAngle;
  20715. this.aClockwise = aClockwise;
  20716. this.aRotation = aRotation;
  20717. }
  20718. getPoint( t, optionalTarget ) {
  20719. const point = optionalTarget || new Vector2();
  20720. const twoPi = Math.PI * 2;
  20721. let deltaAngle = this.aEndAngle - this.aStartAngle;
  20722. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20723. // ensures that deltaAngle is 0 .. 2 PI
  20724. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20725. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20726. if ( deltaAngle < Number.EPSILON ) {
  20727. if ( samePoints ) {
  20728. deltaAngle = 0;
  20729. } else {
  20730. deltaAngle = twoPi;
  20731. }
  20732. }
  20733. if ( this.aClockwise === true && ! samePoints ) {
  20734. if ( deltaAngle === twoPi ) {
  20735. deltaAngle = - twoPi;
  20736. } else {
  20737. deltaAngle = deltaAngle - twoPi;
  20738. }
  20739. }
  20740. const angle = this.aStartAngle + t * deltaAngle;
  20741. let x = this.aX + this.xRadius * Math.cos( angle );
  20742. let y = this.aY + this.yRadius * Math.sin( angle );
  20743. if ( this.aRotation !== 0 ) {
  20744. const cos = Math.cos( this.aRotation );
  20745. const sin = Math.sin( this.aRotation );
  20746. const tx = x - this.aX;
  20747. const ty = y - this.aY;
  20748. // Rotate the point about the center of the ellipse.
  20749. x = tx * cos - ty * sin + this.aX;
  20750. y = tx * sin + ty * cos + this.aY;
  20751. }
  20752. return point.set( x, y );
  20753. }
  20754. copy( source ) {
  20755. super.copy( source );
  20756. this.aX = source.aX;
  20757. this.aY = source.aY;
  20758. this.xRadius = source.xRadius;
  20759. this.yRadius = source.yRadius;
  20760. this.aStartAngle = source.aStartAngle;
  20761. this.aEndAngle = source.aEndAngle;
  20762. this.aClockwise = source.aClockwise;
  20763. this.aRotation = source.aRotation;
  20764. return this;
  20765. }
  20766. toJSON() {
  20767. const data = super.toJSON();
  20768. data.aX = this.aX;
  20769. data.aY = this.aY;
  20770. data.xRadius = this.xRadius;
  20771. data.yRadius = this.yRadius;
  20772. data.aStartAngle = this.aStartAngle;
  20773. data.aEndAngle = this.aEndAngle;
  20774. data.aClockwise = this.aClockwise;
  20775. data.aRotation = this.aRotation;
  20776. return data;
  20777. }
  20778. fromJSON( json ) {
  20779. super.fromJSON( json );
  20780. this.aX = json.aX;
  20781. this.aY = json.aY;
  20782. this.xRadius = json.xRadius;
  20783. this.yRadius = json.yRadius;
  20784. this.aStartAngle = json.aStartAngle;
  20785. this.aEndAngle = json.aEndAngle;
  20786. this.aClockwise = json.aClockwise;
  20787. this.aRotation = json.aRotation;
  20788. return this;
  20789. }
  20790. }
  20791. class ArcCurve extends EllipseCurve {
  20792. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20793. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20794. this.isArcCurve = true;
  20795. this.type = 'ArcCurve';
  20796. }
  20797. }
  20798. /**
  20799. * Centripetal CatmullRom Curve - which is useful for avoiding
  20800. * cusps and self-intersections in non-uniform catmull rom curves.
  20801. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  20802. *
  20803. * curve.type accepts centripetal(default), chordal and catmullrom
  20804. * curve.tension is used for catmullrom which defaults to 0.5
  20805. */
  20806. /*
  20807. Based on an optimized c++ solution in
  20808. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  20809. - http://ideone.com/NoEbVM
  20810. This CubicPoly class could be used for reusing some variables and calculations,
  20811. but for three.js curve use, it could be possible inlined and flatten into a single function call
  20812. which can be placed in CurveUtils.
  20813. */
  20814. function CubicPoly() {
  20815. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  20816. /*
  20817. * Compute coefficients for a cubic polynomial
  20818. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  20819. * such that
  20820. * p(0) = x0, p(1) = x1
  20821. * and
  20822. * p'(0) = t0, p'(1) = t1.
  20823. */
  20824. function init( x0, x1, t0, t1 ) {
  20825. c0 = x0;
  20826. c1 = t0;
  20827. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  20828. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  20829. }
  20830. return {
  20831. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  20832. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  20833. },
  20834. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  20835. // compute tangents when parameterized in [t1,t2]
  20836. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  20837. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  20838. // rescale tangents for parametrization in [0,1]
  20839. t1 *= dt1;
  20840. t2 *= dt1;
  20841. init( x1, x2, t1, t2 );
  20842. },
  20843. calc: function ( t ) {
  20844. const t2 = t * t;
  20845. const t3 = t2 * t;
  20846. return c0 + c1 * t + c2 * t2 + c3 * t3;
  20847. }
  20848. };
  20849. }
  20850. //
  20851. const tmp = /*@__PURE__*/ new Vector3();
  20852. const px = /*@__PURE__*/ new CubicPoly();
  20853. const py = /*@__PURE__*/ new CubicPoly();
  20854. const pz = /*@__PURE__*/ new CubicPoly();
  20855. class CatmullRomCurve3 extends Curve {
  20856. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  20857. super();
  20858. this.isCatmullRomCurve3 = true;
  20859. this.type = 'CatmullRomCurve3';
  20860. this.points = points;
  20861. this.closed = closed;
  20862. this.curveType = curveType;
  20863. this.tension = tension;
  20864. }
  20865. getPoint( t, optionalTarget = new Vector3() ) {
  20866. const point = optionalTarget;
  20867. const points = this.points;
  20868. const l = points.length;
  20869. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  20870. let intPoint = Math.floor( p );
  20871. let weight = p - intPoint;
  20872. if ( this.closed ) {
  20873. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  20874. } else if ( weight === 0 && intPoint === l - 1 ) {
  20875. intPoint = l - 2;
  20876. weight = 1;
  20877. }
  20878. let p0, p3; // 4 points (p1 & p2 defined below)
  20879. if ( this.closed || intPoint > 0 ) {
  20880. p0 = points[ ( intPoint - 1 ) % l ];
  20881. } else {
  20882. // extrapolate first point
  20883. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  20884. p0 = tmp;
  20885. }
  20886. const p1 = points[ intPoint % l ];
  20887. const p2 = points[ ( intPoint + 1 ) % l ];
  20888. if ( this.closed || intPoint + 2 < l ) {
  20889. p3 = points[ ( intPoint + 2 ) % l ];
  20890. } else {
  20891. // extrapolate last point
  20892. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  20893. p3 = tmp;
  20894. }
  20895. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  20896. // init Centripetal / Chordal Catmull-Rom
  20897. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  20898. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  20899. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  20900. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  20901. // safety check for repeated points
  20902. if ( dt1 < 1e-4 ) dt1 = 1.0;
  20903. if ( dt0 < 1e-4 ) dt0 = dt1;
  20904. if ( dt2 < 1e-4 ) dt2 = dt1;
  20905. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  20906. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  20907. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  20908. } else if ( this.curveType === 'catmullrom' ) {
  20909. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  20910. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  20911. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  20912. }
  20913. point.set(
  20914. px.calc( weight ),
  20915. py.calc( weight ),
  20916. pz.calc( weight )
  20917. );
  20918. return point;
  20919. }
  20920. copy( source ) {
  20921. super.copy( source );
  20922. this.points = [];
  20923. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  20924. const point = source.points[ i ];
  20925. this.points.push( point.clone() );
  20926. }
  20927. this.closed = source.closed;
  20928. this.curveType = source.curveType;
  20929. this.tension = source.tension;
  20930. return this;
  20931. }
  20932. toJSON() {
  20933. const data = super.toJSON();
  20934. data.points = [];
  20935. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20936. const point = this.points[ i ];
  20937. data.points.push( point.toArray() );
  20938. }
  20939. data.closed = this.closed;
  20940. data.curveType = this.curveType;
  20941. data.tension = this.tension;
  20942. return data;
  20943. }
  20944. fromJSON( json ) {
  20945. super.fromJSON( json );
  20946. this.points = [];
  20947. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20948. const point = json.points[ i ];
  20949. this.points.push( new Vector3().fromArray( point ) );
  20950. }
  20951. this.closed = json.closed;
  20952. this.curveType = json.curveType;
  20953. this.tension = json.tension;
  20954. return this;
  20955. }
  20956. }
  20957. /**
  20958. * Bezier Curves formulas obtained from
  20959. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  20960. */
  20961. function CatmullRom( t, p0, p1, p2, p3 ) {
  20962. const v0 = ( p2 - p0 ) * 0.5;
  20963. const v1 = ( p3 - p1 ) * 0.5;
  20964. const t2 = t * t;
  20965. const t3 = t * t2;
  20966. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20967. }
  20968. //
  20969. function QuadraticBezierP0( t, p ) {
  20970. const k = 1 - t;
  20971. return k * k * p;
  20972. }
  20973. function QuadraticBezierP1( t, p ) {
  20974. return 2 * ( 1 - t ) * t * p;
  20975. }
  20976. function QuadraticBezierP2( t, p ) {
  20977. return t * t * p;
  20978. }
  20979. function QuadraticBezier( t, p0, p1, p2 ) {
  20980. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20981. QuadraticBezierP2( t, p2 );
  20982. }
  20983. //
  20984. function CubicBezierP0( t, p ) {
  20985. const k = 1 - t;
  20986. return k * k * k * p;
  20987. }
  20988. function CubicBezierP1( t, p ) {
  20989. const k = 1 - t;
  20990. return 3 * k * k * t * p;
  20991. }
  20992. function CubicBezierP2( t, p ) {
  20993. return 3 * ( 1 - t ) * t * t * p;
  20994. }
  20995. function CubicBezierP3( t, p ) {
  20996. return t * t * t * p;
  20997. }
  20998. function CubicBezier( t, p0, p1, p2, p3 ) {
  20999. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  21000. CubicBezierP3( t, p3 );
  21001. }
  21002. class CubicBezierCurve extends Curve {
  21003. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  21004. super();
  21005. this.isCubicBezierCurve = true;
  21006. this.type = 'CubicBezierCurve';
  21007. this.v0 = v0;
  21008. this.v1 = v1;
  21009. this.v2 = v2;
  21010. this.v3 = v3;
  21011. }
  21012. getPoint( t, optionalTarget = new Vector2() ) {
  21013. const point = optionalTarget;
  21014. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21015. point.set(
  21016. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21017. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21018. );
  21019. return point;
  21020. }
  21021. copy( source ) {
  21022. super.copy( source );
  21023. this.v0.copy( source.v0 );
  21024. this.v1.copy( source.v1 );
  21025. this.v2.copy( source.v2 );
  21026. this.v3.copy( source.v3 );
  21027. return this;
  21028. }
  21029. toJSON() {
  21030. const data = super.toJSON();
  21031. data.v0 = this.v0.toArray();
  21032. data.v1 = this.v1.toArray();
  21033. data.v2 = this.v2.toArray();
  21034. data.v3 = this.v3.toArray();
  21035. return data;
  21036. }
  21037. fromJSON( json ) {
  21038. super.fromJSON( json );
  21039. this.v0.fromArray( json.v0 );
  21040. this.v1.fromArray( json.v1 );
  21041. this.v2.fromArray( json.v2 );
  21042. this.v3.fromArray( json.v3 );
  21043. return this;
  21044. }
  21045. }
  21046. class CubicBezierCurve3 extends Curve {
  21047. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  21048. super();
  21049. this.isCubicBezierCurve3 = true;
  21050. this.type = 'CubicBezierCurve3';
  21051. this.v0 = v0;
  21052. this.v1 = v1;
  21053. this.v2 = v2;
  21054. this.v3 = v3;
  21055. }
  21056. getPoint( t, optionalTarget = new Vector3() ) {
  21057. const point = optionalTarget;
  21058. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21059. point.set(
  21060. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21061. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  21062. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  21063. );
  21064. return point;
  21065. }
  21066. copy( source ) {
  21067. super.copy( source );
  21068. this.v0.copy( source.v0 );
  21069. this.v1.copy( source.v1 );
  21070. this.v2.copy( source.v2 );
  21071. this.v3.copy( source.v3 );
  21072. return this;
  21073. }
  21074. toJSON() {
  21075. const data = super.toJSON();
  21076. data.v0 = this.v0.toArray();
  21077. data.v1 = this.v1.toArray();
  21078. data.v2 = this.v2.toArray();
  21079. data.v3 = this.v3.toArray();
  21080. return data;
  21081. }
  21082. fromJSON( json ) {
  21083. super.fromJSON( json );
  21084. this.v0.fromArray( json.v0 );
  21085. this.v1.fromArray( json.v1 );
  21086. this.v2.fromArray( json.v2 );
  21087. this.v3.fromArray( json.v3 );
  21088. return this;
  21089. }
  21090. }
  21091. class LineCurve extends Curve {
  21092. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  21093. super();
  21094. this.isLineCurve = true;
  21095. this.type = 'LineCurve';
  21096. this.v1 = v1;
  21097. this.v2 = v2;
  21098. }
  21099. getPoint( t, optionalTarget = new Vector2() ) {
  21100. const point = optionalTarget;
  21101. if ( t === 1 ) {
  21102. point.copy( this.v2 );
  21103. } else {
  21104. point.copy( this.v2 ).sub( this.v1 );
  21105. point.multiplyScalar( t ).add( this.v1 );
  21106. }
  21107. return point;
  21108. }
  21109. // Line curve is linear, so we can overwrite default getPointAt
  21110. getPointAt( u, optionalTarget ) {
  21111. return this.getPoint( u, optionalTarget );
  21112. }
  21113. getTangent( t, optionalTarget = new Vector2() ) {
  21114. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21115. }
  21116. getTangentAt( u, optionalTarget ) {
  21117. return this.getTangent( u, optionalTarget );
  21118. }
  21119. copy( source ) {
  21120. super.copy( source );
  21121. this.v1.copy( source.v1 );
  21122. this.v2.copy( source.v2 );
  21123. return this;
  21124. }
  21125. toJSON() {
  21126. const data = super.toJSON();
  21127. data.v1 = this.v1.toArray();
  21128. data.v2 = this.v2.toArray();
  21129. return data;
  21130. }
  21131. fromJSON( json ) {
  21132. super.fromJSON( json );
  21133. this.v1.fromArray( json.v1 );
  21134. this.v2.fromArray( json.v2 );
  21135. return this;
  21136. }
  21137. }
  21138. class LineCurve3 extends Curve {
  21139. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21140. super();
  21141. this.isLineCurve3 = true;
  21142. this.type = 'LineCurve3';
  21143. this.v1 = v1;
  21144. this.v2 = v2;
  21145. }
  21146. getPoint( t, optionalTarget = new Vector3() ) {
  21147. const point = optionalTarget;
  21148. if ( t === 1 ) {
  21149. point.copy( this.v2 );
  21150. } else {
  21151. point.copy( this.v2 ).sub( this.v1 );
  21152. point.multiplyScalar( t ).add( this.v1 );
  21153. }
  21154. return point;
  21155. }
  21156. // Line curve is linear, so we can overwrite default getPointAt
  21157. getPointAt( u, optionalTarget ) {
  21158. return this.getPoint( u, optionalTarget );
  21159. }
  21160. getTangent( t, optionalTarget = new Vector3() ) {
  21161. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21162. }
  21163. getTangentAt( u, optionalTarget ) {
  21164. return this.getTangent( u, optionalTarget );
  21165. }
  21166. copy( source ) {
  21167. super.copy( source );
  21168. this.v1.copy( source.v1 );
  21169. this.v2.copy( source.v2 );
  21170. return this;
  21171. }
  21172. toJSON() {
  21173. const data = super.toJSON();
  21174. data.v1 = this.v1.toArray();
  21175. data.v2 = this.v2.toArray();
  21176. return data;
  21177. }
  21178. fromJSON( json ) {
  21179. super.fromJSON( json );
  21180. this.v1.fromArray( json.v1 );
  21181. this.v2.fromArray( json.v2 );
  21182. return this;
  21183. }
  21184. }
  21185. class QuadraticBezierCurve extends Curve {
  21186. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21187. super();
  21188. this.isQuadraticBezierCurve = true;
  21189. this.type = 'QuadraticBezierCurve';
  21190. this.v0 = v0;
  21191. this.v1 = v1;
  21192. this.v2 = v2;
  21193. }
  21194. getPoint( t, optionalTarget = new Vector2() ) {
  21195. const point = optionalTarget;
  21196. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21197. point.set(
  21198. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21199. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21200. );
  21201. return point;
  21202. }
  21203. copy( source ) {
  21204. super.copy( source );
  21205. this.v0.copy( source.v0 );
  21206. this.v1.copy( source.v1 );
  21207. this.v2.copy( source.v2 );
  21208. return this;
  21209. }
  21210. toJSON() {
  21211. const data = super.toJSON();
  21212. data.v0 = this.v0.toArray();
  21213. data.v1 = this.v1.toArray();
  21214. data.v2 = this.v2.toArray();
  21215. return data;
  21216. }
  21217. fromJSON( json ) {
  21218. super.fromJSON( json );
  21219. this.v0.fromArray( json.v0 );
  21220. this.v1.fromArray( json.v1 );
  21221. this.v2.fromArray( json.v2 );
  21222. return this;
  21223. }
  21224. }
  21225. class QuadraticBezierCurve3 extends Curve {
  21226. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21227. super();
  21228. this.isQuadraticBezierCurve3 = true;
  21229. this.type = 'QuadraticBezierCurve3';
  21230. this.v0 = v0;
  21231. this.v1 = v1;
  21232. this.v2 = v2;
  21233. }
  21234. getPoint( t, optionalTarget = new Vector3() ) {
  21235. const point = optionalTarget;
  21236. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21237. point.set(
  21238. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21239. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21240. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21241. );
  21242. return point;
  21243. }
  21244. copy( source ) {
  21245. super.copy( source );
  21246. this.v0.copy( source.v0 );
  21247. this.v1.copy( source.v1 );
  21248. this.v2.copy( source.v2 );
  21249. return this;
  21250. }
  21251. toJSON() {
  21252. const data = super.toJSON();
  21253. data.v0 = this.v0.toArray();
  21254. data.v1 = this.v1.toArray();
  21255. data.v2 = this.v2.toArray();
  21256. return data;
  21257. }
  21258. fromJSON( json ) {
  21259. super.fromJSON( json );
  21260. this.v0.fromArray( json.v0 );
  21261. this.v1.fromArray( json.v1 );
  21262. this.v2.fromArray( json.v2 );
  21263. return this;
  21264. }
  21265. }
  21266. class SplineCurve extends Curve {
  21267. constructor( points = [] ) {
  21268. super();
  21269. this.isSplineCurve = true;
  21270. this.type = 'SplineCurve';
  21271. this.points = points;
  21272. }
  21273. getPoint( t, optionalTarget = new Vector2() ) {
  21274. const point = optionalTarget;
  21275. const points = this.points;
  21276. const p = ( points.length - 1 ) * t;
  21277. const intPoint = Math.floor( p );
  21278. const weight = p - intPoint;
  21279. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21280. const p1 = points[ intPoint ];
  21281. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21282. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21283. point.set(
  21284. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21285. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21286. );
  21287. return point;
  21288. }
  21289. copy( source ) {
  21290. super.copy( source );
  21291. this.points = [];
  21292. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21293. const point = source.points[ i ];
  21294. this.points.push( point.clone() );
  21295. }
  21296. return this;
  21297. }
  21298. toJSON() {
  21299. const data = super.toJSON();
  21300. data.points = [];
  21301. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21302. const point = this.points[ i ];
  21303. data.points.push( point.toArray() );
  21304. }
  21305. return data;
  21306. }
  21307. fromJSON( json ) {
  21308. super.fromJSON( json );
  21309. this.points = [];
  21310. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21311. const point = json.points[ i ];
  21312. this.points.push( new Vector2().fromArray( point ) );
  21313. }
  21314. return this;
  21315. }
  21316. }
  21317. var Curves = /*#__PURE__*/Object.freeze({
  21318. __proto__: null,
  21319. ArcCurve: ArcCurve,
  21320. CatmullRomCurve3: CatmullRomCurve3,
  21321. CubicBezierCurve: CubicBezierCurve,
  21322. CubicBezierCurve3: CubicBezierCurve3,
  21323. EllipseCurve: EllipseCurve,
  21324. LineCurve: LineCurve,
  21325. LineCurve3: LineCurve3,
  21326. QuadraticBezierCurve: QuadraticBezierCurve,
  21327. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21328. SplineCurve: SplineCurve
  21329. });
  21330. /**************************************************************
  21331. * Curved Path - a curve path is simply a array of connected
  21332. * curves, but retains the api of a curve
  21333. **************************************************************/
  21334. class CurvePath extends Curve {
  21335. constructor() {
  21336. super();
  21337. this.type = 'CurvePath';
  21338. this.curves = [];
  21339. this.autoClose = false; // Automatically closes the path
  21340. }
  21341. add( curve ) {
  21342. this.curves.push( curve );
  21343. }
  21344. closePath() {
  21345. // Add a line curve if start and end of lines are not connected
  21346. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21347. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21348. if ( ! startPoint.equals( endPoint ) ) {
  21349. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  21350. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  21351. }
  21352. return this;
  21353. }
  21354. // To get accurate point with reference to
  21355. // entire path distance at time t,
  21356. // following has to be done:
  21357. // 1. Length of each sub path have to be known
  21358. // 2. Locate and identify type of curve
  21359. // 3. Get t for the curve
  21360. // 4. Return curve.getPointAt(t')
  21361. getPoint( t, optionalTarget ) {
  21362. const d = t * this.getLength();
  21363. const curveLengths = this.getCurveLengths();
  21364. let i = 0;
  21365. // To think about boundaries points.
  21366. while ( i < curveLengths.length ) {
  21367. if ( curveLengths[ i ] >= d ) {
  21368. const diff = curveLengths[ i ] - d;
  21369. const curve = this.curves[ i ];
  21370. const segmentLength = curve.getLength();
  21371. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21372. return curve.getPointAt( u, optionalTarget );
  21373. }
  21374. i ++;
  21375. }
  21376. return null;
  21377. // loop where sum != 0, sum > d , sum+1 <d
  21378. }
  21379. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21380. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21381. // getPoint() depends on getLength
  21382. getLength() {
  21383. const lens = this.getCurveLengths();
  21384. return lens[ lens.length - 1 ];
  21385. }
  21386. // cacheLengths must be recalculated.
  21387. updateArcLengths() {
  21388. this.needsUpdate = true;
  21389. this.cacheLengths = null;
  21390. this.getCurveLengths();
  21391. }
  21392. // Compute lengths and cache them
  21393. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21394. getCurveLengths() {
  21395. // We use cache values if curves and cache array are same length
  21396. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21397. return this.cacheLengths;
  21398. }
  21399. // Get length of sub-curve
  21400. // Push sums into cached array
  21401. const lengths = [];
  21402. let sums = 0;
  21403. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21404. sums += this.curves[ i ].getLength();
  21405. lengths.push( sums );
  21406. }
  21407. this.cacheLengths = lengths;
  21408. return lengths;
  21409. }
  21410. getSpacedPoints( divisions = 40 ) {
  21411. const points = [];
  21412. for ( let i = 0; i <= divisions; i ++ ) {
  21413. points.push( this.getPoint( i / divisions ) );
  21414. }
  21415. if ( this.autoClose ) {
  21416. points.push( points[ 0 ] );
  21417. }
  21418. return points;
  21419. }
  21420. getPoints( divisions = 12 ) {
  21421. const points = [];
  21422. let last;
  21423. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21424. const curve = curves[ i ];
  21425. const resolution = curve.isEllipseCurve ? divisions * 2
  21426. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  21427. : curve.isSplineCurve ? divisions * curve.points.length
  21428. : divisions;
  21429. const pts = curve.getPoints( resolution );
  21430. for ( let j = 0; j < pts.length; j ++ ) {
  21431. const point = pts[ j ];
  21432. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21433. points.push( point );
  21434. last = point;
  21435. }
  21436. }
  21437. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21438. points.push( points[ 0 ] );
  21439. }
  21440. return points;
  21441. }
  21442. copy( source ) {
  21443. super.copy( source );
  21444. this.curves = [];
  21445. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21446. const curve = source.curves[ i ];
  21447. this.curves.push( curve.clone() );
  21448. }
  21449. this.autoClose = source.autoClose;
  21450. return this;
  21451. }
  21452. toJSON() {
  21453. const data = super.toJSON();
  21454. data.autoClose = this.autoClose;
  21455. data.curves = [];
  21456. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21457. const curve = this.curves[ i ];
  21458. data.curves.push( curve.toJSON() );
  21459. }
  21460. return data;
  21461. }
  21462. fromJSON( json ) {
  21463. super.fromJSON( json );
  21464. this.autoClose = json.autoClose;
  21465. this.curves = [];
  21466. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21467. const curve = json.curves[ i ];
  21468. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21469. }
  21470. return this;
  21471. }
  21472. }
  21473. class Path extends CurvePath {
  21474. constructor( points ) {
  21475. super();
  21476. this.type = 'Path';
  21477. this.currentPoint = new Vector2();
  21478. if ( points ) {
  21479. this.setFromPoints( points );
  21480. }
  21481. }
  21482. setFromPoints( points ) {
  21483. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21484. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21485. this.lineTo( points[ i ].x, points[ i ].y );
  21486. }
  21487. return this;
  21488. }
  21489. moveTo( x, y ) {
  21490. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21491. return this;
  21492. }
  21493. lineTo( x, y ) {
  21494. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21495. this.curves.push( curve );
  21496. this.currentPoint.set( x, y );
  21497. return this;
  21498. }
  21499. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21500. const curve = new QuadraticBezierCurve(
  21501. this.currentPoint.clone(),
  21502. new Vector2( aCPx, aCPy ),
  21503. new Vector2( aX, aY )
  21504. );
  21505. this.curves.push( curve );
  21506. this.currentPoint.set( aX, aY );
  21507. return this;
  21508. }
  21509. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21510. const curve = new CubicBezierCurve(
  21511. this.currentPoint.clone(),
  21512. new Vector2( aCP1x, aCP1y ),
  21513. new Vector2( aCP2x, aCP2y ),
  21514. new Vector2( aX, aY )
  21515. );
  21516. this.curves.push( curve );
  21517. this.currentPoint.set( aX, aY );
  21518. return this;
  21519. }
  21520. splineThru( pts /*Array of Vector*/ ) {
  21521. const npts = [ this.currentPoint.clone() ].concat( pts );
  21522. const curve = new SplineCurve( npts );
  21523. this.curves.push( curve );
  21524. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21525. return this;
  21526. }
  21527. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21528. const x0 = this.currentPoint.x;
  21529. const y0 = this.currentPoint.y;
  21530. this.absarc( aX + x0, aY + y0, aRadius,
  21531. aStartAngle, aEndAngle, aClockwise );
  21532. return this;
  21533. }
  21534. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21535. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21536. return this;
  21537. }
  21538. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21539. const x0 = this.currentPoint.x;
  21540. const y0 = this.currentPoint.y;
  21541. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21542. return this;
  21543. }
  21544. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21545. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21546. if ( this.curves.length > 0 ) {
  21547. // if a previous curve is present, attempt to join
  21548. const firstPoint = curve.getPoint( 0 );
  21549. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21550. this.lineTo( firstPoint.x, firstPoint.y );
  21551. }
  21552. }
  21553. this.curves.push( curve );
  21554. const lastPoint = curve.getPoint( 1 );
  21555. this.currentPoint.copy( lastPoint );
  21556. return this;
  21557. }
  21558. copy( source ) {
  21559. super.copy( source );
  21560. this.currentPoint.copy( source.currentPoint );
  21561. return this;
  21562. }
  21563. toJSON() {
  21564. const data = super.toJSON();
  21565. data.currentPoint = this.currentPoint.toArray();
  21566. return data;
  21567. }
  21568. fromJSON( json ) {
  21569. super.fromJSON( json );
  21570. this.currentPoint.fromArray( json.currentPoint );
  21571. return this;
  21572. }
  21573. }
  21574. class LatheGeometry extends BufferGeometry {
  21575. 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 ) {
  21576. super();
  21577. this.type = 'LatheGeometry';
  21578. this.parameters = {
  21579. points: points,
  21580. segments: segments,
  21581. phiStart: phiStart,
  21582. phiLength: phiLength
  21583. };
  21584. segments = Math.floor( segments );
  21585. // clamp phiLength so it's in range of [ 0, 2PI ]
  21586. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21587. // buffers
  21588. const indices = [];
  21589. const vertices = [];
  21590. const uvs = [];
  21591. const initNormals = [];
  21592. const normals = [];
  21593. // helper variables
  21594. const inverseSegments = 1.0 / segments;
  21595. const vertex = new Vector3();
  21596. const uv = new Vector2();
  21597. const normal = new Vector3();
  21598. const curNormal = new Vector3();
  21599. const prevNormal = new Vector3();
  21600. let dx = 0;
  21601. let dy = 0;
  21602. // pre-compute normals for initial "meridian"
  21603. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21604. switch ( j ) {
  21605. case 0: // special handling for 1st vertex on path
  21606. dx = points[ j + 1 ].x - points[ j ].x;
  21607. dy = points[ j + 1 ].y - points[ j ].y;
  21608. normal.x = dy * 1.0;
  21609. normal.y = - dx;
  21610. normal.z = dy * 0.0;
  21611. prevNormal.copy( normal );
  21612. normal.normalize();
  21613. initNormals.push( normal.x, normal.y, normal.z );
  21614. break;
  21615. case ( points.length - 1 ): // special handling for last Vertex on path
  21616. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  21617. break;
  21618. default: // default handling for all vertices in between
  21619. dx = points[ j + 1 ].x - points[ j ].x;
  21620. dy = points[ j + 1 ].y - points[ j ].y;
  21621. normal.x = dy * 1.0;
  21622. normal.y = - dx;
  21623. normal.z = dy * 0.0;
  21624. curNormal.copy( normal );
  21625. normal.x += prevNormal.x;
  21626. normal.y += prevNormal.y;
  21627. normal.z += prevNormal.z;
  21628. normal.normalize();
  21629. initNormals.push( normal.x, normal.y, normal.z );
  21630. prevNormal.copy( curNormal );
  21631. }
  21632. }
  21633. // generate vertices, uvs and normals
  21634. for ( let i = 0; i <= segments; i ++ ) {
  21635. const phi = phiStart + i * inverseSegments * phiLength;
  21636. const sin = Math.sin( phi );
  21637. const cos = Math.cos( phi );
  21638. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21639. // vertex
  21640. vertex.x = points[ j ].x * sin;
  21641. vertex.y = points[ j ].y;
  21642. vertex.z = points[ j ].x * cos;
  21643. vertices.push( vertex.x, vertex.y, vertex.z );
  21644. // uv
  21645. uv.x = i / segments;
  21646. uv.y = j / ( points.length - 1 );
  21647. uvs.push( uv.x, uv.y );
  21648. // normal
  21649. const x = initNormals[ 3 * j + 0 ] * sin;
  21650. const y = initNormals[ 3 * j + 1 ];
  21651. const z = initNormals[ 3 * j + 0 ] * cos;
  21652. normals.push( x, y, z );
  21653. }
  21654. }
  21655. // indices
  21656. for ( let i = 0; i < segments; i ++ ) {
  21657. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  21658. const base = j + i * points.length;
  21659. const a = base;
  21660. const b = base + points.length;
  21661. const c = base + points.length + 1;
  21662. const d = base + 1;
  21663. // faces
  21664. indices.push( a, b, d );
  21665. indices.push( c, d, b );
  21666. }
  21667. }
  21668. // build geometry
  21669. this.setIndex( indices );
  21670. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21671. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21672. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21673. }
  21674. copy( source ) {
  21675. super.copy( source );
  21676. this.parameters = Object.assign( {}, source.parameters );
  21677. return this;
  21678. }
  21679. static fromJSON( data ) {
  21680. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  21681. }
  21682. }
  21683. class CapsuleGeometry extends LatheGeometry {
  21684. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  21685. const path = new Path();
  21686. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  21687. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  21688. super( path.getPoints( capSegments ), radialSegments );
  21689. this.type = 'CapsuleGeometry';
  21690. this.parameters = {
  21691. radius: radius,
  21692. length: length,
  21693. capSegments: capSegments,
  21694. radialSegments: radialSegments,
  21695. };
  21696. }
  21697. static fromJSON( data ) {
  21698. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  21699. }
  21700. }
  21701. class CircleGeometry extends BufferGeometry {
  21702. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21703. super();
  21704. this.type = 'CircleGeometry';
  21705. this.parameters = {
  21706. radius: radius,
  21707. segments: segments,
  21708. thetaStart: thetaStart,
  21709. thetaLength: thetaLength
  21710. };
  21711. segments = Math.max( 3, segments );
  21712. // buffers
  21713. const indices = [];
  21714. const vertices = [];
  21715. const normals = [];
  21716. const uvs = [];
  21717. // helper variables
  21718. const vertex = new Vector3();
  21719. const uv = new Vector2();
  21720. // center point
  21721. vertices.push( 0, 0, 0 );
  21722. normals.push( 0, 0, 1 );
  21723. uvs.push( 0.5, 0.5 );
  21724. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21725. const segment = thetaStart + s / segments * thetaLength;
  21726. // vertex
  21727. vertex.x = radius * Math.cos( segment );
  21728. vertex.y = radius * Math.sin( segment );
  21729. vertices.push( vertex.x, vertex.y, vertex.z );
  21730. // normal
  21731. normals.push( 0, 0, 1 );
  21732. // uvs
  21733. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21734. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21735. uvs.push( uv.x, uv.y );
  21736. }
  21737. // indices
  21738. for ( let i = 1; i <= segments; i ++ ) {
  21739. indices.push( i, i + 1, 0 );
  21740. }
  21741. // build geometry
  21742. this.setIndex( indices );
  21743. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21744. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21745. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21746. }
  21747. copy( source ) {
  21748. super.copy( source );
  21749. this.parameters = Object.assign( {}, source.parameters );
  21750. return this;
  21751. }
  21752. static fromJSON( data ) {
  21753. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21754. }
  21755. }
  21756. class CylinderGeometry extends BufferGeometry {
  21757. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21758. super();
  21759. this.type = 'CylinderGeometry';
  21760. this.parameters = {
  21761. radiusTop: radiusTop,
  21762. radiusBottom: radiusBottom,
  21763. height: height,
  21764. radialSegments: radialSegments,
  21765. heightSegments: heightSegments,
  21766. openEnded: openEnded,
  21767. thetaStart: thetaStart,
  21768. thetaLength: thetaLength
  21769. };
  21770. const scope = this;
  21771. radialSegments = Math.floor( radialSegments );
  21772. heightSegments = Math.floor( heightSegments );
  21773. // buffers
  21774. const indices = [];
  21775. const vertices = [];
  21776. const normals = [];
  21777. const uvs = [];
  21778. // helper variables
  21779. let index = 0;
  21780. const indexArray = [];
  21781. const halfHeight = height / 2;
  21782. let groupStart = 0;
  21783. // generate geometry
  21784. generateTorso();
  21785. if ( openEnded === false ) {
  21786. if ( radiusTop > 0 ) generateCap( true );
  21787. if ( radiusBottom > 0 ) generateCap( false );
  21788. }
  21789. // build geometry
  21790. this.setIndex( indices );
  21791. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21792. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21793. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21794. function generateTorso() {
  21795. const normal = new Vector3();
  21796. const vertex = new Vector3();
  21797. let groupCount = 0;
  21798. // this will be used to calculate the normal
  21799. const slope = ( radiusBottom - radiusTop ) / height;
  21800. // generate vertices, normals and uvs
  21801. for ( let y = 0; y <= heightSegments; y ++ ) {
  21802. const indexRow = [];
  21803. const v = y / heightSegments;
  21804. // calculate the radius of the current row
  21805. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21806. for ( let x = 0; x <= radialSegments; x ++ ) {
  21807. const u = x / radialSegments;
  21808. const theta = u * thetaLength + thetaStart;
  21809. const sinTheta = Math.sin( theta );
  21810. const cosTheta = Math.cos( theta );
  21811. // vertex
  21812. vertex.x = radius * sinTheta;
  21813. vertex.y = - v * height + halfHeight;
  21814. vertex.z = radius * cosTheta;
  21815. vertices.push( vertex.x, vertex.y, vertex.z );
  21816. // normal
  21817. normal.set( sinTheta, slope, cosTheta ).normalize();
  21818. normals.push( normal.x, normal.y, normal.z );
  21819. // uv
  21820. uvs.push( u, 1 - v );
  21821. // save index of vertex in respective row
  21822. indexRow.push( index ++ );
  21823. }
  21824. // now save vertices of the row in our index array
  21825. indexArray.push( indexRow );
  21826. }
  21827. // generate indices
  21828. for ( let x = 0; x < radialSegments; x ++ ) {
  21829. for ( let y = 0; y < heightSegments; y ++ ) {
  21830. // we use the index array to access the correct indices
  21831. const a = indexArray[ y ][ x ];
  21832. const b = indexArray[ y + 1 ][ x ];
  21833. const c = indexArray[ y + 1 ][ x + 1 ];
  21834. const d = indexArray[ y ][ x + 1 ];
  21835. // faces
  21836. indices.push( a, b, d );
  21837. indices.push( b, c, d );
  21838. // update group counter
  21839. groupCount += 6;
  21840. }
  21841. }
  21842. // add a group to the geometry. this will ensure multi material support
  21843. scope.addGroup( groupStart, groupCount, 0 );
  21844. // calculate new start value for groups
  21845. groupStart += groupCount;
  21846. }
  21847. function generateCap( top ) {
  21848. // save the index of the first center vertex
  21849. const centerIndexStart = index;
  21850. const uv = new Vector2();
  21851. const vertex = new Vector3();
  21852. let groupCount = 0;
  21853. const radius = ( top === true ) ? radiusTop : radiusBottom;
  21854. const sign = ( top === true ) ? 1 : - 1;
  21855. // first we generate the center vertex data of the cap.
  21856. // because the geometry needs one set of uvs per face,
  21857. // we must generate a center vertex per face/segment
  21858. for ( let x = 1; x <= radialSegments; x ++ ) {
  21859. // vertex
  21860. vertices.push( 0, halfHeight * sign, 0 );
  21861. // normal
  21862. normals.push( 0, sign, 0 );
  21863. // uv
  21864. uvs.push( 0.5, 0.5 );
  21865. // increase index
  21866. index ++;
  21867. }
  21868. // save the index of the last center vertex
  21869. const centerIndexEnd = index;
  21870. // now we generate the surrounding vertices, normals and uvs
  21871. for ( let x = 0; x <= radialSegments; x ++ ) {
  21872. const u = x / radialSegments;
  21873. const theta = u * thetaLength + thetaStart;
  21874. const cosTheta = Math.cos( theta );
  21875. const sinTheta = Math.sin( theta );
  21876. // vertex
  21877. vertex.x = radius * sinTheta;
  21878. vertex.y = halfHeight * sign;
  21879. vertex.z = radius * cosTheta;
  21880. vertices.push( vertex.x, vertex.y, vertex.z );
  21881. // normal
  21882. normals.push( 0, sign, 0 );
  21883. // uv
  21884. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21885. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21886. uvs.push( uv.x, uv.y );
  21887. // increase index
  21888. index ++;
  21889. }
  21890. // generate indices
  21891. for ( let x = 0; x < radialSegments; x ++ ) {
  21892. const c = centerIndexStart + x;
  21893. const i = centerIndexEnd + x;
  21894. if ( top === true ) {
  21895. // face top
  21896. indices.push( i, i + 1, c );
  21897. } else {
  21898. // face bottom
  21899. indices.push( i + 1, i, c );
  21900. }
  21901. groupCount += 3;
  21902. }
  21903. // add a group to the geometry. this will ensure multi material support
  21904. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21905. // calculate new start value for groups
  21906. groupStart += groupCount;
  21907. }
  21908. }
  21909. copy( source ) {
  21910. super.copy( source );
  21911. this.parameters = Object.assign( {}, source.parameters );
  21912. return this;
  21913. }
  21914. static fromJSON( data ) {
  21915. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21916. }
  21917. }
  21918. class ConeGeometry extends CylinderGeometry {
  21919. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21920. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21921. this.type = 'ConeGeometry';
  21922. this.parameters = {
  21923. radius: radius,
  21924. height: height,
  21925. radialSegments: radialSegments,
  21926. heightSegments: heightSegments,
  21927. openEnded: openEnded,
  21928. thetaStart: thetaStart,
  21929. thetaLength: thetaLength
  21930. };
  21931. }
  21932. static fromJSON( data ) {
  21933. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21934. }
  21935. }
  21936. class PolyhedronGeometry extends BufferGeometry {
  21937. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  21938. super();
  21939. this.type = 'PolyhedronGeometry';
  21940. this.parameters = {
  21941. vertices: vertices,
  21942. indices: indices,
  21943. radius: radius,
  21944. detail: detail
  21945. };
  21946. // default buffer data
  21947. const vertexBuffer = [];
  21948. const uvBuffer = [];
  21949. // the subdivision creates the vertex buffer data
  21950. subdivide( detail );
  21951. // all vertices should lie on a conceptual sphere with a given radius
  21952. applyRadius( radius );
  21953. // finally, create the uv data
  21954. generateUVs();
  21955. // build non-indexed geometry
  21956. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  21957. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  21958. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  21959. if ( detail === 0 ) {
  21960. this.computeVertexNormals(); // flat normals
  21961. } else {
  21962. this.normalizeNormals(); // smooth normals
  21963. }
  21964. // helper functions
  21965. function subdivide( detail ) {
  21966. const a = new Vector3();
  21967. const b = new Vector3();
  21968. const c = new Vector3();
  21969. // iterate over all faces and apply a subdivision with the given detail value
  21970. for ( let i = 0; i < indices.length; i += 3 ) {
  21971. // get the vertices of the face
  21972. getVertexByIndex( indices[ i + 0 ], a );
  21973. getVertexByIndex( indices[ i + 1 ], b );
  21974. getVertexByIndex( indices[ i + 2 ], c );
  21975. // perform subdivision
  21976. subdivideFace( a, b, c, detail );
  21977. }
  21978. }
  21979. function subdivideFace( a, b, c, detail ) {
  21980. const cols = detail + 1;
  21981. // we use this multidimensional array as a data structure for creating the subdivision
  21982. const v = [];
  21983. // construct all of the vertices for this subdivision
  21984. for ( let i = 0; i <= cols; i ++ ) {
  21985. v[ i ] = [];
  21986. const aj = a.clone().lerp( c, i / cols );
  21987. const bj = b.clone().lerp( c, i / cols );
  21988. const rows = cols - i;
  21989. for ( let j = 0; j <= rows; j ++ ) {
  21990. if ( j === 0 && i === cols ) {
  21991. v[ i ][ j ] = aj;
  21992. } else {
  21993. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  21994. }
  21995. }
  21996. }
  21997. // construct all of the faces
  21998. for ( let i = 0; i < cols; i ++ ) {
  21999. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22000. const k = Math.floor( j / 2 );
  22001. if ( j % 2 === 0 ) {
  22002. pushVertex( v[ i ][ k + 1 ] );
  22003. pushVertex( v[ i + 1 ][ k ] );
  22004. pushVertex( v[ i ][ k ] );
  22005. } else {
  22006. pushVertex( v[ i ][ k + 1 ] );
  22007. pushVertex( v[ i + 1 ][ k + 1 ] );
  22008. pushVertex( v[ i + 1 ][ k ] );
  22009. }
  22010. }
  22011. }
  22012. }
  22013. function applyRadius( radius ) {
  22014. const vertex = new Vector3();
  22015. // iterate over the entire buffer and apply the radius to each vertex
  22016. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22017. vertex.x = vertexBuffer[ i + 0 ];
  22018. vertex.y = vertexBuffer[ i + 1 ];
  22019. vertex.z = vertexBuffer[ i + 2 ];
  22020. vertex.normalize().multiplyScalar( radius );
  22021. vertexBuffer[ i + 0 ] = vertex.x;
  22022. vertexBuffer[ i + 1 ] = vertex.y;
  22023. vertexBuffer[ i + 2 ] = vertex.z;
  22024. }
  22025. }
  22026. function generateUVs() {
  22027. const vertex = new Vector3();
  22028. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22029. vertex.x = vertexBuffer[ i + 0 ];
  22030. vertex.y = vertexBuffer[ i + 1 ];
  22031. vertex.z = vertexBuffer[ i + 2 ];
  22032. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22033. const v = inclination( vertex ) / Math.PI + 0.5;
  22034. uvBuffer.push( u, 1 - v );
  22035. }
  22036. correctUVs();
  22037. correctSeam();
  22038. }
  22039. function correctSeam() {
  22040. // handle case when face straddles the seam, see #3269
  22041. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22042. // uv data of a single face
  22043. const x0 = uvBuffer[ i + 0 ];
  22044. const x1 = uvBuffer[ i + 2 ];
  22045. const x2 = uvBuffer[ i + 4 ];
  22046. const max = Math.max( x0, x1, x2 );
  22047. const min = Math.min( x0, x1, x2 );
  22048. // 0.9 is somewhat arbitrary
  22049. if ( max > 0.9 && min < 0.1 ) {
  22050. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22051. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22052. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22053. }
  22054. }
  22055. }
  22056. function pushVertex( vertex ) {
  22057. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22058. }
  22059. function getVertexByIndex( index, vertex ) {
  22060. const stride = index * 3;
  22061. vertex.x = vertices[ stride + 0 ];
  22062. vertex.y = vertices[ stride + 1 ];
  22063. vertex.z = vertices[ stride + 2 ];
  22064. }
  22065. function correctUVs() {
  22066. const a = new Vector3();
  22067. const b = new Vector3();
  22068. const c = new Vector3();
  22069. const centroid = new Vector3();
  22070. const uvA = new Vector2();
  22071. const uvB = new Vector2();
  22072. const uvC = new Vector2();
  22073. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22074. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22075. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22076. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22077. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22078. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22079. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22080. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22081. const azi = azimuth( centroid );
  22082. correctUV( uvA, j + 0, a, azi );
  22083. correctUV( uvB, j + 2, b, azi );
  22084. correctUV( uvC, j + 4, c, azi );
  22085. }
  22086. }
  22087. function correctUV( uv, stride, vector, azimuth ) {
  22088. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22089. uvBuffer[ stride ] = uv.x - 1;
  22090. }
  22091. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22092. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22093. }
  22094. }
  22095. // Angle around the Y axis, counter-clockwise when looking from above.
  22096. function azimuth( vector ) {
  22097. return Math.atan2( vector.z, - vector.x );
  22098. }
  22099. // Angle above the XZ plane.
  22100. function inclination( vector ) {
  22101. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22102. }
  22103. }
  22104. copy( source ) {
  22105. super.copy( source );
  22106. this.parameters = Object.assign( {}, source.parameters );
  22107. return this;
  22108. }
  22109. static fromJSON( data ) {
  22110. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22111. }
  22112. }
  22113. class DodecahedronGeometry extends PolyhedronGeometry {
  22114. constructor( radius = 1, detail = 0 ) {
  22115. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22116. const r = 1 / t;
  22117. const vertices = [
  22118. // (±1, ±1, ±1)
  22119. - 1, - 1, - 1, - 1, - 1, 1,
  22120. - 1, 1, - 1, - 1, 1, 1,
  22121. 1, - 1, - 1, 1, - 1, 1,
  22122. 1, 1, - 1, 1, 1, 1,
  22123. // (0, ±1/φ, ±φ)
  22124. 0, - r, - t, 0, - r, t,
  22125. 0, r, - t, 0, r, t,
  22126. // (±1/φ, ±φ, 0)
  22127. - r, - t, 0, - r, t, 0,
  22128. r, - t, 0, r, t, 0,
  22129. // (±φ, 0, ±1/φ)
  22130. - t, 0, - r, t, 0, - r,
  22131. - t, 0, r, t, 0, r
  22132. ];
  22133. const indices = [
  22134. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22135. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22136. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22137. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22138. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22139. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22140. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22141. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22142. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22143. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22144. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22145. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22146. ];
  22147. super( vertices, indices, radius, detail );
  22148. this.type = 'DodecahedronGeometry';
  22149. this.parameters = {
  22150. radius: radius,
  22151. detail: detail
  22152. };
  22153. }
  22154. static fromJSON( data ) {
  22155. return new DodecahedronGeometry( data.radius, data.detail );
  22156. }
  22157. }
  22158. const _v0 = /*@__PURE__*/ new Vector3();
  22159. const _v1$1 = /*@__PURE__*/ new Vector3();
  22160. const _normal = /*@__PURE__*/ new Vector3();
  22161. const _triangle = /*@__PURE__*/ new Triangle();
  22162. class EdgesGeometry extends BufferGeometry {
  22163. constructor( geometry = null, thresholdAngle = 1 ) {
  22164. super();
  22165. this.type = 'EdgesGeometry';
  22166. this.parameters = {
  22167. geometry: geometry,
  22168. thresholdAngle: thresholdAngle
  22169. };
  22170. if ( geometry !== null ) {
  22171. const precisionPoints = 4;
  22172. const precision = Math.pow( 10, precisionPoints );
  22173. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22174. const indexAttr = geometry.getIndex();
  22175. const positionAttr = geometry.getAttribute( 'position' );
  22176. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22177. const indexArr = [ 0, 0, 0 ];
  22178. const vertKeys = [ 'a', 'b', 'c' ];
  22179. const hashes = new Array( 3 );
  22180. const edgeData = {};
  22181. const vertices = [];
  22182. for ( let i = 0; i < indexCount; i += 3 ) {
  22183. if ( indexAttr ) {
  22184. indexArr[ 0 ] = indexAttr.getX( i );
  22185. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22186. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22187. } else {
  22188. indexArr[ 0 ] = i;
  22189. indexArr[ 1 ] = i + 1;
  22190. indexArr[ 2 ] = i + 2;
  22191. }
  22192. const { a, b, c } = _triangle;
  22193. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22194. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22195. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22196. _triangle.getNormal( _normal );
  22197. // create hashes for the edge from the vertices
  22198. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22199. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22200. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22201. // skip degenerate triangles
  22202. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22203. continue;
  22204. }
  22205. // iterate over every edge
  22206. for ( let j = 0; j < 3; j ++ ) {
  22207. // get the first and next vertex making up the edge
  22208. const jNext = ( j + 1 ) % 3;
  22209. const vecHash0 = hashes[ j ];
  22210. const vecHash1 = hashes[ jNext ];
  22211. const v0 = _triangle[ vertKeys[ j ] ];
  22212. const v1 = _triangle[ vertKeys[ jNext ] ];
  22213. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22214. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22215. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22216. // if we found a sibling edge add it into the vertex array if
  22217. // it meets the angle threshold and delete the edge from the map.
  22218. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22219. vertices.push( v0.x, v0.y, v0.z );
  22220. vertices.push( v1.x, v1.y, v1.z );
  22221. }
  22222. edgeData[ reverseHash ] = null;
  22223. } else if ( ! ( hash in edgeData ) ) {
  22224. // if we've already got an edge here then skip adding a new one
  22225. edgeData[ hash ] = {
  22226. index0: indexArr[ j ],
  22227. index1: indexArr[ jNext ],
  22228. normal: _normal.clone(),
  22229. };
  22230. }
  22231. }
  22232. }
  22233. // iterate over all remaining, unmatched edges and add them to the vertex array
  22234. for ( const key in edgeData ) {
  22235. if ( edgeData[ key ] ) {
  22236. const { index0, index1 } = edgeData[ key ];
  22237. _v0.fromBufferAttribute( positionAttr, index0 );
  22238. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22239. vertices.push( _v0.x, _v0.y, _v0.z );
  22240. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22241. }
  22242. }
  22243. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22244. }
  22245. }
  22246. copy( source ) {
  22247. super.copy( source );
  22248. this.parameters = Object.assign( {}, source.parameters );
  22249. return this;
  22250. }
  22251. }
  22252. class Shape extends Path {
  22253. constructor( points ) {
  22254. super( points );
  22255. this.uuid = generateUUID();
  22256. this.type = 'Shape';
  22257. this.holes = [];
  22258. }
  22259. getPointsHoles( divisions ) {
  22260. const holesPts = [];
  22261. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22262. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22263. }
  22264. return holesPts;
  22265. }
  22266. // get points of shape and holes (keypoints based on segments parameter)
  22267. extractPoints( divisions ) {
  22268. return {
  22269. shape: this.getPoints( divisions ),
  22270. holes: this.getPointsHoles( divisions )
  22271. };
  22272. }
  22273. copy( source ) {
  22274. super.copy( source );
  22275. this.holes = [];
  22276. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22277. const hole = source.holes[ i ];
  22278. this.holes.push( hole.clone() );
  22279. }
  22280. return this;
  22281. }
  22282. toJSON() {
  22283. const data = super.toJSON();
  22284. data.uuid = this.uuid;
  22285. data.holes = [];
  22286. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22287. const hole = this.holes[ i ];
  22288. data.holes.push( hole.toJSON() );
  22289. }
  22290. return data;
  22291. }
  22292. fromJSON( json ) {
  22293. super.fromJSON( json );
  22294. this.uuid = json.uuid;
  22295. this.holes = [];
  22296. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22297. const hole = json.holes[ i ];
  22298. this.holes.push( new Path().fromJSON( hole ) );
  22299. }
  22300. return this;
  22301. }
  22302. }
  22303. /**
  22304. * Port from https://github.com/mapbox/earcut (v2.2.4)
  22305. */
  22306. const Earcut = {
  22307. triangulate: function ( data, holeIndices, dim = 2 ) {
  22308. const hasHoles = holeIndices && holeIndices.length;
  22309. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  22310. let outerNode = linkedList( data, 0, outerLen, dim, true );
  22311. const triangles = [];
  22312. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  22313. let minX, minY, maxX, maxY, x, y, invSize;
  22314. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  22315. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22316. if ( data.length > 80 * dim ) {
  22317. minX = maxX = data[ 0 ];
  22318. minY = maxY = data[ 1 ];
  22319. for ( let i = dim; i < outerLen; i += dim ) {
  22320. x = data[ i ];
  22321. y = data[ i + 1 ];
  22322. if ( x < minX ) minX = x;
  22323. if ( y < minY ) minY = y;
  22324. if ( x > maxX ) maxX = x;
  22325. if ( y > maxY ) maxY = y;
  22326. }
  22327. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22328. invSize = Math.max( maxX - minX, maxY - minY );
  22329. invSize = invSize !== 0 ? 32767 / invSize : 0;
  22330. }
  22331. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  22332. return triangles;
  22333. }
  22334. };
  22335. // create a circular doubly linked list from polygon points in the specified winding order
  22336. function linkedList( data, start, end, dim, clockwise ) {
  22337. let i, last;
  22338. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22339. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22340. } else {
  22341. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22342. }
  22343. if ( last && equals( last, last.next ) ) {
  22344. removeNode( last );
  22345. last = last.next;
  22346. }
  22347. return last;
  22348. }
  22349. // eliminate colinear or duplicate points
  22350. function filterPoints( start, end ) {
  22351. if ( ! start ) return start;
  22352. if ( ! end ) end = start;
  22353. let p = start,
  22354. again;
  22355. do {
  22356. again = false;
  22357. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22358. removeNode( p );
  22359. p = end = p.prev;
  22360. if ( p === p.next ) break;
  22361. again = true;
  22362. } else {
  22363. p = p.next;
  22364. }
  22365. } while ( again || p !== end );
  22366. return end;
  22367. }
  22368. // main ear slicing loop which triangulates a polygon (given as a linked list)
  22369. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  22370. if ( ! ear ) return;
  22371. // interlink polygon nodes in z-order
  22372. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  22373. let stop = ear,
  22374. prev, next;
  22375. // iterate through ears, slicing them one by one
  22376. while ( ear.prev !== ear.next ) {
  22377. prev = ear.prev;
  22378. next = ear.next;
  22379. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  22380. // cut off the triangle
  22381. triangles.push( prev.i / dim | 0 );
  22382. triangles.push( ear.i / dim | 0 );
  22383. triangles.push( next.i / dim | 0 );
  22384. removeNode( ear );
  22385. // skipping the next vertex leads to less sliver triangles
  22386. ear = next.next;
  22387. stop = next.next;
  22388. continue;
  22389. }
  22390. ear = next;
  22391. // if we looped through the whole remaining polygon and can't find any more ears
  22392. if ( ear === stop ) {
  22393. // try filtering points and slicing again
  22394. if ( ! pass ) {
  22395. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  22396. // if this didn't work, try curing all small self-intersections locally
  22397. } else if ( pass === 1 ) {
  22398. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  22399. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  22400. // as a last resort, try splitting the remaining polygon into two
  22401. } else if ( pass === 2 ) {
  22402. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  22403. }
  22404. break;
  22405. }
  22406. }
  22407. }
  22408. // check whether a polygon node forms a valid ear with adjacent nodes
  22409. function isEar( ear ) {
  22410. const a = ear.prev,
  22411. b = ear,
  22412. c = ear.next;
  22413. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22414. // now make sure we don't have other points inside the potential ear
  22415. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22416. // triangle bbox; min & max are calculated like this for speed
  22417. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22418. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22419. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22420. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22421. let p = c.next;
  22422. while ( p !== a ) {
  22423. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  22424. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  22425. area( p.prev, p, p.next ) >= 0 ) return false;
  22426. p = p.next;
  22427. }
  22428. return true;
  22429. }
  22430. function isEarHashed( ear, minX, minY, invSize ) {
  22431. const a = ear.prev,
  22432. b = ear,
  22433. c = ear.next;
  22434. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22435. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22436. // triangle bbox; min & max are calculated like this for speed
  22437. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22438. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22439. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22440. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22441. // z-order range for the current triangle bbox;
  22442. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  22443. maxZ = zOrder( x1, y1, minX, minY, invSize );
  22444. let p = ear.prevZ,
  22445. n = ear.nextZ;
  22446. // look for points inside the triangle in both directions
  22447. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  22448. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22449. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22450. p = p.prevZ;
  22451. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22452. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22453. n = n.nextZ;
  22454. }
  22455. // look for remaining points in decreasing z-order
  22456. while ( p && p.z >= minZ ) {
  22457. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22458. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22459. p = p.prevZ;
  22460. }
  22461. // look for remaining points in increasing z-order
  22462. while ( n && n.z <= maxZ ) {
  22463. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22464. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22465. n = n.nextZ;
  22466. }
  22467. return true;
  22468. }
  22469. // go through all polygon nodes and cure small local self-intersections
  22470. function cureLocalIntersections( start, triangles, dim ) {
  22471. let p = start;
  22472. do {
  22473. const a = p.prev,
  22474. b = p.next.next;
  22475. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  22476. triangles.push( a.i / dim | 0 );
  22477. triangles.push( p.i / dim | 0 );
  22478. triangles.push( b.i / dim | 0 );
  22479. // remove two nodes involved
  22480. removeNode( p );
  22481. removeNode( p.next );
  22482. p = start = b;
  22483. }
  22484. p = p.next;
  22485. } while ( p !== start );
  22486. return filterPoints( p );
  22487. }
  22488. // try splitting polygon into two and triangulate them independently
  22489. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  22490. // look for a valid diagonal that divides the polygon into two
  22491. let a = start;
  22492. do {
  22493. let b = a.next.next;
  22494. while ( b !== a.prev ) {
  22495. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  22496. // split the polygon in two by the diagonal
  22497. let c = splitPolygon( a, b );
  22498. // filter colinear points around the cuts
  22499. a = filterPoints( a, a.next );
  22500. c = filterPoints( c, c.next );
  22501. // run earcut on each half
  22502. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  22503. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  22504. return;
  22505. }
  22506. b = b.next;
  22507. }
  22508. a = a.next;
  22509. } while ( a !== start );
  22510. }
  22511. // link every hole into the outer loop, producing a single-ring polygon without holes
  22512. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  22513. const queue = [];
  22514. let i, len, start, end, list;
  22515. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  22516. start = holeIndices[ i ] * dim;
  22517. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  22518. list = linkedList( data, start, end, dim, false );
  22519. if ( list === list.next ) list.steiner = true;
  22520. queue.push( getLeftmost( list ) );
  22521. }
  22522. queue.sort( compareX );
  22523. // process holes from left to right
  22524. for ( i = 0; i < queue.length; i ++ ) {
  22525. outerNode = eliminateHole( queue[ i ], outerNode );
  22526. }
  22527. return outerNode;
  22528. }
  22529. function compareX( a, b ) {
  22530. return a.x - b.x;
  22531. }
  22532. // find a bridge between vertices that connects hole with an outer ring and link it
  22533. function eliminateHole( hole, outerNode ) {
  22534. const bridge = findHoleBridge( hole, outerNode );
  22535. if ( ! bridge ) {
  22536. return outerNode;
  22537. }
  22538. const bridgeReverse = splitPolygon( bridge, hole );
  22539. // filter collinear points around the cuts
  22540. filterPoints( bridgeReverse, bridgeReverse.next );
  22541. return filterPoints( bridge, bridge.next );
  22542. }
  22543. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  22544. function findHoleBridge( hole, outerNode ) {
  22545. let p = outerNode,
  22546. qx = - Infinity,
  22547. m;
  22548. const hx = hole.x, hy = hole.y;
  22549. // find a segment intersected by a ray from the hole's leftmost point to the left;
  22550. // segment's endpoint with lesser x will be potential connection point
  22551. do {
  22552. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  22553. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  22554. if ( x <= hx && x > qx ) {
  22555. qx = x;
  22556. m = p.x < p.next.x ? p : p.next;
  22557. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  22558. }
  22559. }
  22560. p = p.next;
  22561. } while ( p !== outerNode );
  22562. if ( ! m ) return null;
  22563. // look for points inside the triangle of hole point, segment intersection and endpoint;
  22564. // if there are no points found, we have a valid connection;
  22565. // otherwise choose the point of the minimum angle with the ray as connection point
  22566. const stop = m,
  22567. mx = m.x,
  22568. my = m.y;
  22569. let tanMin = Infinity, tan;
  22570. p = m;
  22571. do {
  22572. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  22573. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  22574. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  22575. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  22576. m = p;
  22577. tanMin = tan;
  22578. }
  22579. }
  22580. p = p.next;
  22581. } while ( p !== stop );
  22582. return m;
  22583. }
  22584. // whether sector in vertex m contains sector in vertex p in the same coordinates
  22585. function sectorContainsSector( m, p ) {
  22586. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  22587. }
  22588. // interlink polygon nodes in z-order
  22589. function indexCurve( start, minX, minY, invSize ) {
  22590. let p = start;
  22591. do {
  22592. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  22593. p.prevZ = p.prev;
  22594. p.nextZ = p.next;
  22595. p = p.next;
  22596. } while ( p !== start );
  22597. p.prevZ.nextZ = null;
  22598. p.prevZ = null;
  22599. sortLinked( p );
  22600. }
  22601. // Simon Tatham's linked list merge sort algorithm
  22602. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  22603. function sortLinked( list ) {
  22604. let i, p, q, e, tail, numMerges, pSize, qSize,
  22605. inSize = 1;
  22606. do {
  22607. p = list;
  22608. list = null;
  22609. tail = null;
  22610. numMerges = 0;
  22611. while ( p ) {
  22612. numMerges ++;
  22613. q = p;
  22614. pSize = 0;
  22615. for ( i = 0; i < inSize; i ++ ) {
  22616. pSize ++;
  22617. q = q.nextZ;
  22618. if ( ! q ) break;
  22619. }
  22620. qSize = inSize;
  22621. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  22622. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  22623. e = p;
  22624. p = p.nextZ;
  22625. pSize --;
  22626. } else {
  22627. e = q;
  22628. q = q.nextZ;
  22629. qSize --;
  22630. }
  22631. if ( tail ) tail.nextZ = e;
  22632. else list = e;
  22633. e.prevZ = tail;
  22634. tail = e;
  22635. }
  22636. p = q;
  22637. }
  22638. tail.nextZ = null;
  22639. inSize *= 2;
  22640. } while ( numMerges > 1 );
  22641. return list;
  22642. }
  22643. // z-order of a point given coords and inverse of the longer side of data bbox
  22644. function zOrder( x, y, minX, minY, invSize ) {
  22645. // coords are transformed into non-negative 15-bit integer range
  22646. x = ( x - minX ) * invSize | 0;
  22647. y = ( y - minY ) * invSize | 0;
  22648. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  22649. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  22650. x = ( x | ( x << 2 ) ) & 0x33333333;
  22651. x = ( x | ( x << 1 ) ) & 0x55555555;
  22652. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  22653. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  22654. y = ( y | ( y << 2 ) ) & 0x33333333;
  22655. y = ( y | ( y << 1 ) ) & 0x55555555;
  22656. return x | ( y << 1 );
  22657. }
  22658. // find the leftmost node of a polygon ring
  22659. function getLeftmost( start ) {
  22660. let p = start,
  22661. leftmost = start;
  22662. do {
  22663. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  22664. p = p.next;
  22665. } while ( p !== start );
  22666. return leftmost;
  22667. }
  22668. // check if a point lies within a convex triangle
  22669. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  22670. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  22671. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  22672. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  22673. }
  22674. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  22675. function isValidDiagonal( a, b ) {
  22676. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  22677. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  22678. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  22679. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  22680. }
  22681. // signed area of a triangle
  22682. function area( p, q, r ) {
  22683. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  22684. }
  22685. // check if two points are equal
  22686. function equals( p1, p2 ) {
  22687. return p1.x === p2.x && p1.y === p2.y;
  22688. }
  22689. // check if two segments intersect
  22690. function intersects( p1, q1, p2, q2 ) {
  22691. const o1 = sign( area( p1, q1, p2 ) );
  22692. const o2 = sign( area( p1, q1, q2 ) );
  22693. const o3 = sign( area( p2, q2, p1 ) );
  22694. const o4 = sign( area( p2, q2, q1 ) );
  22695. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  22696. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  22697. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  22698. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  22699. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  22700. return false;
  22701. }
  22702. // for collinear points p, q, r, check if point q lies on segment pr
  22703. function onSegment( p, q, r ) {
  22704. 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 );
  22705. }
  22706. function sign( num ) {
  22707. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  22708. }
  22709. // check if a polygon diagonal intersects any polygon segments
  22710. function intersectsPolygon( a, b ) {
  22711. let p = a;
  22712. do {
  22713. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  22714. intersects( p, p.next, a, b ) ) return true;
  22715. p = p.next;
  22716. } while ( p !== a );
  22717. return false;
  22718. }
  22719. // check if a polygon diagonal is locally inside the polygon
  22720. function locallyInside( a, b ) {
  22721. return area( a.prev, a, a.next ) < 0 ?
  22722. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  22723. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  22724. }
  22725. // check if the middle point of a polygon diagonal is inside the polygon
  22726. function middleInside( a, b ) {
  22727. let p = a,
  22728. inside = false;
  22729. const px = ( a.x + b.x ) / 2,
  22730. py = ( a.y + b.y ) / 2;
  22731. do {
  22732. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  22733. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  22734. inside = ! inside;
  22735. p = p.next;
  22736. } while ( p !== a );
  22737. return inside;
  22738. }
  22739. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  22740. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  22741. function splitPolygon( a, b ) {
  22742. const a2 = new Node( a.i, a.x, a.y ),
  22743. b2 = new Node( b.i, b.x, b.y ),
  22744. an = a.next,
  22745. bp = b.prev;
  22746. a.next = b;
  22747. b.prev = a;
  22748. a2.next = an;
  22749. an.prev = a2;
  22750. b2.next = a2;
  22751. a2.prev = b2;
  22752. bp.next = b2;
  22753. b2.prev = bp;
  22754. return b2;
  22755. }
  22756. // create a node and optionally link it with previous one (in a circular doubly linked list)
  22757. function insertNode( i, x, y, last ) {
  22758. const p = new Node( i, x, y );
  22759. if ( ! last ) {
  22760. p.prev = p;
  22761. p.next = p;
  22762. } else {
  22763. p.next = last.next;
  22764. p.prev = last;
  22765. last.next.prev = p;
  22766. last.next = p;
  22767. }
  22768. return p;
  22769. }
  22770. function removeNode( p ) {
  22771. p.next.prev = p.prev;
  22772. p.prev.next = p.next;
  22773. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  22774. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  22775. }
  22776. function Node( i, x, y ) {
  22777. // vertex index in coordinates array
  22778. this.i = i;
  22779. // vertex coordinates
  22780. this.x = x;
  22781. this.y = y;
  22782. // previous and next vertex nodes in a polygon ring
  22783. this.prev = null;
  22784. this.next = null;
  22785. // z-order curve value
  22786. this.z = 0;
  22787. // previous and next nodes in z-order
  22788. this.prevZ = null;
  22789. this.nextZ = null;
  22790. // indicates whether this is a steiner point
  22791. this.steiner = false;
  22792. }
  22793. function signedArea( data, start, end, dim ) {
  22794. let sum = 0;
  22795. for ( let i = start, j = end - dim; i < end; i += dim ) {
  22796. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  22797. j = i;
  22798. }
  22799. return sum;
  22800. }
  22801. class ShapeUtils {
  22802. // calculate area of the contour polygon
  22803. static area( contour ) {
  22804. const n = contour.length;
  22805. let a = 0.0;
  22806. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  22807. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  22808. }
  22809. return a * 0.5;
  22810. }
  22811. static isClockWise( pts ) {
  22812. return ShapeUtils.area( pts ) < 0;
  22813. }
  22814. static triangulateShape( contour, holes ) {
  22815. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  22816. const holeIndices = []; // array of hole indices
  22817. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  22818. removeDupEndPts( contour );
  22819. addContour( vertices, contour );
  22820. //
  22821. let holeIndex = contour.length;
  22822. holes.forEach( removeDupEndPts );
  22823. for ( let i = 0; i < holes.length; i ++ ) {
  22824. holeIndices.push( holeIndex );
  22825. holeIndex += holes[ i ].length;
  22826. addContour( vertices, holes[ i ] );
  22827. }
  22828. //
  22829. const triangles = Earcut.triangulate( vertices, holeIndices );
  22830. //
  22831. for ( let i = 0; i < triangles.length; i += 3 ) {
  22832. faces.push( triangles.slice( i, i + 3 ) );
  22833. }
  22834. return faces;
  22835. }
  22836. }
  22837. function removeDupEndPts( points ) {
  22838. const l = points.length;
  22839. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  22840. points.pop();
  22841. }
  22842. }
  22843. function addContour( vertices, contour ) {
  22844. for ( let i = 0; i < contour.length; i ++ ) {
  22845. vertices.push( contour[ i ].x );
  22846. vertices.push( contour[ i ].y );
  22847. }
  22848. }
  22849. /**
  22850. * Creates extruded geometry from a path shape.
  22851. *
  22852. * parameters = {
  22853. *
  22854. * curveSegments: <int>, // number of points on the curves
  22855. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  22856. * depth: <float>, // Depth to extrude the shape
  22857. *
  22858. * bevelEnabled: <bool>, // turn on bevel
  22859. * bevelThickness: <float>, // how deep into the original shape bevel goes
  22860. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  22861. * bevelOffset: <float>, // how far from shape outline does bevel start
  22862. * bevelSegments: <int>, // number of bevel layers
  22863. *
  22864. * extrudePath: <THREE.Curve> // curve to extrude shape along
  22865. *
  22866. * UVGenerator: <Object> // object that provides UV generator functions
  22867. *
  22868. * }
  22869. */
  22870. class ExtrudeGeometry extends BufferGeometry {
  22871. 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 = {} ) {
  22872. super();
  22873. this.type = 'ExtrudeGeometry';
  22874. this.parameters = {
  22875. shapes: shapes,
  22876. options: options
  22877. };
  22878. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  22879. const scope = this;
  22880. const verticesArray = [];
  22881. const uvArray = [];
  22882. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22883. const shape = shapes[ i ];
  22884. addShape( shape );
  22885. }
  22886. // build geometry
  22887. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  22888. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  22889. this.computeVertexNormals();
  22890. // functions
  22891. function addShape( shape ) {
  22892. const placeholder = [];
  22893. // options
  22894. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22895. const steps = options.steps !== undefined ? options.steps : 1;
  22896. const depth = options.depth !== undefined ? options.depth : 1;
  22897. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  22898. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  22899. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  22900. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  22901. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  22902. const extrudePath = options.extrudePath;
  22903. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  22904. //
  22905. let extrudePts, extrudeByPath = false;
  22906. let splineTube, binormal, normal, position2;
  22907. if ( extrudePath ) {
  22908. extrudePts = extrudePath.getSpacedPoints( steps );
  22909. extrudeByPath = true;
  22910. bevelEnabled = false; // bevels not supported for path extrusion
  22911. // SETUP TNB variables
  22912. // TODO1 - have a .isClosed in spline?
  22913. splineTube = extrudePath.computeFrenetFrames( steps, false );
  22914. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  22915. binormal = new Vector3();
  22916. normal = new Vector3();
  22917. position2 = new Vector3();
  22918. }
  22919. // Safeguards if bevels are not enabled
  22920. if ( ! bevelEnabled ) {
  22921. bevelSegments = 0;
  22922. bevelThickness = 0;
  22923. bevelSize = 0;
  22924. bevelOffset = 0;
  22925. }
  22926. // Variables initialization
  22927. const shapePoints = shape.extractPoints( curveSegments );
  22928. let vertices = shapePoints.shape;
  22929. const holes = shapePoints.holes;
  22930. const reverse = ! ShapeUtils.isClockWise( vertices );
  22931. if ( reverse ) {
  22932. vertices = vertices.reverse();
  22933. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  22934. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22935. const ahole = holes[ h ];
  22936. if ( ShapeUtils.isClockWise( ahole ) ) {
  22937. holes[ h ] = ahole.reverse();
  22938. }
  22939. }
  22940. }
  22941. const faces = ShapeUtils.triangulateShape( vertices, holes );
  22942. /* Vertices */
  22943. const contour = vertices; // vertices has all points but contour has only points of circumference
  22944. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22945. const ahole = holes[ h ];
  22946. vertices = vertices.concat( ahole );
  22947. }
  22948. function scalePt2( pt, vec, size ) {
  22949. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  22950. return pt.clone().addScaledVector( vec, size );
  22951. }
  22952. const vlen = vertices.length, flen = faces.length;
  22953. // Find directions for point movement
  22954. function getBevelVec( inPt, inPrev, inNext ) {
  22955. // computes for inPt the corresponding point inPt' on a new contour
  22956. // shifted by 1 unit (length of normalized vector) to the left
  22957. // if we walk along contour clockwise, this new contour is outside the old one
  22958. //
  22959. // inPt' is the intersection of the two lines parallel to the two
  22960. // adjacent edges of inPt at a distance of 1 unit on the left side.
  22961. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  22962. // good reading for geometry algorithms (here: line-line intersection)
  22963. // http://geomalgorithms.com/a05-_intersect-1.html
  22964. const v_prev_x = inPt.x - inPrev.x,
  22965. v_prev_y = inPt.y - inPrev.y;
  22966. const v_next_x = inNext.x - inPt.x,
  22967. v_next_y = inNext.y - inPt.y;
  22968. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  22969. // check for collinear edges
  22970. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22971. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  22972. // not collinear
  22973. // length of vectors for normalizing
  22974. const v_prev_len = Math.sqrt( v_prev_lensq );
  22975. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  22976. // shift adjacent points by unit vectors to the left
  22977. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  22978. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  22979. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  22980. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  22981. // scaling factor for v_prev to intersection point
  22982. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  22983. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  22984. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22985. // vector from inPt to intersection point
  22986. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  22987. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  22988. // Don't normalize!, otherwise sharp corners become ugly
  22989. // but prevent crazy spikes
  22990. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  22991. if ( v_trans_lensq <= 2 ) {
  22992. return new Vector2( v_trans_x, v_trans_y );
  22993. } else {
  22994. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  22995. }
  22996. } else {
  22997. // handle special case of collinear edges
  22998. let direction_eq = false; // assumes: opposite
  22999. if ( v_prev_x > Number.EPSILON ) {
  23000. if ( v_next_x > Number.EPSILON ) {
  23001. direction_eq = true;
  23002. }
  23003. } else {
  23004. if ( v_prev_x < - Number.EPSILON ) {
  23005. if ( v_next_x < - Number.EPSILON ) {
  23006. direction_eq = true;
  23007. }
  23008. } else {
  23009. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  23010. direction_eq = true;
  23011. }
  23012. }
  23013. }
  23014. if ( direction_eq ) {
  23015. // console.log("Warning: lines are a straight sequence");
  23016. v_trans_x = - v_prev_y;
  23017. v_trans_y = v_prev_x;
  23018. shrink_by = Math.sqrt( v_prev_lensq );
  23019. } else {
  23020. // console.log("Warning: lines are a straight spike");
  23021. v_trans_x = v_prev_x;
  23022. v_trans_y = v_prev_y;
  23023. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  23024. }
  23025. }
  23026. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  23027. }
  23028. const contourMovements = [];
  23029. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23030. if ( j === il ) j = 0;
  23031. if ( k === il ) k = 0;
  23032. // (j)---(i)---(k)
  23033. // console.log('i,j,k', i, j , k)
  23034. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  23035. }
  23036. const holesMovements = [];
  23037. let oneHoleMovements, verticesMovements = contourMovements.concat();
  23038. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23039. const ahole = holes[ h ];
  23040. oneHoleMovements = [];
  23041. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23042. if ( j === il ) j = 0;
  23043. if ( k === il ) k = 0;
  23044. // (j)---(i)---(k)
  23045. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  23046. }
  23047. holesMovements.push( oneHoleMovements );
  23048. verticesMovements = verticesMovements.concat( oneHoleMovements );
  23049. }
  23050. // Loop bevelSegments, 1 for the front, 1 for the back
  23051. for ( let b = 0; b < bevelSegments; b ++ ) {
  23052. //for ( b = bevelSegments; b > 0; b -- ) {
  23053. const t = b / bevelSegments;
  23054. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23055. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23056. // contract shape
  23057. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23058. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23059. v( vert.x, vert.y, - z );
  23060. }
  23061. // expand holes
  23062. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23063. const ahole = holes[ h ];
  23064. oneHoleMovements = holesMovements[ h ];
  23065. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23066. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23067. v( vert.x, vert.y, - z );
  23068. }
  23069. }
  23070. }
  23071. const bs = bevelSize + bevelOffset;
  23072. // Back facing vertices
  23073. for ( let i = 0; i < vlen; i ++ ) {
  23074. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23075. if ( ! extrudeByPath ) {
  23076. v( vert.x, vert.y, 0 );
  23077. } else {
  23078. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  23079. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  23080. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  23081. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  23082. v( position2.x, position2.y, position2.z );
  23083. }
  23084. }
  23085. // Add stepped vertices...
  23086. // Including front facing vertices
  23087. for ( let s = 1; s <= steps; s ++ ) {
  23088. for ( let i = 0; i < vlen; i ++ ) {
  23089. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23090. if ( ! extrudeByPath ) {
  23091. v( vert.x, vert.y, depth / steps * s );
  23092. } else {
  23093. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  23094. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  23095. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  23096. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  23097. v( position2.x, position2.y, position2.z );
  23098. }
  23099. }
  23100. }
  23101. // Add bevel segments planes
  23102. //for ( b = 1; b <= bevelSegments; b ++ ) {
  23103. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  23104. const t = b / bevelSegments;
  23105. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23106. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23107. // contract shape
  23108. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23109. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23110. v( vert.x, vert.y, depth + z );
  23111. }
  23112. // expand holes
  23113. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23114. const ahole = holes[ h ];
  23115. oneHoleMovements = holesMovements[ h ];
  23116. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23117. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23118. if ( ! extrudeByPath ) {
  23119. v( vert.x, vert.y, depth + z );
  23120. } else {
  23121. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  23122. }
  23123. }
  23124. }
  23125. }
  23126. /* Faces */
  23127. // Top and bottom faces
  23128. buildLidFaces();
  23129. // Sides faces
  23130. buildSideFaces();
  23131. ///// Internal functions
  23132. function buildLidFaces() {
  23133. const start = verticesArray.length / 3;
  23134. if ( bevelEnabled ) {
  23135. let layer = 0; // steps + 1
  23136. let offset = vlen * layer;
  23137. // Bottom faces
  23138. for ( let i = 0; i < flen; i ++ ) {
  23139. const face = faces[ i ];
  23140. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  23141. }
  23142. layer = steps + bevelSegments * 2;
  23143. offset = vlen * layer;
  23144. // Top faces
  23145. for ( let i = 0; i < flen; i ++ ) {
  23146. const face = faces[ i ];
  23147. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23148. }
  23149. } else {
  23150. // Bottom faces
  23151. for ( let i = 0; i < flen; i ++ ) {
  23152. const face = faces[ i ];
  23153. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23154. }
  23155. // Top faces
  23156. for ( let i = 0; i < flen; i ++ ) {
  23157. const face = faces[ i ];
  23158. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23159. }
  23160. }
  23161. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23162. }
  23163. // Create faces for the z-sides of the shape
  23164. function buildSideFaces() {
  23165. const start = verticesArray.length / 3;
  23166. let layeroffset = 0;
  23167. sidewalls( contour, layeroffset );
  23168. layeroffset += contour.length;
  23169. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23170. const ahole = holes[ h ];
  23171. sidewalls( ahole, layeroffset );
  23172. //, true
  23173. layeroffset += ahole.length;
  23174. }
  23175. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23176. }
  23177. function sidewalls( contour, layeroffset ) {
  23178. let i = contour.length;
  23179. while ( -- i >= 0 ) {
  23180. const j = i;
  23181. let k = i - 1;
  23182. if ( k < 0 ) k = contour.length - 1;
  23183. //console.log('b', i,j, i-1, k,vertices.length);
  23184. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  23185. const slen1 = vlen * s;
  23186. const slen2 = vlen * ( s + 1 );
  23187. const a = layeroffset + j + slen1,
  23188. b = layeroffset + k + slen1,
  23189. c = layeroffset + k + slen2,
  23190. d = layeroffset + j + slen2;
  23191. f4( a, b, c, d );
  23192. }
  23193. }
  23194. }
  23195. function v( x, y, z ) {
  23196. placeholder.push( x );
  23197. placeholder.push( y );
  23198. placeholder.push( z );
  23199. }
  23200. function f3( a, b, c ) {
  23201. addVertex( a );
  23202. addVertex( b );
  23203. addVertex( c );
  23204. const nextIndex = verticesArray.length / 3;
  23205. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23206. addUV( uvs[ 0 ] );
  23207. addUV( uvs[ 1 ] );
  23208. addUV( uvs[ 2 ] );
  23209. }
  23210. function f4( a, b, c, d ) {
  23211. addVertex( a );
  23212. addVertex( b );
  23213. addVertex( d );
  23214. addVertex( b );
  23215. addVertex( c );
  23216. addVertex( d );
  23217. const nextIndex = verticesArray.length / 3;
  23218. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23219. addUV( uvs[ 0 ] );
  23220. addUV( uvs[ 1 ] );
  23221. addUV( uvs[ 3 ] );
  23222. addUV( uvs[ 1 ] );
  23223. addUV( uvs[ 2 ] );
  23224. addUV( uvs[ 3 ] );
  23225. }
  23226. function addVertex( index ) {
  23227. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23228. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23229. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23230. }
  23231. function addUV( vector2 ) {
  23232. uvArray.push( vector2.x );
  23233. uvArray.push( vector2.y );
  23234. }
  23235. }
  23236. }
  23237. copy( source ) {
  23238. super.copy( source );
  23239. this.parameters = Object.assign( {}, source.parameters );
  23240. return this;
  23241. }
  23242. toJSON() {
  23243. const data = super.toJSON();
  23244. const shapes = this.parameters.shapes;
  23245. const options = this.parameters.options;
  23246. return toJSON$1( shapes, options, data );
  23247. }
  23248. static fromJSON( data, shapes ) {
  23249. const geometryShapes = [];
  23250. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23251. const shape = shapes[ data.shapes[ j ] ];
  23252. geometryShapes.push( shape );
  23253. }
  23254. const extrudePath = data.options.extrudePath;
  23255. if ( extrudePath !== undefined ) {
  23256. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23257. }
  23258. return new ExtrudeGeometry( geometryShapes, data.options );
  23259. }
  23260. }
  23261. const WorldUVGenerator = {
  23262. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23263. const a_x = vertices[ indexA * 3 ];
  23264. const a_y = vertices[ indexA * 3 + 1 ];
  23265. const b_x = vertices[ indexB * 3 ];
  23266. const b_y = vertices[ indexB * 3 + 1 ];
  23267. const c_x = vertices[ indexC * 3 ];
  23268. const c_y = vertices[ indexC * 3 + 1 ];
  23269. return [
  23270. new Vector2( a_x, a_y ),
  23271. new Vector2( b_x, b_y ),
  23272. new Vector2( c_x, c_y )
  23273. ];
  23274. },
  23275. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23276. const a_x = vertices[ indexA * 3 ];
  23277. const a_y = vertices[ indexA * 3 + 1 ];
  23278. const a_z = vertices[ indexA * 3 + 2 ];
  23279. const b_x = vertices[ indexB * 3 ];
  23280. const b_y = vertices[ indexB * 3 + 1 ];
  23281. const b_z = vertices[ indexB * 3 + 2 ];
  23282. const c_x = vertices[ indexC * 3 ];
  23283. const c_y = vertices[ indexC * 3 + 1 ];
  23284. const c_z = vertices[ indexC * 3 + 2 ];
  23285. const d_x = vertices[ indexD * 3 ];
  23286. const d_y = vertices[ indexD * 3 + 1 ];
  23287. const d_z = vertices[ indexD * 3 + 2 ];
  23288. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  23289. return [
  23290. new Vector2( a_x, 1 - a_z ),
  23291. new Vector2( b_x, 1 - b_z ),
  23292. new Vector2( c_x, 1 - c_z ),
  23293. new Vector2( d_x, 1 - d_z )
  23294. ];
  23295. } else {
  23296. return [
  23297. new Vector2( a_y, 1 - a_z ),
  23298. new Vector2( b_y, 1 - b_z ),
  23299. new Vector2( c_y, 1 - c_z ),
  23300. new Vector2( d_y, 1 - d_z )
  23301. ];
  23302. }
  23303. }
  23304. };
  23305. function toJSON$1( shapes, options, data ) {
  23306. data.shapes = [];
  23307. if ( Array.isArray( shapes ) ) {
  23308. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23309. const shape = shapes[ i ];
  23310. data.shapes.push( shape.uuid );
  23311. }
  23312. } else {
  23313. data.shapes.push( shapes.uuid );
  23314. }
  23315. data.options = Object.assign( {}, options );
  23316. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  23317. return data;
  23318. }
  23319. class IcosahedronGeometry extends PolyhedronGeometry {
  23320. constructor( radius = 1, detail = 0 ) {
  23321. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23322. const vertices = [
  23323. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23324. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23325. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23326. ];
  23327. const indices = [
  23328. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23329. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23330. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23331. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23332. ];
  23333. super( vertices, indices, radius, detail );
  23334. this.type = 'IcosahedronGeometry';
  23335. this.parameters = {
  23336. radius: radius,
  23337. detail: detail
  23338. };
  23339. }
  23340. static fromJSON( data ) {
  23341. return new IcosahedronGeometry( data.radius, data.detail );
  23342. }
  23343. }
  23344. class OctahedronGeometry extends PolyhedronGeometry {
  23345. constructor( radius = 1, detail = 0 ) {
  23346. const vertices = [
  23347. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23348. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23349. ];
  23350. const indices = [
  23351. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23352. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23353. 1, 3, 4, 1, 4, 2
  23354. ];
  23355. super( vertices, indices, radius, detail );
  23356. this.type = 'OctahedronGeometry';
  23357. this.parameters = {
  23358. radius: radius,
  23359. detail: detail
  23360. };
  23361. }
  23362. static fromJSON( data ) {
  23363. return new OctahedronGeometry( data.radius, data.detail );
  23364. }
  23365. }
  23366. class RingGeometry extends BufferGeometry {
  23367. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23368. super();
  23369. this.type = 'RingGeometry';
  23370. this.parameters = {
  23371. innerRadius: innerRadius,
  23372. outerRadius: outerRadius,
  23373. thetaSegments: thetaSegments,
  23374. phiSegments: phiSegments,
  23375. thetaStart: thetaStart,
  23376. thetaLength: thetaLength
  23377. };
  23378. thetaSegments = Math.max( 3, thetaSegments );
  23379. phiSegments = Math.max( 1, phiSegments );
  23380. // buffers
  23381. const indices = [];
  23382. const vertices = [];
  23383. const normals = [];
  23384. const uvs = [];
  23385. // some helper variables
  23386. let radius = innerRadius;
  23387. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23388. const vertex = new Vector3();
  23389. const uv = new Vector2();
  23390. // generate vertices, normals and uvs
  23391. for ( let j = 0; j <= phiSegments; j ++ ) {
  23392. for ( let i = 0; i <= thetaSegments; i ++ ) {
  23393. // values are generate from the inside of the ring to the outside
  23394. const segment = thetaStart + i / thetaSegments * thetaLength;
  23395. // vertex
  23396. vertex.x = radius * Math.cos( segment );
  23397. vertex.y = radius * Math.sin( segment );
  23398. vertices.push( vertex.x, vertex.y, vertex.z );
  23399. // normal
  23400. normals.push( 0, 0, 1 );
  23401. // uv
  23402. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23403. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23404. uvs.push( uv.x, uv.y );
  23405. }
  23406. // increase the radius for next row of vertices
  23407. radius += radiusStep;
  23408. }
  23409. // indices
  23410. for ( let j = 0; j < phiSegments; j ++ ) {
  23411. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  23412. for ( let i = 0; i < thetaSegments; i ++ ) {
  23413. const segment = i + thetaSegmentLevel;
  23414. const a = segment;
  23415. const b = segment + thetaSegments + 1;
  23416. const c = segment + thetaSegments + 2;
  23417. const d = segment + 1;
  23418. // faces
  23419. indices.push( a, b, d );
  23420. indices.push( b, c, d );
  23421. }
  23422. }
  23423. // build geometry
  23424. this.setIndex( indices );
  23425. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23426. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23427. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23428. }
  23429. copy( source ) {
  23430. super.copy( source );
  23431. this.parameters = Object.assign( {}, source.parameters );
  23432. return this;
  23433. }
  23434. static fromJSON( data ) {
  23435. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  23436. }
  23437. }
  23438. class ShapeGeometry extends BufferGeometry {
  23439. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  23440. super();
  23441. this.type = 'ShapeGeometry';
  23442. this.parameters = {
  23443. shapes: shapes,
  23444. curveSegments: curveSegments
  23445. };
  23446. // buffers
  23447. const indices = [];
  23448. const vertices = [];
  23449. const normals = [];
  23450. const uvs = [];
  23451. // helper variables
  23452. let groupStart = 0;
  23453. let groupCount = 0;
  23454. // allow single and array values for "shapes" parameter
  23455. if ( Array.isArray( shapes ) === false ) {
  23456. addShape( shapes );
  23457. } else {
  23458. for ( let i = 0; i < shapes.length; i ++ ) {
  23459. addShape( shapes[ i ] );
  23460. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23461. groupStart += groupCount;
  23462. groupCount = 0;
  23463. }
  23464. }
  23465. // build geometry
  23466. this.setIndex( indices );
  23467. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23468. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23469. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23470. // helper functions
  23471. function addShape( shape ) {
  23472. const indexOffset = vertices.length / 3;
  23473. const points = shape.extractPoints( curveSegments );
  23474. let shapeVertices = points.shape;
  23475. const shapeHoles = points.holes;
  23476. // check direction of vertices
  23477. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23478. shapeVertices = shapeVertices.reverse();
  23479. }
  23480. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23481. const shapeHole = shapeHoles[ i ];
  23482. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23483. shapeHoles[ i ] = shapeHole.reverse();
  23484. }
  23485. }
  23486. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23487. // join vertices of inner and outer paths to a single array
  23488. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23489. const shapeHole = shapeHoles[ i ];
  23490. shapeVertices = shapeVertices.concat( shapeHole );
  23491. }
  23492. // vertices, normals, uvs
  23493. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23494. const vertex = shapeVertices[ i ];
  23495. vertices.push( vertex.x, vertex.y, 0 );
  23496. normals.push( 0, 0, 1 );
  23497. uvs.push( vertex.x, vertex.y ); // world uvs
  23498. }
  23499. // indices
  23500. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  23501. const face = faces[ i ];
  23502. const a = face[ 0 ] + indexOffset;
  23503. const b = face[ 1 ] + indexOffset;
  23504. const c = face[ 2 ] + indexOffset;
  23505. indices.push( a, b, c );
  23506. groupCount += 3;
  23507. }
  23508. }
  23509. }
  23510. copy( source ) {
  23511. super.copy( source );
  23512. this.parameters = Object.assign( {}, source.parameters );
  23513. return this;
  23514. }
  23515. toJSON() {
  23516. const data = super.toJSON();
  23517. const shapes = this.parameters.shapes;
  23518. return toJSON( shapes, data );
  23519. }
  23520. static fromJSON( data, shapes ) {
  23521. const geometryShapes = [];
  23522. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23523. const shape = shapes[ data.shapes[ j ] ];
  23524. geometryShapes.push( shape );
  23525. }
  23526. return new ShapeGeometry( geometryShapes, data.curveSegments );
  23527. }
  23528. }
  23529. function toJSON( shapes, data ) {
  23530. data.shapes = [];
  23531. if ( Array.isArray( shapes ) ) {
  23532. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23533. const shape = shapes[ i ];
  23534. data.shapes.push( shape.uuid );
  23535. }
  23536. } else {
  23537. data.shapes.push( shapes.uuid );
  23538. }
  23539. return data;
  23540. }
  23541. class SphereGeometry extends BufferGeometry {
  23542. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  23543. super();
  23544. this.type = 'SphereGeometry';
  23545. this.parameters = {
  23546. radius: radius,
  23547. widthSegments: widthSegments,
  23548. heightSegments: heightSegments,
  23549. phiStart: phiStart,
  23550. phiLength: phiLength,
  23551. thetaStart: thetaStart,
  23552. thetaLength: thetaLength
  23553. };
  23554. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  23555. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  23556. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  23557. let index = 0;
  23558. const grid = [];
  23559. const vertex = new Vector3();
  23560. const normal = new Vector3();
  23561. // buffers
  23562. const indices = [];
  23563. const vertices = [];
  23564. const normals = [];
  23565. const uvs = [];
  23566. // generate vertices, normals and uvs
  23567. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  23568. const verticesRow = [];
  23569. const v = iy / heightSegments;
  23570. // special case for the poles
  23571. let uOffset = 0;
  23572. if ( iy === 0 && thetaStart === 0 ) {
  23573. uOffset = 0.5 / widthSegments;
  23574. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  23575. uOffset = - 0.5 / widthSegments;
  23576. }
  23577. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  23578. const u = ix / widthSegments;
  23579. // vertex
  23580. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23581. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  23582. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23583. vertices.push( vertex.x, vertex.y, vertex.z );
  23584. // normal
  23585. normal.copy( vertex ).normalize();
  23586. normals.push( normal.x, normal.y, normal.z );
  23587. // uv
  23588. uvs.push( u + uOffset, 1 - v );
  23589. verticesRow.push( index ++ );
  23590. }
  23591. grid.push( verticesRow );
  23592. }
  23593. // indices
  23594. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  23595. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  23596. const a = grid[ iy ][ ix + 1 ];
  23597. const b = grid[ iy ][ ix ];
  23598. const c = grid[ iy + 1 ][ ix ];
  23599. const d = grid[ iy + 1 ][ ix + 1 ];
  23600. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  23601. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  23602. }
  23603. }
  23604. // build geometry
  23605. this.setIndex( indices );
  23606. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23607. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23608. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23609. }
  23610. copy( source ) {
  23611. super.copy( source );
  23612. this.parameters = Object.assign( {}, source.parameters );
  23613. return this;
  23614. }
  23615. static fromJSON( data ) {
  23616. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  23617. }
  23618. }
  23619. class TetrahedronGeometry extends PolyhedronGeometry {
  23620. constructor( radius = 1, detail = 0 ) {
  23621. const vertices = [
  23622. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23623. ];
  23624. const indices = [
  23625. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23626. ];
  23627. super( vertices, indices, radius, detail );
  23628. this.type = 'TetrahedronGeometry';
  23629. this.parameters = {
  23630. radius: radius,
  23631. detail: detail
  23632. };
  23633. }
  23634. static fromJSON( data ) {
  23635. return new TetrahedronGeometry( data.radius, data.detail );
  23636. }
  23637. }
  23638. class TorusGeometry extends BufferGeometry {
  23639. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  23640. super();
  23641. this.type = 'TorusGeometry';
  23642. this.parameters = {
  23643. radius: radius,
  23644. tube: tube,
  23645. radialSegments: radialSegments,
  23646. tubularSegments: tubularSegments,
  23647. arc: arc
  23648. };
  23649. radialSegments = Math.floor( radialSegments );
  23650. tubularSegments = Math.floor( tubularSegments );
  23651. // buffers
  23652. const indices = [];
  23653. const vertices = [];
  23654. const normals = [];
  23655. const uvs = [];
  23656. // helper variables
  23657. const center = new Vector3();
  23658. const vertex = new Vector3();
  23659. const normal = new Vector3();
  23660. // generate vertices, normals and uvs
  23661. for ( let j = 0; j <= radialSegments; j ++ ) {
  23662. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23663. const u = i / tubularSegments * arc;
  23664. const v = j / radialSegments * Math.PI * 2;
  23665. // vertex
  23666. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23667. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23668. vertex.z = tube * Math.sin( v );
  23669. vertices.push( vertex.x, vertex.y, vertex.z );
  23670. // normal
  23671. center.x = radius * Math.cos( u );
  23672. center.y = radius * Math.sin( u );
  23673. normal.subVectors( vertex, center ).normalize();
  23674. normals.push( normal.x, normal.y, normal.z );
  23675. // uv
  23676. uvs.push( i / tubularSegments );
  23677. uvs.push( j / radialSegments );
  23678. }
  23679. }
  23680. // generate indices
  23681. for ( let j = 1; j <= radialSegments; j ++ ) {
  23682. for ( let i = 1; i <= tubularSegments; i ++ ) {
  23683. // indices
  23684. const a = ( tubularSegments + 1 ) * j + i - 1;
  23685. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23686. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23687. const d = ( tubularSegments + 1 ) * j + i;
  23688. // faces
  23689. indices.push( a, b, d );
  23690. indices.push( b, c, d );
  23691. }
  23692. }
  23693. // build geometry
  23694. this.setIndex( indices );
  23695. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23696. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23697. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23698. }
  23699. copy( source ) {
  23700. super.copy( source );
  23701. this.parameters = Object.assign( {}, source.parameters );
  23702. return this;
  23703. }
  23704. static fromJSON( data ) {
  23705. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  23706. }
  23707. }
  23708. class TorusKnotGeometry extends BufferGeometry {
  23709. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  23710. super();
  23711. this.type = 'TorusKnotGeometry';
  23712. this.parameters = {
  23713. radius: radius,
  23714. tube: tube,
  23715. tubularSegments: tubularSegments,
  23716. radialSegments: radialSegments,
  23717. p: p,
  23718. q: q
  23719. };
  23720. tubularSegments = Math.floor( tubularSegments );
  23721. radialSegments = Math.floor( radialSegments );
  23722. // buffers
  23723. const indices = [];
  23724. const vertices = [];
  23725. const normals = [];
  23726. const uvs = [];
  23727. // helper variables
  23728. const vertex = new Vector3();
  23729. const normal = new Vector3();
  23730. const P1 = new Vector3();
  23731. const P2 = new Vector3();
  23732. const B = new Vector3();
  23733. const T = new Vector3();
  23734. const N = new Vector3();
  23735. // generate vertices, normals and uvs
  23736. for ( let i = 0; i <= tubularSegments; ++ i ) {
  23737. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  23738. const u = i / tubularSegments * p * Math.PI * 2;
  23739. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23740. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23741. calculatePositionOnCurve( u, p, q, radius, P1 );
  23742. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23743. // calculate orthonormal basis
  23744. T.subVectors( P2, P1 );
  23745. N.addVectors( P2, P1 );
  23746. B.crossVectors( T, N );
  23747. N.crossVectors( B, T );
  23748. // normalize B, N. T can be ignored, we don't use it
  23749. B.normalize();
  23750. N.normalize();
  23751. for ( let j = 0; j <= radialSegments; ++ j ) {
  23752. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23753. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23754. const v = j / radialSegments * Math.PI * 2;
  23755. const cx = - tube * Math.cos( v );
  23756. const cy = tube * Math.sin( v );
  23757. // now calculate the final vertex position.
  23758. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  23759. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23760. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23761. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23762. vertices.push( vertex.x, vertex.y, vertex.z );
  23763. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23764. normal.subVectors( vertex, P1 ).normalize();
  23765. normals.push( normal.x, normal.y, normal.z );
  23766. // uv
  23767. uvs.push( i / tubularSegments );
  23768. uvs.push( j / radialSegments );
  23769. }
  23770. }
  23771. // generate indices
  23772. for ( let j = 1; j <= tubularSegments; j ++ ) {
  23773. for ( let i = 1; i <= radialSegments; i ++ ) {
  23774. // indices
  23775. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23776. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  23777. const c = ( radialSegments + 1 ) * j + i;
  23778. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23779. // faces
  23780. indices.push( a, b, d );
  23781. indices.push( b, c, d );
  23782. }
  23783. }
  23784. // build geometry
  23785. this.setIndex( indices );
  23786. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23787. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23788. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23789. // this function calculates the current position on the torus curve
  23790. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23791. const cu = Math.cos( u );
  23792. const su = Math.sin( u );
  23793. const quOverP = q / p * u;
  23794. const cs = Math.cos( quOverP );
  23795. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23796. position.y = radius * ( 2 + cs ) * su * 0.5;
  23797. position.z = radius * Math.sin( quOverP ) * 0.5;
  23798. }
  23799. }
  23800. copy( source ) {
  23801. super.copy( source );
  23802. this.parameters = Object.assign( {}, source.parameters );
  23803. return this;
  23804. }
  23805. static fromJSON( data ) {
  23806. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  23807. }
  23808. }
  23809. class TubeGeometry extends BufferGeometry {
  23810. 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 ) {
  23811. super();
  23812. this.type = 'TubeGeometry';
  23813. this.parameters = {
  23814. path: path,
  23815. tubularSegments: tubularSegments,
  23816. radius: radius,
  23817. radialSegments: radialSegments,
  23818. closed: closed
  23819. };
  23820. const frames = path.computeFrenetFrames( tubularSegments, closed );
  23821. // expose internals
  23822. this.tangents = frames.tangents;
  23823. this.normals = frames.normals;
  23824. this.binormals = frames.binormals;
  23825. // helper variables
  23826. const vertex = new Vector3();
  23827. const normal = new Vector3();
  23828. const uv = new Vector2();
  23829. let P = new Vector3();
  23830. // buffer
  23831. const vertices = [];
  23832. const normals = [];
  23833. const uvs = [];
  23834. const indices = [];
  23835. // create buffer data
  23836. generateBufferData();
  23837. // build geometry
  23838. this.setIndex( indices );
  23839. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23840. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23841. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23842. // functions
  23843. function generateBufferData() {
  23844. for ( let i = 0; i < tubularSegments; i ++ ) {
  23845. generateSegment( i );
  23846. }
  23847. // if the geometry is not closed, generate the last row of vertices and normals
  23848. // at the regular position on the given path
  23849. //
  23850. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  23851. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  23852. // uvs are generated in a separate function.
  23853. // this makes it easy compute correct values for closed geometries
  23854. generateUVs();
  23855. // finally create faces
  23856. generateIndices();
  23857. }
  23858. function generateSegment( i ) {
  23859. // we use getPointAt to sample evenly distributed points from the given path
  23860. P = path.getPointAt( i / tubularSegments, P );
  23861. // retrieve corresponding normal and binormal
  23862. const N = frames.normals[ i ];
  23863. const B = frames.binormals[ i ];
  23864. // generate normals and vertices for the current segment
  23865. for ( let j = 0; j <= radialSegments; j ++ ) {
  23866. const v = j / radialSegments * Math.PI * 2;
  23867. const sin = Math.sin( v );
  23868. const cos = - Math.cos( v );
  23869. // normal
  23870. normal.x = ( cos * N.x + sin * B.x );
  23871. normal.y = ( cos * N.y + sin * B.y );
  23872. normal.z = ( cos * N.z + sin * B.z );
  23873. normal.normalize();
  23874. normals.push( normal.x, normal.y, normal.z );
  23875. // vertex
  23876. vertex.x = P.x + radius * normal.x;
  23877. vertex.y = P.y + radius * normal.y;
  23878. vertex.z = P.z + radius * normal.z;
  23879. vertices.push( vertex.x, vertex.y, vertex.z );
  23880. }
  23881. }
  23882. function generateIndices() {
  23883. for ( let j = 1; j <= tubularSegments; j ++ ) {
  23884. for ( let i = 1; i <= radialSegments; i ++ ) {
  23885. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23886. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  23887. const c = ( radialSegments + 1 ) * j + i;
  23888. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23889. // faces
  23890. indices.push( a, b, d );
  23891. indices.push( b, c, d );
  23892. }
  23893. }
  23894. }
  23895. function generateUVs() {
  23896. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23897. for ( let j = 0; j <= radialSegments; j ++ ) {
  23898. uv.x = i / tubularSegments;
  23899. uv.y = j / radialSegments;
  23900. uvs.push( uv.x, uv.y );
  23901. }
  23902. }
  23903. }
  23904. }
  23905. copy( source ) {
  23906. super.copy( source );
  23907. this.parameters = Object.assign( {}, source.parameters );
  23908. return this;
  23909. }
  23910. toJSON() {
  23911. const data = super.toJSON();
  23912. data.path = this.parameters.path.toJSON();
  23913. return data;
  23914. }
  23915. static fromJSON( data ) {
  23916. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23917. // User defined curves or instances of CurvePath will not be deserialized.
  23918. return new TubeGeometry(
  23919. new Curves[ data.path.type ]().fromJSON( data.path ),
  23920. data.tubularSegments,
  23921. data.radius,
  23922. data.radialSegments,
  23923. data.closed
  23924. );
  23925. }
  23926. }
  23927. class WireframeGeometry extends BufferGeometry {
  23928. constructor( geometry = null ) {
  23929. super();
  23930. this.type = 'WireframeGeometry';
  23931. this.parameters = {
  23932. geometry: geometry
  23933. };
  23934. if ( geometry !== null ) {
  23935. // buffer
  23936. const vertices = [];
  23937. const edges = new Set();
  23938. // helper variables
  23939. const start = new Vector3();
  23940. const end = new Vector3();
  23941. if ( geometry.index !== null ) {
  23942. // indexed BufferGeometry
  23943. const position = geometry.attributes.position;
  23944. const indices = geometry.index;
  23945. let groups = geometry.groups;
  23946. if ( groups.length === 0 ) {
  23947. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  23948. }
  23949. // create a data structure that contains all edges without duplicates
  23950. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  23951. const group = groups[ o ];
  23952. const groupStart = group.start;
  23953. const groupCount = group.count;
  23954. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  23955. for ( let j = 0; j < 3; j ++ ) {
  23956. const index1 = indices.getX( i + j );
  23957. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  23958. start.fromBufferAttribute( position, index1 );
  23959. end.fromBufferAttribute( position, index2 );
  23960. if ( isUniqueEdge( start, end, edges ) === true ) {
  23961. vertices.push( start.x, start.y, start.z );
  23962. vertices.push( end.x, end.y, end.z );
  23963. }
  23964. }
  23965. }
  23966. }
  23967. } else {
  23968. // non-indexed BufferGeometry
  23969. const position = geometry.attributes.position;
  23970. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  23971. for ( let j = 0; j < 3; j ++ ) {
  23972. // three edges per triangle, an edge is represented as (index1, index2)
  23973. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  23974. const index1 = 3 * i + j;
  23975. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  23976. start.fromBufferAttribute( position, index1 );
  23977. end.fromBufferAttribute( position, index2 );
  23978. if ( isUniqueEdge( start, end, edges ) === true ) {
  23979. vertices.push( start.x, start.y, start.z );
  23980. vertices.push( end.x, end.y, end.z );
  23981. }
  23982. }
  23983. }
  23984. }
  23985. // build geometry
  23986. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23987. }
  23988. }
  23989. copy( source ) {
  23990. super.copy( source );
  23991. this.parameters = Object.assign( {}, source.parameters );
  23992. return this;
  23993. }
  23994. }
  23995. function isUniqueEdge( start, end, edges ) {
  23996. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  23997. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  23998. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  23999. return false;
  24000. } else {
  24001. edges.add( hash1 );
  24002. edges.add( hash2 );
  24003. return true;
  24004. }
  24005. }
  24006. var Geometries = /*#__PURE__*/Object.freeze({
  24007. __proto__: null,
  24008. BoxGeometry: BoxGeometry,
  24009. CapsuleGeometry: CapsuleGeometry,
  24010. CircleGeometry: CircleGeometry,
  24011. ConeGeometry: ConeGeometry,
  24012. CylinderGeometry: CylinderGeometry,
  24013. DodecahedronGeometry: DodecahedronGeometry,
  24014. EdgesGeometry: EdgesGeometry,
  24015. ExtrudeGeometry: ExtrudeGeometry,
  24016. IcosahedronGeometry: IcosahedronGeometry,
  24017. LatheGeometry: LatheGeometry,
  24018. OctahedronGeometry: OctahedronGeometry,
  24019. PlaneGeometry: PlaneGeometry,
  24020. PolyhedronGeometry: PolyhedronGeometry,
  24021. RingGeometry: RingGeometry,
  24022. ShapeGeometry: ShapeGeometry,
  24023. SphereGeometry: SphereGeometry,
  24024. TetrahedronGeometry: TetrahedronGeometry,
  24025. TorusGeometry: TorusGeometry,
  24026. TorusKnotGeometry: TorusKnotGeometry,
  24027. TubeGeometry: TubeGeometry,
  24028. WireframeGeometry: WireframeGeometry
  24029. });
  24030. class ShadowMaterial extends Material {
  24031. constructor( parameters ) {
  24032. super();
  24033. this.isShadowMaterial = true;
  24034. this.type = 'ShadowMaterial';
  24035. this.color = new Color( 0x000000 );
  24036. this.transparent = true;
  24037. this.fog = true;
  24038. this.setValues( parameters );
  24039. }
  24040. copy( source ) {
  24041. super.copy( source );
  24042. this.color.copy( source.color );
  24043. this.fog = source.fog;
  24044. return this;
  24045. }
  24046. }
  24047. class RawShaderMaterial extends ShaderMaterial {
  24048. constructor( parameters ) {
  24049. super( parameters );
  24050. this.isRawShaderMaterial = true;
  24051. this.type = 'RawShaderMaterial';
  24052. }
  24053. }
  24054. class MeshStandardMaterial extends Material {
  24055. constructor( parameters ) {
  24056. super();
  24057. this.isMeshStandardMaterial = true;
  24058. this.defines = { 'STANDARD': '' };
  24059. this.type = 'MeshStandardMaterial';
  24060. this.color = new Color( 0xffffff ); // diffuse
  24061. this.roughness = 1.0;
  24062. this.metalness = 0.0;
  24063. this.map = null;
  24064. this.lightMap = null;
  24065. this.lightMapIntensity = 1.0;
  24066. this.aoMap = null;
  24067. this.aoMapIntensity = 1.0;
  24068. this.emissive = new Color( 0x000000 );
  24069. this.emissiveIntensity = 1.0;
  24070. this.emissiveMap = null;
  24071. this.bumpMap = null;
  24072. this.bumpScale = 1;
  24073. this.normalMap = null;
  24074. this.normalMapType = TangentSpaceNormalMap;
  24075. this.normalScale = new Vector2( 1, 1 );
  24076. this.displacementMap = null;
  24077. this.displacementScale = 1;
  24078. this.displacementBias = 0;
  24079. this.roughnessMap = null;
  24080. this.metalnessMap = null;
  24081. this.alphaMap = null;
  24082. this.envMap = null;
  24083. this.envMapIntensity = 1.0;
  24084. this.wireframe = false;
  24085. this.wireframeLinewidth = 1;
  24086. this.wireframeLinecap = 'round';
  24087. this.wireframeLinejoin = 'round';
  24088. this.flatShading = false;
  24089. this.fog = true;
  24090. this.setValues( parameters );
  24091. }
  24092. copy( source ) {
  24093. super.copy( source );
  24094. this.defines = { 'STANDARD': '' };
  24095. this.color.copy( source.color );
  24096. this.roughness = source.roughness;
  24097. this.metalness = source.metalness;
  24098. this.map = source.map;
  24099. this.lightMap = source.lightMap;
  24100. this.lightMapIntensity = source.lightMapIntensity;
  24101. this.aoMap = source.aoMap;
  24102. this.aoMapIntensity = source.aoMapIntensity;
  24103. this.emissive.copy( source.emissive );
  24104. this.emissiveMap = source.emissiveMap;
  24105. this.emissiveIntensity = source.emissiveIntensity;
  24106. this.bumpMap = source.bumpMap;
  24107. this.bumpScale = source.bumpScale;
  24108. this.normalMap = source.normalMap;
  24109. this.normalMapType = source.normalMapType;
  24110. this.normalScale.copy( source.normalScale );
  24111. this.displacementMap = source.displacementMap;
  24112. this.displacementScale = source.displacementScale;
  24113. this.displacementBias = source.displacementBias;
  24114. this.roughnessMap = source.roughnessMap;
  24115. this.metalnessMap = source.metalnessMap;
  24116. this.alphaMap = source.alphaMap;
  24117. this.envMap = source.envMap;
  24118. this.envMapIntensity = source.envMapIntensity;
  24119. this.wireframe = source.wireframe;
  24120. this.wireframeLinewidth = source.wireframeLinewidth;
  24121. this.wireframeLinecap = source.wireframeLinecap;
  24122. this.wireframeLinejoin = source.wireframeLinejoin;
  24123. this.flatShading = source.flatShading;
  24124. this.fog = source.fog;
  24125. return this;
  24126. }
  24127. }
  24128. class MeshPhysicalMaterial extends MeshStandardMaterial {
  24129. constructor( parameters ) {
  24130. super();
  24131. this.isMeshPhysicalMaterial = true;
  24132. this.defines = {
  24133. 'STANDARD': '',
  24134. 'PHYSICAL': ''
  24135. };
  24136. this.type = 'MeshPhysicalMaterial';
  24137. this.anisotropyRotation = 0;
  24138. this.anisotropyMap = null;
  24139. this.clearcoatMap = null;
  24140. this.clearcoatRoughness = 0.0;
  24141. this.clearcoatRoughnessMap = null;
  24142. this.clearcoatNormalScale = new Vector2( 1, 1 );
  24143. this.clearcoatNormalMap = null;
  24144. this.ior = 1.5;
  24145. Object.defineProperty( this, 'reflectivity', {
  24146. get: function () {
  24147. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  24148. },
  24149. set: function ( reflectivity ) {
  24150. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  24151. }
  24152. } );
  24153. this.iridescenceMap = null;
  24154. this.iridescenceIOR = 1.3;
  24155. this.iridescenceThicknessRange = [ 100, 400 ];
  24156. this.iridescenceThicknessMap = null;
  24157. this.sheenColor = new Color( 0x000000 );
  24158. this.sheenColorMap = null;
  24159. this.sheenRoughness = 1.0;
  24160. this.sheenRoughnessMap = null;
  24161. this.transmissionMap = null;
  24162. this.thickness = 0;
  24163. this.thicknessMap = null;
  24164. this.attenuationDistance = Infinity;
  24165. this.attenuationColor = new Color( 1, 1, 1 );
  24166. this.specularIntensity = 1.0;
  24167. this.specularIntensityMap = null;
  24168. this.specularColor = new Color( 1, 1, 1 );
  24169. this.specularColorMap = null;
  24170. this._anisotropy = 0;
  24171. this._clearcoat = 0;
  24172. this._iridescence = 0;
  24173. this._sheen = 0.0;
  24174. this._transmission = 0;
  24175. this.setValues( parameters );
  24176. }
  24177. get anisotropy() {
  24178. return this._anisotropy;
  24179. }
  24180. set anisotropy( value ) {
  24181. if ( this._anisotropy > 0 !== value > 0 ) {
  24182. this.version ++;
  24183. }
  24184. this._anisotropy = value;
  24185. }
  24186. get clearcoat() {
  24187. return this._clearcoat;
  24188. }
  24189. set clearcoat( value ) {
  24190. if ( this._clearcoat > 0 !== value > 0 ) {
  24191. this.version ++;
  24192. }
  24193. this._clearcoat = value;
  24194. }
  24195. get iridescence() {
  24196. return this._iridescence;
  24197. }
  24198. set iridescence( value ) {
  24199. if ( this._iridescence > 0 !== value > 0 ) {
  24200. this.version ++;
  24201. }
  24202. this._iridescence = value;
  24203. }
  24204. get sheen() {
  24205. return this._sheen;
  24206. }
  24207. set sheen( value ) {
  24208. if ( this._sheen > 0 !== value > 0 ) {
  24209. this.version ++;
  24210. }
  24211. this._sheen = value;
  24212. }
  24213. get transmission() {
  24214. return this._transmission;
  24215. }
  24216. set transmission( value ) {
  24217. if ( this._transmission > 0 !== value > 0 ) {
  24218. this.version ++;
  24219. }
  24220. this._transmission = value;
  24221. }
  24222. copy( source ) {
  24223. super.copy( source );
  24224. this.defines = {
  24225. 'STANDARD': '',
  24226. 'PHYSICAL': ''
  24227. };
  24228. this.anisotropy = source.anisotropy;
  24229. this.anisotropyRotation = source.anisotropyRotation;
  24230. this.anisotropyMap = source.anisotropyMap;
  24231. this.clearcoat = source.clearcoat;
  24232. this.clearcoatMap = source.clearcoatMap;
  24233. this.clearcoatRoughness = source.clearcoatRoughness;
  24234. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  24235. this.clearcoatNormalMap = source.clearcoatNormalMap;
  24236. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  24237. this.ior = source.ior;
  24238. this.iridescence = source.iridescence;
  24239. this.iridescenceMap = source.iridescenceMap;
  24240. this.iridescenceIOR = source.iridescenceIOR;
  24241. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  24242. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  24243. this.sheen = source.sheen;
  24244. this.sheenColor.copy( source.sheenColor );
  24245. this.sheenColorMap = source.sheenColorMap;
  24246. this.sheenRoughness = source.sheenRoughness;
  24247. this.sheenRoughnessMap = source.sheenRoughnessMap;
  24248. this.transmission = source.transmission;
  24249. this.transmissionMap = source.transmissionMap;
  24250. this.thickness = source.thickness;
  24251. this.thicknessMap = source.thicknessMap;
  24252. this.attenuationDistance = source.attenuationDistance;
  24253. this.attenuationColor.copy( source.attenuationColor );
  24254. this.specularIntensity = source.specularIntensity;
  24255. this.specularIntensityMap = source.specularIntensityMap;
  24256. this.specularColor.copy( source.specularColor );
  24257. this.specularColorMap = source.specularColorMap;
  24258. return this;
  24259. }
  24260. }
  24261. class MeshPhongMaterial extends Material {
  24262. constructor( parameters ) {
  24263. super();
  24264. this.isMeshPhongMaterial = true;
  24265. this.type = 'MeshPhongMaterial';
  24266. this.color = new Color( 0xffffff ); // diffuse
  24267. this.specular = new Color( 0x111111 );
  24268. this.shininess = 30;
  24269. this.map = null;
  24270. this.lightMap = null;
  24271. this.lightMapIntensity = 1.0;
  24272. this.aoMap = null;
  24273. this.aoMapIntensity = 1.0;
  24274. this.emissive = new Color( 0x000000 );
  24275. this.emissiveIntensity = 1.0;
  24276. this.emissiveMap = null;
  24277. this.bumpMap = null;
  24278. this.bumpScale = 1;
  24279. this.normalMap = null;
  24280. this.normalMapType = TangentSpaceNormalMap;
  24281. this.normalScale = new Vector2( 1, 1 );
  24282. this.displacementMap = null;
  24283. this.displacementScale = 1;
  24284. this.displacementBias = 0;
  24285. this.specularMap = null;
  24286. this.alphaMap = null;
  24287. this.envMap = null;
  24288. this.combine = MultiplyOperation;
  24289. this.reflectivity = 1;
  24290. this.refractionRatio = 0.98;
  24291. this.wireframe = false;
  24292. this.wireframeLinewidth = 1;
  24293. this.wireframeLinecap = 'round';
  24294. this.wireframeLinejoin = 'round';
  24295. this.flatShading = false;
  24296. this.fog = true;
  24297. this.setValues( parameters );
  24298. }
  24299. copy( source ) {
  24300. super.copy( source );
  24301. this.color.copy( source.color );
  24302. this.specular.copy( source.specular );
  24303. this.shininess = source.shininess;
  24304. this.map = source.map;
  24305. this.lightMap = source.lightMap;
  24306. this.lightMapIntensity = source.lightMapIntensity;
  24307. this.aoMap = source.aoMap;
  24308. this.aoMapIntensity = source.aoMapIntensity;
  24309. this.emissive.copy( source.emissive );
  24310. this.emissiveMap = source.emissiveMap;
  24311. this.emissiveIntensity = source.emissiveIntensity;
  24312. this.bumpMap = source.bumpMap;
  24313. this.bumpScale = source.bumpScale;
  24314. this.normalMap = source.normalMap;
  24315. this.normalMapType = source.normalMapType;
  24316. this.normalScale.copy( source.normalScale );
  24317. this.displacementMap = source.displacementMap;
  24318. this.displacementScale = source.displacementScale;
  24319. this.displacementBias = source.displacementBias;
  24320. this.specularMap = source.specularMap;
  24321. this.alphaMap = source.alphaMap;
  24322. this.envMap = source.envMap;
  24323. this.combine = source.combine;
  24324. this.reflectivity = source.reflectivity;
  24325. this.refractionRatio = source.refractionRatio;
  24326. this.wireframe = source.wireframe;
  24327. this.wireframeLinewidth = source.wireframeLinewidth;
  24328. this.wireframeLinecap = source.wireframeLinecap;
  24329. this.wireframeLinejoin = source.wireframeLinejoin;
  24330. this.flatShading = source.flatShading;
  24331. this.fog = source.fog;
  24332. return this;
  24333. }
  24334. }
  24335. class MeshToonMaterial extends Material {
  24336. constructor( parameters ) {
  24337. super();
  24338. this.isMeshToonMaterial = true;
  24339. this.defines = { 'TOON': '' };
  24340. this.type = 'MeshToonMaterial';
  24341. this.color = new Color( 0xffffff );
  24342. this.map = null;
  24343. this.gradientMap = null;
  24344. this.lightMap = null;
  24345. this.lightMapIntensity = 1.0;
  24346. this.aoMap = null;
  24347. this.aoMapIntensity = 1.0;
  24348. this.emissive = new Color( 0x000000 );
  24349. this.emissiveIntensity = 1.0;
  24350. this.emissiveMap = null;
  24351. this.bumpMap = null;
  24352. this.bumpScale = 1;
  24353. this.normalMap = null;
  24354. this.normalMapType = TangentSpaceNormalMap;
  24355. this.normalScale = new Vector2( 1, 1 );
  24356. this.displacementMap = null;
  24357. this.displacementScale = 1;
  24358. this.displacementBias = 0;
  24359. this.alphaMap = null;
  24360. this.wireframe = false;
  24361. this.wireframeLinewidth = 1;
  24362. this.wireframeLinecap = 'round';
  24363. this.wireframeLinejoin = 'round';
  24364. this.fog = true;
  24365. this.setValues( parameters );
  24366. }
  24367. copy( source ) {
  24368. super.copy( source );
  24369. this.color.copy( source.color );
  24370. this.map = source.map;
  24371. this.gradientMap = source.gradientMap;
  24372. this.lightMap = source.lightMap;
  24373. this.lightMapIntensity = source.lightMapIntensity;
  24374. this.aoMap = source.aoMap;
  24375. this.aoMapIntensity = source.aoMapIntensity;
  24376. this.emissive.copy( source.emissive );
  24377. this.emissiveMap = source.emissiveMap;
  24378. this.emissiveIntensity = source.emissiveIntensity;
  24379. this.bumpMap = source.bumpMap;
  24380. this.bumpScale = source.bumpScale;
  24381. this.normalMap = source.normalMap;
  24382. this.normalMapType = source.normalMapType;
  24383. this.normalScale.copy( source.normalScale );
  24384. this.displacementMap = source.displacementMap;
  24385. this.displacementScale = source.displacementScale;
  24386. this.displacementBias = source.displacementBias;
  24387. this.alphaMap = source.alphaMap;
  24388. this.wireframe = source.wireframe;
  24389. this.wireframeLinewidth = source.wireframeLinewidth;
  24390. this.wireframeLinecap = source.wireframeLinecap;
  24391. this.wireframeLinejoin = source.wireframeLinejoin;
  24392. this.fog = source.fog;
  24393. return this;
  24394. }
  24395. }
  24396. class MeshNormalMaterial extends Material {
  24397. constructor( parameters ) {
  24398. super();
  24399. this.isMeshNormalMaterial = true;
  24400. this.type = 'MeshNormalMaterial';
  24401. this.bumpMap = null;
  24402. this.bumpScale = 1;
  24403. this.normalMap = null;
  24404. this.normalMapType = TangentSpaceNormalMap;
  24405. this.normalScale = new Vector2( 1, 1 );
  24406. this.displacementMap = null;
  24407. this.displacementScale = 1;
  24408. this.displacementBias = 0;
  24409. this.wireframe = false;
  24410. this.wireframeLinewidth = 1;
  24411. this.flatShading = false;
  24412. this.setValues( parameters );
  24413. }
  24414. copy( source ) {
  24415. super.copy( source );
  24416. this.bumpMap = source.bumpMap;
  24417. this.bumpScale = source.bumpScale;
  24418. this.normalMap = source.normalMap;
  24419. this.normalMapType = source.normalMapType;
  24420. this.normalScale.copy( source.normalScale );
  24421. this.displacementMap = source.displacementMap;
  24422. this.displacementScale = source.displacementScale;
  24423. this.displacementBias = source.displacementBias;
  24424. this.wireframe = source.wireframe;
  24425. this.wireframeLinewidth = source.wireframeLinewidth;
  24426. this.flatShading = source.flatShading;
  24427. return this;
  24428. }
  24429. }
  24430. class MeshLambertMaterial extends Material {
  24431. constructor( parameters ) {
  24432. super();
  24433. this.isMeshLambertMaterial = true;
  24434. this.type = 'MeshLambertMaterial';
  24435. this.color = new Color( 0xffffff ); // diffuse
  24436. this.map = null;
  24437. this.lightMap = null;
  24438. this.lightMapIntensity = 1.0;
  24439. this.aoMap = null;
  24440. this.aoMapIntensity = 1.0;
  24441. this.emissive = new Color( 0x000000 );
  24442. this.emissiveIntensity = 1.0;
  24443. this.emissiveMap = null;
  24444. this.bumpMap = null;
  24445. this.bumpScale = 1;
  24446. this.normalMap = null;
  24447. this.normalMapType = TangentSpaceNormalMap;
  24448. this.normalScale = new Vector2( 1, 1 );
  24449. this.displacementMap = null;
  24450. this.displacementScale = 1;
  24451. this.displacementBias = 0;
  24452. this.specularMap = null;
  24453. this.alphaMap = null;
  24454. this.envMap = null;
  24455. this.combine = MultiplyOperation;
  24456. this.reflectivity = 1;
  24457. this.refractionRatio = 0.98;
  24458. this.wireframe = false;
  24459. this.wireframeLinewidth = 1;
  24460. this.wireframeLinecap = 'round';
  24461. this.wireframeLinejoin = 'round';
  24462. this.flatShading = false;
  24463. this.fog = true;
  24464. this.setValues( parameters );
  24465. }
  24466. copy( source ) {
  24467. super.copy( source );
  24468. this.color.copy( source.color );
  24469. this.map = source.map;
  24470. this.lightMap = source.lightMap;
  24471. this.lightMapIntensity = source.lightMapIntensity;
  24472. this.aoMap = source.aoMap;
  24473. this.aoMapIntensity = source.aoMapIntensity;
  24474. this.emissive.copy( source.emissive );
  24475. this.emissiveMap = source.emissiveMap;
  24476. this.emissiveIntensity = source.emissiveIntensity;
  24477. this.bumpMap = source.bumpMap;
  24478. this.bumpScale = source.bumpScale;
  24479. this.normalMap = source.normalMap;
  24480. this.normalMapType = source.normalMapType;
  24481. this.normalScale.copy( source.normalScale );
  24482. this.displacementMap = source.displacementMap;
  24483. this.displacementScale = source.displacementScale;
  24484. this.displacementBias = source.displacementBias;
  24485. this.specularMap = source.specularMap;
  24486. this.alphaMap = source.alphaMap;
  24487. this.envMap = source.envMap;
  24488. this.combine = source.combine;
  24489. this.reflectivity = source.reflectivity;
  24490. this.refractionRatio = source.refractionRatio;
  24491. this.wireframe = source.wireframe;
  24492. this.wireframeLinewidth = source.wireframeLinewidth;
  24493. this.wireframeLinecap = source.wireframeLinecap;
  24494. this.wireframeLinejoin = source.wireframeLinejoin;
  24495. this.flatShading = source.flatShading;
  24496. this.fog = source.fog;
  24497. return this;
  24498. }
  24499. }
  24500. class MeshMatcapMaterial extends Material {
  24501. constructor( parameters ) {
  24502. super();
  24503. this.isMeshMatcapMaterial = true;
  24504. this.defines = { 'MATCAP': '' };
  24505. this.type = 'MeshMatcapMaterial';
  24506. this.color = new Color( 0xffffff ); // diffuse
  24507. this.matcap = null;
  24508. this.map = null;
  24509. this.bumpMap = null;
  24510. this.bumpScale = 1;
  24511. this.normalMap = null;
  24512. this.normalMapType = TangentSpaceNormalMap;
  24513. this.normalScale = new Vector2( 1, 1 );
  24514. this.displacementMap = null;
  24515. this.displacementScale = 1;
  24516. this.displacementBias = 0;
  24517. this.alphaMap = null;
  24518. this.flatShading = false;
  24519. this.fog = true;
  24520. this.setValues( parameters );
  24521. }
  24522. copy( source ) {
  24523. super.copy( source );
  24524. this.defines = { 'MATCAP': '' };
  24525. this.color.copy( source.color );
  24526. this.matcap = source.matcap;
  24527. this.map = source.map;
  24528. this.bumpMap = source.bumpMap;
  24529. this.bumpScale = source.bumpScale;
  24530. this.normalMap = source.normalMap;
  24531. this.normalMapType = source.normalMapType;
  24532. this.normalScale.copy( source.normalScale );
  24533. this.displacementMap = source.displacementMap;
  24534. this.displacementScale = source.displacementScale;
  24535. this.displacementBias = source.displacementBias;
  24536. this.alphaMap = source.alphaMap;
  24537. this.flatShading = source.flatShading;
  24538. this.fog = source.fog;
  24539. return this;
  24540. }
  24541. }
  24542. class LineDashedMaterial extends LineBasicMaterial {
  24543. constructor( parameters ) {
  24544. super();
  24545. this.isLineDashedMaterial = true;
  24546. this.type = 'LineDashedMaterial';
  24547. this.scale = 1;
  24548. this.dashSize = 3;
  24549. this.gapSize = 1;
  24550. this.setValues( parameters );
  24551. }
  24552. copy( source ) {
  24553. super.copy( source );
  24554. this.scale = source.scale;
  24555. this.dashSize = source.dashSize;
  24556. this.gapSize = source.gapSize;
  24557. return this;
  24558. }
  24559. }
  24560. // converts an array to a specific type
  24561. function convertArray( array, type, forceClone ) {
  24562. if ( ! array || // let 'undefined' and 'null' pass
  24563. ! forceClone && array.constructor === type ) return array;
  24564. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24565. return new type( array ); // create typed array
  24566. }
  24567. return Array.prototype.slice.call( array ); // create Array
  24568. }
  24569. function isTypedArray( object ) {
  24570. return ArrayBuffer.isView( object ) &&
  24571. ! ( object instanceof DataView );
  24572. }
  24573. // returns an array by which times and values can be sorted
  24574. function getKeyframeOrder( times ) {
  24575. function compareTime( i, j ) {
  24576. return times[ i ] - times[ j ];
  24577. }
  24578. const n = times.length;
  24579. const result = new Array( n );
  24580. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  24581. result.sort( compareTime );
  24582. return result;
  24583. }
  24584. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24585. function sortedArray( values, stride, order ) {
  24586. const nValues = values.length;
  24587. const result = new values.constructor( nValues );
  24588. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24589. const srcOffset = order[ i ] * stride;
  24590. for ( let j = 0; j !== stride; ++ j ) {
  24591. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24592. }
  24593. }
  24594. return result;
  24595. }
  24596. // function for parsing AOS keyframe formats
  24597. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  24598. let i = 1, key = jsonKeys[ 0 ];
  24599. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24600. key = jsonKeys[ i ++ ];
  24601. }
  24602. if ( key === undefined ) return; // no data
  24603. let value = key[ valuePropertyName ];
  24604. if ( value === undefined ) return; // no data
  24605. if ( Array.isArray( value ) ) {
  24606. do {
  24607. value = key[ valuePropertyName ];
  24608. if ( value !== undefined ) {
  24609. times.push( key.time );
  24610. values.push.apply( values, value ); // push all elements
  24611. }
  24612. key = jsonKeys[ i ++ ];
  24613. } while ( key !== undefined );
  24614. } else if ( value.toArray !== undefined ) {
  24615. // ...assume THREE.Math-ish
  24616. do {
  24617. value = key[ valuePropertyName ];
  24618. if ( value !== undefined ) {
  24619. times.push( key.time );
  24620. value.toArray( values, values.length );
  24621. }
  24622. key = jsonKeys[ i ++ ];
  24623. } while ( key !== undefined );
  24624. } else {
  24625. // otherwise push as-is
  24626. do {
  24627. value = key[ valuePropertyName ];
  24628. if ( value !== undefined ) {
  24629. times.push( key.time );
  24630. values.push( value );
  24631. }
  24632. key = jsonKeys[ i ++ ];
  24633. } while ( key !== undefined );
  24634. }
  24635. }
  24636. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  24637. const clip = sourceClip.clone();
  24638. clip.name = name;
  24639. const tracks = [];
  24640. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24641. const track = clip.tracks[ i ];
  24642. const valueSize = track.getValueSize();
  24643. const times = [];
  24644. const values = [];
  24645. for ( let j = 0; j < track.times.length; ++ j ) {
  24646. const frame = track.times[ j ] * fps;
  24647. if ( frame < startFrame || frame >= endFrame ) continue;
  24648. times.push( track.times[ j ] );
  24649. for ( let k = 0; k < valueSize; ++ k ) {
  24650. values.push( track.values[ j * valueSize + k ] );
  24651. }
  24652. }
  24653. if ( times.length === 0 ) continue;
  24654. track.times = convertArray( times, track.times.constructor );
  24655. track.values = convertArray( values, track.values.constructor );
  24656. tracks.push( track );
  24657. }
  24658. clip.tracks = tracks;
  24659. // find minimum .times value across all tracks in the trimmed clip
  24660. let minStartTime = Infinity;
  24661. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24662. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  24663. minStartTime = clip.tracks[ i ].times[ 0 ];
  24664. }
  24665. }
  24666. // shift all tracks such that clip begins at t=0
  24667. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24668. clip.tracks[ i ].shift( - 1 * minStartTime );
  24669. }
  24670. clip.resetDuration();
  24671. return clip;
  24672. }
  24673. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  24674. if ( fps <= 0 ) fps = 30;
  24675. const numTracks = referenceClip.tracks.length;
  24676. const referenceTime = referenceFrame / fps;
  24677. // Make each track's values relative to the values at the reference frame
  24678. for ( let i = 0; i < numTracks; ++ i ) {
  24679. const referenceTrack = referenceClip.tracks[ i ];
  24680. const referenceTrackType = referenceTrack.ValueTypeName;
  24681. // Skip this track if it's non-numeric
  24682. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  24683. // Find the track in the target clip whose name and type matches the reference track
  24684. const targetTrack = targetClip.tracks.find( function ( track ) {
  24685. return track.name === referenceTrack.name
  24686. && track.ValueTypeName === referenceTrackType;
  24687. } );
  24688. if ( targetTrack === undefined ) continue;
  24689. let referenceOffset = 0;
  24690. const referenceValueSize = referenceTrack.getValueSize();
  24691. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24692. referenceOffset = referenceValueSize / 3;
  24693. }
  24694. let targetOffset = 0;
  24695. const targetValueSize = targetTrack.getValueSize();
  24696. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24697. targetOffset = targetValueSize / 3;
  24698. }
  24699. const lastIndex = referenceTrack.times.length - 1;
  24700. let referenceValue;
  24701. // Find the value to subtract out of the track
  24702. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  24703. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  24704. const startIndex = referenceOffset;
  24705. const endIndex = referenceValueSize - referenceOffset;
  24706. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24707. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  24708. // Reference frame is after the last keyframe, so just use the last keyframe
  24709. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  24710. const endIndex = startIndex + referenceValueSize - referenceOffset;
  24711. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24712. } else {
  24713. // Interpolate to the reference value
  24714. const interpolant = referenceTrack.createInterpolant();
  24715. const startIndex = referenceOffset;
  24716. const endIndex = referenceValueSize - referenceOffset;
  24717. interpolant.evaluate( referenceTime );
  24718. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  24719. }
  24720. // Conjugate the quaternion
  24721. if ( referenceTrackType === 'quaternion' ) {
  24722. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  24723. referenceQuat.toArray( referenceValue );
  24724. }
  24725. // Subtract the reference value from all of the track values
  24726. const numTimes = targetTrack.times.length;
  24727. for ( let j = 0; j < numTimes; ++ j ) {
  24728. const valueStart = j * targetValueSize + targetOffset;
  24729. if ( referenceTrackType === 'quaternion' ) {
  24730. // Multiply the conjugate for quaternion track types
  24731. Quaternion.multiplyQuaternionsFlat(
  24732. targetTrack.values,
  24733. valueStart,
  24734. referenceValue,
  24735. 0,
  24736. targetTrack.values,
  24737. valueStart
  24738. );
  24739. } else {
  24740. const valueEnd = targetValueSize - targetOffset * 2;
  24741. // Subtract each value for all other numeric track types
  24742. for ( let k = 0; k < valueEnd; ++ k ) {
  24743. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  24744. }
  24745. }
  24746. }
  24747. }
  24748. targetClip.blendMode = AdditiveAnimationBlendMode;
  24749. return targetClip;
  24750. }
  24751. const AnimationUtils = {
  24752. convertArray: convertArray,
  24753. isTypedArray: isTypedArray,
  24754. getKeyframeOrder: getKeyframeOrder,
  24755. sortedArray: sortedArray,
  24756. flattenJSON: flattenJSON,
  24757. subclip: subclip,
  24758. makeClipAdditive: makeClipAdditive
  24759. };
  24760. /**
  24761. * Abstract base class of interpolants over parametric samples.
  24762. *
  24763. * The parameter domain is one dimensional, typically the time or a path
  24764. * along a curve defined by the data.
  24765. *
  24766. * The sample values can have any dimensionality and derived classes may
  24767. * apply special interpretations to the data.
  24768. *
  24769. * This class provides the interval seek in a Template Method, deferring
  24770. * the actual interpolation to derived classes.
  24771. *
  24772. * Time complexity is O(1) for linear access crossing at most two points
  24773. * and O(log N) for random access, where N is the number of positions.
  24774. *
  24775. * References:
  24776. *
  24777. * http://www.oodesign.com/template-method-pattern.html
  24778. *
  24779. */
  24780. class Interpolant {
  24781. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24782. this.parameterPositions = parameterPositions;
  24783. this._cachedIndex = 0;
  24784. this.resultBuffer = resultBuffer !== undefined ?
  24785. resultBuffer : new sampleValues.constructor( sampleSize );
  24786. this.sampleValues = sampleValues;
  24787. this.valueSize = sampleSize;
  24788. this.settings = null;
  24789. this.DefaultSettings_ = {};
  24790. }
  24791. evaluate( t ) {
  24792. const pp = this.parameterPositions;
  24793. let i1 = this._cachedIndex,
  24794. t1 = pp[ i1 ],
  24795. t0 = pp[ i1 - 1 ];
  24796. validate_interval: {
  24797. seek: {
  24798. let right;
  24799. linear_scan: {
  24800. //- See http://jsperf.com/comparison-to-undefined/3
  24801. //- slower code:
  24802. //-
  24803. //- if ( t >= t1 || t1 === undefined ) {
  24804. forward_scan: if ( ! ( t < t1 ) ) {
  24805. for ( let giveUpAt = i1 + 2; ; ) {
  24806. if ( t1 === undefined ) {
  24807. if ( t < t0 ) break forward_scan;
  24808. // after end
  24809. i1 = pp.length;
  24810. this._cachedIndex = i1;
  24811. return this.copySampleValue_( i1 - 1 );
  24812. }
  24813. if ( i1 === giveUpAt ) break; // this loop
  24814. t0 = t1;
  24815. t1 = pp[ ++ i1 ];
  24816. if ( t < t1 ) {
  24817. // we have arrived at the sought interval
  24818. break seek;
  24819. }
  24820. }
  24821. // prepare binary search on the right side of the index
  24822. right = pp.length;
  24823. break linear_scan;
  24824. }
  24825. //- slower code:
  24826. //- if ( t < t0 || t0 === undefined ) {
  24827. if ( ! ( t >= t0 ) ) {
  24828. // looping?
  24829. const t1global = pp[ 1 ];
  24830. if ( t < t1global ) {
  24831. i1 = 2; // + 1, using the scan for the details
  24832. t0 = t1global;
  24833. }
  24834. // linear reverse scan
  24835. for ( let giveUpAt = i1 - 2; ; ) {
  24836. if ( t0 === undefined ) {
  24837. // before start
  24838. this._cachedIndex = 0;
  24839. return this.copySampleValue_( 0 );
  24840. }
  24841. if ( i1 === giveUpAt ) break; // this loop
  24842. t1 = t0;
  24843. t0 = pp[ -- i1 - 1 ];
  24844. if ( t >= t0 ) {
  24845. // we have arrived at the sought interval
  24846. break seek;
  24847. }
  24848. }
  24849. // prepare binary search on the left side of the index
  24850. right = i1;
  24851. i1 = 0;
  24852. break linear_scan;
  24853. }
  24854. // the interval is valid
  24855. break validate_interval;
  24856. } // linear scan
  24857. // binary search
  24858. while ( i1 < right ) {
  24859. const mid = ( i1 + right ) >>> 1;
  24860. if ( t < pp[ mid ] ) {
  24861. right = mid;
  24862. } else {
  24863. i1 = mid + 1;
  24864. }
  24865. }
  24866. t1 = pp[ i1 ];
  24867. t0 = pp[ i1 - 1 ];
  24868. // check boundary cases, again
  24869. if ( t0 === undefined ) {
  24870. this._cachedIndex = 0;
  24871. return this.copySampleValue_( 0 );
  24872. }
  24873. if ( t1 === undefined ) {
  24874. i1 = pp.length;
  24875. this._cachedIndex = i1;
  24876. return this.copySampleValue_( i1 - 1 );
  24877. }
  24878. } // seek
  24879. this._cachedIndex = i1;
  24880. this.intervalChanged_( i1, t0, t1 );
  24881. } // validate_interval
  24882. return this.interpolate_( i1, t0, t, t1 );
  24883. }
  24884. getSettings_() {
  24885. return this.settings || this.DefaultSettings_;
  24886. }
  24887. copySampleValue_( index ) {
  24888. // copies a sample value to the result buffer
  24889. const result = this.resultBuffer,
  24890. values = this.sampleValues,
  24891. stride = this.valueSize,
  24892. offset = index * stride;
  24893. for ( let i = 0; i !== stride; ++ i ) {
  24894. result[ i ] = values[ offset + i ];
  24895. }
  24896. return result;
  24897. }
  24898. // Template methods for derived classes:
  24899. interpolate_( /* i1, t0, t, t1 */ ) {
  24900. throw new Error( 'call to abstract method' );
  24901. // implementations shall return this.resultBuffer
  24902. }
  24903. intervalChanged_( /* i1, t0, t1 */ ) {
  24904. // empty
  24905. }
  24906. }
  24907. /**
  24908. * Fast and simple cubic spline interpolant.
  24909. *
  24910. * It was derived from a Hermitian construction setting the first derivative
  24911. * at each sample position to the linear slope between neighboring positions
  24912. * over their parameter interval.
  24913. */
  24914. class CubicInterpolant extends Interpolant {
  24915. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24916. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24917. this._weightPrev = - 0;
  24918. this._offsetPrev = - 0;
  24919. this._weightNext = - 0;
  24920. this._offsetNext = - 0;
  24921. this.DefaultSettings_ = {
  24922. endingStart: ZeroCurvatureEnding,
  24923. endingEnd: ZeroCurvatureEnding
  24924. };
  24925. }
  24926. intervalChanged_( i1, t0, t1 ) {
  24927. const pp = this.parameterPositions;
  24928. let iPrev = i1 - 2,
  24929. iNext = i1 + 1,
  24930. tPrev = pp[ iPrev ],
  24931. tNext = pp[ iNext ];
  24932. if ( tPrev === undefined ) {
  24933. switch ( this.getSettings_().endingStart ) {
  24934. case ZeroSlopeEnding:
  24935. // f'(t0) = 0
  24936. iPrev = i1;
  24937. tPrev = 2 * t0 - t1;
  24938. break;
  24939. case WrapAroundEnding:
  24940. // use the other end of the curve
  24941. iPrev = pp.length - 2;
  24942. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24943. break;
  24944. default: // ZeroCurvatureEnding
  24945. // f''(t0) = 0 a.k.a. Natural Spline
  24946. iPrev = i1;
  24947. tPrev = t1;
  24948. }
  24949. }
  24950. if ( tNext === undefined ) {
  24951. switch ( this.getSettings_().endingEnd ) {
  24952. case ZeroSlopeEnding:
  24953. // f'(tN) = 0
  24954. iNext = i1;
  24955. tNext = 2 * t1 - t0;
  24956. break;
  24957. case WrapAroundEnding:
  24958. // use the other end of the curve
  24959. iNext = 1;
  24960. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24961. break;
  24962. default: // ZeroCurvatureEnding
  24963. // f''(tN) = 0, a.k.a. Natural Spline
  24964. iNext = i1 - 1;
  24965. tNext = t0;
  24966. }
  24967. }
  24968. const halfDt = ( t1 - t0 ) * 0.5,
  24969. stride = this.valueSize;
  24970. this._weightPrev = halfDt / ( t0 - tPrev );
  24971. this._weightNext = halfDt / ( tNext - t1 );
  24972. this._offsetPrev = iPrev * stride;
  24973. this._offsetNext = iNext * stride;
  24974. }
  24975. interpolate_( i1, t0, t, t1 ) {
  24976. const result = this.resultBuffer,
  24977. values = this.sampleValues,
  24978. stride = this.valueSize,
  24979. o1 = i1 * stride, o0 = o1 - stride,
  24980. oP = this._offsetPrev, oN = this._offsetNext,
  24981. wP = this._weightPrev, wN = this._weightNext,
  24982. p = ( t - t0 ) / ( t1 - t0 ),
  24983. pp = p * p,
  24984. ppp = pp * p;
  24985. // evaluate polynomials
  24986. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  24987. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24988. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24989. const sN = wN * ppp - wN * pp;
  24990. // combine data linearly
  24991. for ( let i = 0; i !== stride; ++ i ) {
  24992. result[ i ] =
  24993. sP * values[ oP + i ] +
  24994. s0 * values[ o0 + i ] +
  24995. s1 * values[ o1 + i ] +
  24996. sN * values[ oN + i ];
  24997. }
  24998. return result;
  24999. }
  25000. }
  25001. class LinearInterpolant extends Interpolant {
  25002. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25003. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25004. }
  25005. interpolate_( i1, t0, t, t1 ) {
  25006. const result = this.resultBuffer,
  25007. values = this.sampleValues,
  25008. stride = this.valueSize,
  25009. offset1 = i1 * stride,
  25010. offset0 = offset1 - stride,
  25011. weight1 = ( t - t0 ) / ( t1 - t0 ),
  25012. weight0 = 1 - weight1;
  25013. for ( let i = 0; i !== stride; ++ i ) {
  25014. result[ i ] =
  25015. values[ offset0 + i ] * weight0 +
  25016. values[ offset1 + i ] * weight1;
  25017. }
  25018. return result;
  25019. }
  25020. }
  25021. /**
  25022. *
  25023. * Interpolant that evaluates to the sample value at the position preceding
  25024. * the parameter.
  25025. */
  25026. class DiscreteInterpolant extends Interpolant {
  25027. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25028. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25029. }
  25030. interpolate_( i1 /*, t0, t, t1 */ ) {
  25031. return this.copySampleValue_( i1 - 1 );
  25032. }
  25033. }
  25034. class KeyframeTrack {
  25035. constructor( name, times, values, interpolation ) {
  25036. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25037. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25038. this.name = name;
  25039. this.times = convertArray( times, this.TimeBufferType );
  25040. this.values = convertArray( values, this.ValueBufferType );
  25041. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25042. }
  25043. // Serialization (in static context, because of constructor invocation
  25044. // and automatic invocation of .toJSON):
  25045. static toJSON( track ) {
  25046. const trackType = track.constructor;
  25047. let json;
  25048. // derived classes can define a static toJSON method
  25049. if ( trackType.toJSON !== this.toJSON ) {
  25050. json = trackType.toJSON( track );
  25051. } else {
  25052. // by default, we assume the data can be serialized as-is
  25053. json = {
  25054. 'name': track.name,
  25055. 'times': convertArray( track.times, Array ),
  25056. 'values': convertArray( track.values, Array )
  25057. };
  25058. const interpolation = track.getInterpolation();
  25059. if ( interpolation !== track.DefaultInterpolation ) {
  25060. json.interpolation = interpolation;
  25061. }
  25062. }
  25063. json.type = track.ValueTypeName; // mandatory
  25064. return json;
  25065. }
  25066. InterpolantFactoryMethodDiscrete( result ) {
  25067. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25068. }
  25069. InterpolantFactoryMethodLinear( result ) {
  25070. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25071. }
  25072. InterpolantFactoryMethodSmooth( result ) {
  25073. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25074. }
  25075. setInterpolation( interpolation ) {
  25076. let factoryMethod;
  25077. switch ( interpolation ) {
  25078. case InterpolateDiscrete:
  25079. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25080. break;
  25081. case InterpolateLinear:
  25082. factoryMethod = this.InterpolantFactoryMethodLinear;
  25083. break;
  25084. case InterpolateSmooth:
  25085. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25086. break;
  25087. }
  25088. if ( factoryMethod === undefined ) {
  25089. const message = 'unsupported interpolation for ' +
  25090. this.ValueTypeName + ' keyframe track named ' + this.name;
  25091. if ( this.createInterpolant === undefined ) {
  25092. // fall back to default, unless the default itself is messed up
  25093. if ( interpolation !== this.DefaultInterpolation ) {
  25094. this.setInterpolation( this.DefaultInterpolation );
  25095. } else {
  25096. throw new Error( message ); // fatal, in this case
  25097. }
  25098. }
  25099. console.warn( 'THREE.KeyframeTrack:', message );
  25100. return this;
  25101. }
  25102. this.createInterpolant = factoryMethod;
  25103. return this;
  25104. }
  25105. getInterpolation() {
  25106. switch ( this.createInterpolant ) {
  25107. case this.InterpolantFactoryMethodDiscrete:
  25108. return InterpolateDiscrete;
  25109. case this.InterpolantFactoryMethodLinear:
  25110. return InterpolateLinear;
  25111. case this.InterpolantFactoryMethodSmooth:
  25112. return InterpolateSmooth;
  25113. }
  25114. }
  25115. getValueSize() {
  25116. return this.values.length / this.times.length;
  25117. }
  25118. // move all keyframes either forwards or backwards in time
  25119. shift( timeOffset ) {
  25120. if ( timeOffset !== 0.0 ) {
  25121. const times = this.times;
  25122. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25123. times[ i ] += timeOffset;
  25124. }
  25125. }
  25126. return this;
  25127. }
  25128. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25129. scale( timeScale ) {
  25130. if ( timeScale !== 1.0 ) {
  25131. const times = this.times;
  25132. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25133. times[ i ] *= timeScale;
  25134. }
  25135. }
  25136. return this;
  25137. }
  25138. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25139. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25140. trim( startTime, endTime ) {
  25141. const times = this.times,
  25142. nKeys = times.length;
  25143. let from = 0,
  25144. to = nKeys - 1;
  25145. while ( from !== nKeys && times[ from ] < startTime ) {
  25146. ++ from;
  25147. }
  25148. while ( to !== - 1 && times[ to ] > endTime ) {
  25149. -- to;
  25150. }
  25151. ++ to; // inclusive -> exclusive bound
  25152. if ( from !== 0 || to !== nKeys ) {
  25153. // empty tracks are forbidden, so keep at least one keyframe
  25154. if ( from >= to ) {
  25155. to = Math.max( to, 1 );
  25156. from = to - 1;
  25157. }
  25158. const stride = this.getValueSize();
  25159. this.times = times.slice( from, to );
  25160. this.values = this.values.slice( from * stride, to * stride );
  25161. }
  25162. return this;
  25163. }
  25164. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25165. validate() {
  25166. let valid = true;
  25167. const valueSize = this.getValueSize();
  25168. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25169. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25170. valid = false;
  25171. }
  25172. const times = this.times,
  25173. values = this.values,
  25174. nKeys = times.length;
  25175. if ( nKeys === 0 ) {
  25176. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25177. valid = false;
  25178. }
  25179. let prevTime = null;
  25180. for ( let i = 0; i !== nKeys; i ++ ) {
  25181. const currTime = times[ i ];
  25182. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25183. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25184. valid = false;
  25185. break;
  25186. }
  25187. if ( prevTime !== null && prevTime > currTime ) {
  25188. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25189. valid = false;
  25190. break;
  25191. }
  25192. prevTime = currTime;
  25193. }
  25194. if ( values !== undefined ) {
  25195. if ( isTypedArray( values ) ) {
  25196. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  25197. const value = values[ i ];
  25198. if ( isNaN( value ) ) {
  25199. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25200. valid = false;
  25201. break;
  25202. }
  25203. }
  25204. }
  25205. }
  25206. return valid;
  25207. }
  25208. // removes equivalent sequential keys as common in morph target sequences
  25209. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25210. optimize() {
  25211. // times or values may be shared with other tracks, so overwriting is unsafe
  25212. const times = this.times.slice(),
  25213. values = this.values.slice(),
  25214. stride = this.getValueSize(),
  25215. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25216. lastIndex = times.length - 1;
  25217. let writeIndex = 1;
  25218. for ( let i = 1; i < lastIndex; ++ i ) {
  25219. let keep = false;
  25220. const time = times[ i ];
  25221. const timeNext = times[ i + 1 ];
  25222. // remove adjacent keyframes scheduled at the same time
  25223. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  25224. if ( ! smoothInterpolation ) {
  25225. // remove unnecessary keyframes same as their neighbors
  25226. const offset = i * stride,
  25227. offsetP = offset - stride,
  25228. offsetN = offset + stride;
  25229. for ( let j = 0; j !== stride; ++ j ) {
  25230. const value = values[ offset + j ];
  25231. if ( value !== values[ offsetP + j ] ||
  25232. value !== values[ offsetN + j ] ) {
  25233. keep = true;
  25234. break;
  25235. }
  25236. }
  25237. } else {
  25238. keep = true;
  25239. }
  25240. }
  25241. // in-place compaction
  25242. if ( keep ) {
  25243. if ( i !== writeIndex ) {
  25244. times[ writeIndex ] = times[ i ];
  25245. const readOffset = i * stride,
  25246. writeOffset = writeIndex * stride;
  25247. for ( let j = 0; j !== stride; ++ j ) {
  25248. values[ writeOffset + j ] = values[ readOffset + j ];
  25249. }
  25250. }
  25251. ++ writeIndex;
  25252. }
  25253. }
  25254. // flush last keyframe (compaction looks ahead)
  25255. if ( lastIndex > 0 ) {
  25256. times[ writeIndex ] = times[ lastIndex ];
  25257. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25258. values[ writeOffset + j ] = values[ readOffset + j ];
  25259. }
  25260. ++ writeIndex;
  25261. }
  25262. if ( writeIndex !== times.length ) {
  25263. this.times = times.slice( 0, writeIndex );
  25264. this.values = values.slice( 0, writeIndex * stride );
  25265. } else {
  25266. this.times = times;
  25267. this.values = values;
  25268. }
  25269. return this;
  25270. }
  25271. clone() {
  25272. const times = this.times.slice();
  25273. const values = this.values.slice();
  25274. const TypedKeyframeTrack = this.constructor;
  25275. const track = new TypedKeyframeTrack( this.name, times, values );
  25276. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  25277. track.createInterpolant = this.createInterpolant;
  25278. return track;
  25279. }
  25280. }
  25281. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  25282. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  25283. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25284. /**
  25285. * A Track of Boolean keyframe values.
  25286. */
  25287. class BooleanKeyframeTrack extends KeyframeTrack {}
  25288. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  25289. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  25290. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25291. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25292. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25293. /**
  25294. * A Track of keyframe values that represent color.
  25295. */
  25296. class ColorKeyframeTrack extends KeyframeTrack {}
  25297. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  25298. /**
  25299. * A Track of numeric keyframe values.
  25300. */
  25301. class NumberKeyframeTrack extends KeyframeTrack {}
  25302. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  25303. /**
  25304. * Spherical linear unit quaternion interpolant.
  25305. */
  25306. class QuaternionLinearInterpolant extends Interpolant {
  25307. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25308. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25309. }
  25310. interpolate_( i1, t0, t, t1 ) {
  25311. const result = this.resultBuffer,
  25312. values = this.sampleValues,
  25313. stride = this.valueSize,
  25314. alpha = ( t - t0 ) / ( t1 - t0 );
  25315. let offset = i1 * stride;
  25316. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  25317. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25318. }
  25319. return result;
  25320. }
  25321. }
  25322. /**
  25323. * A Track of quaternion keyframe values.
  25324. */
  25325. class QuaternionKeyframeTrack extends KeyframeTrack {
  25326. InterpolantFactoryMethodLinear( result ) {
  25327. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25328. }
  25329. }
  25330. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  25331. // ValueBufferType is inherited
  25332. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25333. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25334. /**
  25335. * A Track that interpolates Strings
  25336. */
  25337. class StringKeyframeTrack extends KeyframeTrack {}
  25338. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  25339. StringKeyframeTrack.prototype.ValueBufferType = Array;
  25340. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25341. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25342. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25343. /**
  25344. * A Track of vectored keyframe values.
  25345. */
  25346. class VectorKeyframeTrack extends KeyframeTrack {}
  25347. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  25348. class AnimationClip {
  25349. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  25350. this.name = name;
  25351. this.tracks = tracks;
  25352. this.duration = duration;
  25353. this.blendMode = blendMode;
  25354. this.uuid = generateUUID();
  25355. // this means it should figure out its duration by scanning the tracks
  25356. if ( this.duration < 0 ) {
  25357. this.resetDuration();
  25358. }
  25359. }
  25360. static parse( json ) {
  25361. const tracks = [],
  25362. jsonTracks = json.tracks,
  25363. frameTime = 1.0 / ( json.fps || 1.0 );
  25364. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25365. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25366. }
  25367. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  25368. clip.uuid = json.uuid;
  25369. return clip;
  25370. }
  25371. static toJSON( clip ) {
  25372. const tracks = [],
  25373. clipTracks = clip.tracks;
  25374. const json = {
  25375. 'name': clip.name,
  25376. 'duration': clip.duration,
  25377. 'tracks': tracks,
  25378. 'uuid': clip.uuid,
  25379. 'blendMode': clip.blendMode
  25380. };
  25381. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25382. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25383. }
  25384. return json;
  25385. }
  25386. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  25387. const numMorphTargets = morphTargetSequence.length;
  25388. const tracks = [];
  25389. for ( let i = 0; i < numMorphTargets; i ++ ) {
  25390. let times = [];
  25391. let values = [];
  25392. times.push(
  25393. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25394. i,
  25395. ( i + 1 ) % numMorphTargets );
  25396. values.push( 0, 1, 0 );
  25397. const order = getKeyframeOrder( times );
  25398. times = sortedArray( times, 1, order );
  25399. values = sortedArray( values, 1, order );
  25400. // if there is a key at the first frame, duplicate it as the
  25401. // last frame as well for perfect loop.
  25402. if ( ! noLoop && times[ 0 ] === 0 ) {
  25403. times.push( numMorphTargets );
  25404. values.push( values[ 0 ] );
  25405. }
  25406. tracks.push(
  25407. new NumberKeyframeTrack(
  25408. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25409. times, values
  25410. ).scale( 1.0 / fps ) );
  25411. }
  25412. return new this( name, - 1, tracks );
  25413. }
  25414. static findByName( objectOrClipArray, name ) {
  25415. let clipArray = objectOrClipArray;
  25416. if ( ! Array.isArray( objectOrClipArray ) ) {
  25417. const o = objectOrClipArray;
  25418. clipArray = o.geometry && o.geometry.animations || o.animations;
  25419. }
  25420. for ( let i = 0; i < clipArray.length; i ++ ) {
  25421. if ( clipArray[ i ].name === name ) {
  25422. return clipArray[ i ];
  25423. }
  25424. }
  25425. return null;
  25426. }
  25427. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  25428. const animationToMorphTargets = {};
  25429. // tested with https://regex101.com/ on trick sequences
  25430. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25431. const pattern = /^([\w-]*?)([\d]+)$/;
  25432. // sort morph target names into animation groups based
  25433. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25434. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  25435. const morphTarget = morphTargets[ i ];
  25436. const parts = morphTarget.name.match( pattern );
  25437. if ( parts && parts.length > 1 ) {
  25438. const name = parts[ 1 ];
  25439. let animationMorphTargets = animationToMorphTargets[ name ];
  25440. if ( ! animationMorphTargets ) {
  25441. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25442. }
  25443. animationMorphTargets.push( morphTarget );
  25444. }
  25445. }
  25446. const clips = [];
  25447. for ( const name in animationToMorphTargets ) {
  25448. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25449. }
  25450. return clips;
  25451. }
  25452. // parse the animation.hierarchy format
  25453. static parseAnimation( animation, bones ) {
  25454. if ( ! animation ) {
  25455. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25456. return null;
  25457. }
  25458. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25459. // only return track if there are actually keys.
  25460. if ( animationKeys.length !== 0 ) {
  25461. const times = [];
  25462. const values = [];
  25463. flattenJSON( animationKeys, times, values, propertyName );
  25464. // empty keys are filtered out, so check again
  25465. if ( times.length !== 0 ) {
  25466. destTracks.push( new trackType( trackName, times, values ) );
  25467. }
  25468. }
  25469. };
  25470. const tracks = [];
  25471. const clipName = animation.name || 'default';
  25472. const fps = animation.fps || 30;
  25473. const blendMode = animation.blendMode;
  25474. // automatic length determination in AnimationClip.
  25475. let duration = animation.length || - 1;
  25476. const hierarchyTracks = animation.hierarchy || [];
  25477. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  25478. const animationKeys = hierarchyTracks[ h ].keys;
  25479. // skip empty tracks
  25480. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25481. // process morph targets
  25482. if ( animationKeys[ 0 ].morphTargets ) {
  25483. // figure out all morph targets used in this track
  25484. const morphTargetNames = {};
  25485. let k;
  25486. for ( k = 0; k < animationKeys.length; k ++ ) {
  25487. if ( animationKeys[ k ].morphTargets ) {
  25488. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25489. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25490. }
  25491. }
  25492. }
  25493. // create a track for each morph target with all zero
  25494. // morphTargetInfluences except for the keys in which
  25495. // the morphTarget is named.
  25496. for ( const morphTargetName in morphTargetNames ) {
  25497. const times = [];
  25498. const values = [];
  25499. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25500. const animationKey = animationKeys[ k ];
  25501. times.push( animationKey.time );
  25502. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25503. }
  25504. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25505. }
  25506. duration = morphTargetNames.length * fps;
  25507. } else {
  25508. // ...assume skeletal animation
  25509. const boneName = '.bones[' + bones[ h ].name + ']';
  25510. addNonemptyTrack(
  25511. VectorKeyframeTrack, boneName + '.position',
  25512. animationKeys, 'pos', tracks );
  25513. addNonemptyTrack(
  25514. QuaternionKeyframeTrack, boneName + '.quaternion',
  25515. animationKeys, 'rot', tracks );
  25516. addNonemptyTrack(
  25517. VectorKeyframeTrack, boneName + '.scale',
  25518. animationKeys, 'scl', tracks );
  25519. }
  25520. }
  25521. if ( tracks.length === 0 ) {
  25522. return null;
  25523. }
  25524. const clip = new this( clipName, duration, tracks, blendMode );
  25525. return clip;
  25526. }
  25527. resetDuration() {
  25528. const tracks = this.tracks;
  25529. let duration = 0;
  25530. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  25531. const track = this.tracks[ i ];
  25532. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25533. }
  25534. this.duration = duration;
  25535. return this;
  25536. }
  25537. trim() {
  25538. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25539. this.tracks[ i ].trim( 0, this.duration );
  25540. }
  25541. return this;
  25542. }
  25543. validate() {
  25544. let valid = true;
  25545. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25546. valid = valid && this.tracks[ i ].validate();
  25547. }
  25548. return valid;
  25549. }
  25550. optimize() {
  25551. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25552. this.tracks[ i ].optimize();
  25553. }
  25554. return this;
  25555. }
  25556. clone() {
  25557. const tracks = [];
  25558. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25559. tracks.push( this.tracks[ i ].clone() );
  25560. }
  25561. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  25562. }
  25563. toJSON() {
  25564. return this.constructor.toJSON( this );
  25565. }
  25566. }
  25567. function getTrackTypeForValueTypeName( typeName ) {
  25568. switch ( typeName.toLowerCase() ) {
  25569. case 'scalar':
  25570. case 'double':
  25571. case 'float':
  25572. case 'number':
  25573. case 'integer':
  25574. return NumberKeyframeTrack;
  25575. case 'vector':
  25576. case 'vector2':
  25577. case 'vector3':
  25578. case 'vector4':
  25579. return VectorKeyframeTrack;
  25580. case 'color':
  25581. return ColorKeyframeTrack;
  25582. case 'quaternion':
  25583. return QuaternionKeyframeTrack;
  25584. case 'bool':
  25585. case 'boolean':
  25586. return BooleanKeyframeTrack;
  25587. case 'string':
  25588. return StringKeyframeTrack;
  25589. }
  25590. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25591. }
  25592. function parseKeyframeTrack( json ) {
  25593. if ( json.type === undefined ) {
  25594. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25595. }
  25596. const trackType = getTrackTypeForValueTypeName( json.type );
  25597. if ( json.times === undefined ) {
  25598. const times = [], values = [];
  25599. flattenJSON( json.keys, times, values, 'value' );
  25600. json.times = times;
  25601. json.values = values;
  25602. }
  25603. // derived classes can define a static parse method
  25604. if ( trackType.parse !== undefined ) {
  25605. return trackType.parse( json );
  25606. } else {
  25607. // by default, we assume a constructor compatible with the base
  25608. return new trackType( json.name, json.times, json.values, json.interpolation );
  25609. }
  25610. }
  25611. const Cache = {
  25612. enabled: false,
  25613. files: {},
  25614. add: function ( key, file ) {
  25615. if ( this.enabled === false ) return;
  25616. // console.log( 'THREE.Cache', 'Adding key:', key );
  25617. this.files[ key ] = file;
  25618. },
  25619. get: function ( key ) {
  25620. if ( this.enabled === false ) return;
  25621. // console.log( 'THREE.Cache', 'Checking key:', key );
  25622. return this.files[ key ];
  25623. },
  25624. remove: function ( key ) {
  25625. delete this.files[ key ];
  25626. },
  25627. clear: function () {
  25628. this.files = {};
  25629. }
  25630. };
  25631. class LoadingManager {
  25632. constructor( onLoad, onProgress, onError ) {
  25633. const scope = this;
  25634. let isLoading = false;
  25635. let itemsLoaded = 0;
  25636. let itemsTotal = 0;
  25637. let urlModifier = undefined;
  25638. const handlers = [];
  25639. // Refer to #5689 for the reason why we don't set .onStart
  25640. // in the constructor
  25641. this.onStart = undefined;
  25642. this.onLoad = onLoad;
  25643. this.onProgress = onProgress;
  25644. this.onError = onError;
  25645. this.itemStart = function ( url ) {
  25646. itemsTotal ++;
  25647. if ( isLoading === false ) {
  25648. if ( scope.onStart !== undefined ) {
  25649. scope.onStart( url, itemsLoaded, itemsTotal );
  25650. }
  25651. }
  25652. isLoading = true;
  25653. };
  25654. this.itemEnd = function ( url ) {
  25655. itemsLoaded ++;
  25656. if ( scope.onProgress !== undefined ) {
  25657. scope.onProgress( url, itemsLoaded, itemsTotal );
  25658. }
  25659. if ( itemsLoaded === itemsTotal ) {
  25660. isLoading = false;
  25661. if ( scope.onLoad !== undefined ) {
  25662. scope.onLoad();
  25663. }
  25664. }
  25665. };
  25666. this.itemError = function ( url ) {
  25667. if ( scope.onError !== undefined ) {
  25668. scope.onError( url );
  25669. }
  25670. };
  25671. this.resolveURL = function ( url ) {
  25672. if ( urlModifier ) {
  25673. return urlModifier( url );
  25674. }
  25675. return url;
  25676. };
  25677. this.setURLModifier = function ( transform ) {
  25678. urlModifier = transform;
  25679. return this;
  25680. };
  25681. this.addHandler = function ( regex, loader ) {
  25682. handlers.push( regex, loader );
  25683. return this;
  25684. };
  25685. this.removeHandler = function ( regex ) {
  25686. const index = handlers.indexOf( regex );
  25687. if ( index !== - 1 ) {
  25688. handlers.splice( index, 2 );
  25689. }
  25690. return this;
  25691. };
  25692. this.getHandler = function ( file ) {
  25693. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  25694. const regex = handlers[ i ];
  25695. const loader = handlers[ i + 1 ];
  25696. if ( regex.global ) regex.lastIndex = 0; // see #17920
  25697. if ( regex.test( file ) ) {
  25698. return loader;
  25699. }
  25700. }
  25701. return null;
  25702. };
  25703. }
  25704. }
  25705. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  25706. class Loader {
  25707. constructor( manager ) {
  25708. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25709. this.crossOrigin = 'anonymous';
  25710. this.withCredentials = false;
  25711. this.path = '';
  25712. this.resourcePath = '';
  25713. this.requestHeader = {};
  25714. }
  25715. load( /* url, onLoad, onProgress, onError */ ) {}
  25716. loadAsync( url, onProgress ) {
  25717. const scope = this;
  25718. return new Promise( function ( resolve, reject ) {
  25719. scope.load( url, resolve, onProgress, reject );
  25720. } );
  25721. }
  25722. parse( /* data */ ) {}
  25723. setCrossOrigin( crossOrigin ) {
  25724. this.crossOrigin = crossOrigin;
  25725. return this;
  25726. }
  25727. setWithCredentials( value ) {
  25728. this.withCredentials = value;
  25729. return this;
  25730. }
  25731. setPath( path ) {
  25732. this.path = path;
  25733. return this;
  25734. }
  25735. setResourcePath( resourcePath ) {
  25736. this.resourcePath = resourcePath;
  25737. return this;
  25738. }
  25739. setRequestHeader( requestHeader ) {
  25740. this.requestHeader = requestHeader;
  25741. return this;
  25742. }
  25743. }
  25744. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  25745. const loading = {};
  25746. class HttpError extends Error {
  25747. constructor( message, response ) {
  25748. super( message );
  25749. this.response = response;
  25750. }
  25751. }
  25752. class FileLoader extends Loader {
  25753. constructor( manager ) {
  25754. super( manager );
  25755. }
  25756. load( url, onLoad, onProgress, onError ) {
  25757. if ( url === undefined ) url = '';
  25758. if ( this.path !== undefined ) url = this.path + url;
  25759. url = this.manager.resolveURL( url );
  25760. const cached = Cache.get( url );
  25761. if ( cached !== undefined ) {
  25762. this.manager.itemStart( url );
  25763. setTimeout( () => {
  25764. if ( onLoad ) onLoad( cached );
  25765. this.manager.itemEnd( url );
  25766. }, 0 );
  25767. return cached;
  25768. }
  25769. // Check if request is duplicate
  25770. if ( loading[ url ] !== undefined ) {
  25771. loading[ url ].push( {
  25772. onLoad: onLoad,
  25773. onProgress: onProgress,
  25774. onError: onError
  25775. } );
  25776. return;
  25777. }
  25778. // Initialise array for duplicate requests
  25779. loading[ url ] = [];
  25780. loading[ url ].push( {
  25781. onLoad: onLoad,
  25782. onProgress: onProgress,
  25783. onError: onError,
  25784. } );
  25785. // create request
  25786. const req = new Request( url, {
  25787. headers: new Headers( this.requestHeader ),
  25788. credentials: this.withCredentials ? 'include' : 'same-origin',
  25789. // An abort controller could be added within a future PR
  25790. } );
  25791. // record states ( avoid data race )
  25792. const mimeType = this.mimeType;
  25793. const responseType = this.responseType;
  25794. // start the fetch
  25795. fetch( req )
  25796. .then( response => {
  25797. if ( response.status === 200 || response.status === 0 ) {
  25798. // Some browsers return HTTP Status 0 when using non-http protocol
  25799. // e.g. 'file://' or 'data://'. Handle as success.
  25800. if ( response.status === 0 ) {
  25801. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  25802. }
  25803. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  25804. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  25805. return response;
  25806. }
  25807. const callbacks = loading[ url ];
  25808. const reader = response.body.getReader();
  25809. // Nginx needs X-File-Size check
  25810. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  25811. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  25812. const total = contentLength ? parseInt( contentLength ) : 0;
  25813. const lengthComputable = total !== 0;
  25814. let loaded = 0;
  25815. // periodically read data into the new stream tracking while download progress
  25816. const stream = new ReadableStream( {
  25817. start( controller ) {
  25818. readData();
  25819. function readData() {
  25820. reader.read().then( ( { done, value } ) => {
  25821. if ( done ) {
  25822. controller.close();
  25823. } else {
  25824. loaded += value.byteLength;
  25825. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  25826. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25827. const callback = callbacks[ i ];
  25828. if ( callback.onProgress ) callback.onProgress( event );
  25829. }
  25830. controller.enqueue( value );
  25831. readData();
  25832. }
  25833. } );
  25834. }
  25835. }
  25836. } );
  25837. return new Response( stream );
  25838. } else {
  25839. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  25840. }
  25841. } )
  25842. .then( response => {
  25843. switch ( responseType ) {
  25844. case 'arraybuffer':
  25845. return response.arrayBuffer();
  25846. case 'blob':
  25847. return response.blob();
  25848. case 'document':
  25849. return response.text()
  25850. .then( text => {
  25851. const parser = new DOMParser();
  25852. return parser.parseFromString( text, mimeType );
  25853. } );
  25854. case 'json':
  25855. return response.json();
  25856. default:
  25857. if ( mimeType === undefined ) {
  25858. return response.text();
  25859. } else {
  25860. // sniff encoding
  25861. const re = /charset="?([^;"\s]*)"?/i;
  25862. const exec = re.exec( mimeType );
  25863. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  25864. const decoder = new TextDecoder( label );
  25865. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  25866. }
  25867. }
  25868. } )
  25869. .then( data => {
  25870. // Add to cache only on HTTP success, so that we do not cache
  25871. // error response bodies as proper responses to requests.
  25872. Cache.add( url, data );
  25873. const callbacks = loading[ url ];
  25874. delete loading[ url ];
  25875. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25876. const callback = callbacks[ i ];
  25877. if ( callback.onLoad ) callback.onLoad( data );
  25878. }
  25879. } )
  25880. .catch( err => {
  25881. // Abort errors and other errors are handled the same
  25882. const callbacks = loading[ url ];
  25883. if ( callbacks === undefined ) {
  25884. // When onLoad was called and url was deleted in `loading`
  25885. this.manager.itemError( url );
  25886. throw err;
  25887. }
  25888. delete loading[ url ];
  25889. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25890. const callback = callbacks[ i ];
  25891. if ( callback.onError ) callback.onError( err );
  25892. }
  25893. this.manager.itemError( url );
  25894. } )
  25895. .finally( () => {
  25896. this.manager.itemEnd( url );
  25897. } );
  25898. this.manager.itemStart( url );
  25899. }
  25900. setResponseType( value ) {
  25901. this.responseType = value;
  25902. return this;
  25903. }
  25904. setMimeType( value ) {
  25905. this.mimeType = value;
  25906. return this;
  25907. }
  25908. }
  25909. class AnimationLoader extends Loader {
  25910. constructor( manager ) {
  25911. super( manager );
  25912. }
  25913. load( url, onLoad, onProgress, onError ) {
  25914. const scope = this;
  25915. const loader = new FileLoader( this.manager );
  25916. loader.setPath( this.path );
  25917. loader.setRequestHeader( this.requestHeader );
  25918. loader.setWithCredentials( this.withCredentials );
  25919. loader.load( url, function ( text ) {
  25920. try {
  25921. onLoad( scope.parse( JSON.parse( text ) ) );
  25922. } catch ( e ) {
  25923. if ( onError ) {
  25924. onError( e );
  25925. } else {
  25926. console.error( e );
  25927. }
  25928. scope.manager.itemError( url );
  25929. }
  25930. }, onProgress, onError );
  25931. }
  25932. parse( json ) {
  25933. const animations = [];
  25934. for ( let i = 0; i < json.length; i ++ ) {
  25935. const clip = AnimationClip.parse( json[ i ] );
  25936. animations.push( clip );
  25937. }
  25938. return animations;
  25939. }
  25940. }
  25941. /**
  25942. * Abstract Base class to block based textures loader (dds, pvr, ...)
  25943. *
  25944. * Sub classes have to implement the parse() method which will be used in load().
  25945. */
  25946. class CompressedTextureLoader extends Loader {
  25947. constructor( manager ) {
  25948. super( manager );
  25949. }
  25950. load( url, onLoad, onProgress, onError ) {
  25951. const scope = this;
  25952. const images = [];
  25953. const texture = new CompressedTexture();
  25954. const loader = new FileLoader( this.manager );
  25955. loader.setPath( this.path );
  25956. loader.setResponseType( 'arraybuffer' );
  25957. loader.setRequestHeader( this.requestHeader );
  25958. loader.setWithCredentials( scope.withCredentials );
  25959. let loaded = 0;
  25960. function loadTexture( i ) {
  25961. loader.load( url[ i ], function ( buffer ) {
  25962. const texDatas = scope.parse( buffer, true );
  25963. images[ i ] = {
  25964. width: texDatas.width,
  25965. height: texDatas.height,
  25966. format: texDatas.format,
  25967. mipmaps: texDatas.mipmaps
  25968. };
  25969. loaded += 1;
  25970. if ( loaded === 6 ) {
  25971. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  25972. texture.image = images;
  25973. texture.format = texDatas.format;
  25974. texture.needsUpdate = true;
  25975. if ( onLoad ) onLoad( texture );
  25976. }
  25977. }, onProgress, onError );
  25978. }
  25979. if ( Array.isArray( url ) ) {
  25980. for ( let i = 0, il = url.length; i < il; ++ i ) {
  25981. loadTexture( i );
  25982. }
  25983. } else {
  25984. // compressed cubemap texture stored in a single DDS file
  25985. loader.load( url, function ( buffer ) {
  25986. const texDatas = scope.parse( buffer, true );
  25987. if ( texDatas.isCubemap ) {
  25988. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  25989. for ( let f = 0; f < faces; f ++ ) {
  25990. images[ f ] = { mipmaps: [] };
  25991. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  25992. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  25993. images[ f ].format = texDatas.format;
  25994. images[ f ].width = texDatas.width;
  25995. images[ f ].height = texDatas.height;
  25996. }
  25997. }
  25998. texture.image = images;
  25999. } else {
  26000. texture.image.width = texDatas.width;
  26001. texture.image.height = texDatas.height;
  26002. texture.mipmaps = texDatas.mipmaps;
  26003. }
  26004. if ( texDatas.mipmapCount === 1 ) {
  26005. texture.minFilter = LinearFilter;
  26006. }
  26007. texture.format = texDatas.format;
  26008. texture.needsUpdate = true;
  26009. if ( onLoad ) onLoad( texture );
  26010. }, onProgress, onError );
  26011. }
  26012. return texture;
  26013. }
  26014. }
  26015. class ImageLoader extends Loader {
  26016. constructor( manager ) {
  26017. super( manager );
  26018. }
  26019. load( url, onLoad, onProgress, onError ) {
  26020. if ( this.path !== undefined ) url = this.path + url;
  26021. url = this.manager.resolveURL( url );
  26022. const scope = this;
  26023. const cached = Cache.get( url );
  26024. if ( cached !== undefined ) {
  26025. scope.manager.itemStart( url );
  26026. setTimeout( function () {
  26027. if ( onLoad ) onLoad( cached );
  26028. scope.manager.itemEnd( url );
  26029. }, 0 );
  26030. return cached;
  26031. }
  26032. const image = createElementNS( 'img' );
  26033. function onImageLoad() {
  26034. removeEventListeners();
  26035. Cache.add( url, this );
  26036. if ( onLoad ) onLoad( this );
  26037. scope.manager.itemEnd( url );
  26038. }
  26039. function onImageError( event ) {
  26040. removeEventListeners();
  26041. if ( onError ) onError( event );
  26042. scope.manager.itemError( url );
  26043. scope.manager.itemEnd( url );
  26044. }
  26045. function removeEventListeners() {
  26046. image.removeEventListener( 'load', onImageLoad, false );
  26047. image.removeEventListener( 'error', onImageError, false );
  26048. }
  26049. image.addEventListener( 'load', onImageLoad, false );
  26050. image.addEventListener( 'error', onImageError, false );
  26051. if ( url.slice( 0, 5 ) !== 'data:' ) {
  26052. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  26053. }
  26054. scope.manager.itemStart( url );
  26055. image.src = url;
  26056. return image;
  26057. }
  26058. }
  26059. class CubeTextureLoader extends Loader {
  26060. constructor( manager ) {
  26061. super( manager );
  26062. }
  26063. load( urls, onLoad, onProgress, onError ) {
  26064. const texture = new CubeTexture();
  26065. texture.colorSpace = SRGBColorSpace;
  26066. const loader = new ImageLoader( this.manager );
  26067. loader.setCrossOrigin( this.crossOrigin );
  26068. loader.setPath( this.path );
  26069. let loaded = 0;
  26070. function loadTexture( i ) {
  26071. loader.load( urls[ i ], function ( image ) {
  26072. texture.images[ i ] = image;
  26073. loaded ++;
  26074. if ( loaded === 6 ) {
  26075. texture.needsUpdate = true;
  26076. if ( onLoad ) onLoad( texture );
  26077. }
  26078. }, undefined, onError );
  26079. }
  26080. for ( let i = 0; i < urls.length; ++ i ) {
  26081. loadTexture( i );
  26082. }
  26083. return texture;
  26084. }
  26085. }
  26086. /**
  26087. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  26088. *
  26089. * Sub classes have to implement the parse() method which will be used in load().
  26090. */
  26091. class DataTextureLoader extends Loader {
  26092. constructor( manager ) {
  26093. super( manager );
  26094. }
  26095. load( url, onLoad, onProgress, onError ) {
  26096. const scope = this;
  26097. const texture = new DataTexture();
  26098. const loader = new FileLoader( this.manager );
  26099. loader.setResponseType( 'arraybuffer' );
  26100. loader.setRequestHeader( this.requestHeader );
  26101. loader.setPath( this.path );
  26102. loader.setWithCredentials( scope.withCredentials );
  26103. loader.load( url, function ( buffer ) {
  26104. let texData;
  26105. try {
  26106. texData = scope.parse( buffer );
  26107. } catch ( error ) {
  26108. if ( onError !== undefined ) {
  26109. onError( error );
  26110. } else {
  26111. console.error( error );
  26112. return;
  26113. }
  26114. }
  26115. if ( texData.image !== undefined ) {
  26116. texture.image = texData.image;
  26117. } else if ( texData.data !== undefined ) {
  26118. texture.image.width = texData.width;
  26119. texture.image.height = texData.height;
  26120. texture.image.data = texData.data;
  26121. }
  26122. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  26123. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  26124. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  26125. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  26126. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  26127. if ( texData.colorSpace !== undefined ) {
  26128. texture.colorSpace = texData.colorSpace;
  26129. } else if ( texData.encoding !== undefined ) { // @deprecated, r152
  26130. texture.encoding = texData.encoding;
  26131. }
  26132. if ( texData.flipY !== undefined ) {
  26133. texture.flipY = texData.flipY;
  26134. }
  26135. if ( texData.format !== undefined ) {
  26136. texture.format = texData.format;
  26137. }
  26138. if ( texData.type !== undefined ) {
  26139. texture.type = texData.type;
  26140. }
  26141. if ( texData.mipmaps !== undefined ) {
  26142. texture.mipmaps = texData.mipmaps;
  26143. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  26144. }
  26145. if ( texData.mipmapCount === 1 ) {
  26146. texture.minFilter = LinearFilter;
  26147. }
  26148. if ( texData.generateMipmaps !== undefined ) {
  26149. texture.generateMipmaps = texData.generateMipmaps;
  26150. }
  26151. texture.needsUpdate = true;
  26152. if ( onLoad ) onLoad( texture, texData );
  26153. }, onProgress, onError );
  26154. return texture;
  26155. }
  26156. }
  26157. class TextureLoader extends Loader {
  26158. constructor( manager ) {
  26159. super( manager );
  26160. }
  26161. load( url, onLoad, onProgress, onError ) {
  26162. const texture = new Texture();
  26163. const loader = new ImageLoader( this.manager );
  26164. loader.setCrossOrigin( this.crossOrigin );
  26165. loader.setPath( this.path );
  26166. loader.load( url, function ( image ) {
  26167. texture.image = image;
  26168. texture.needsUpdate = true;
  26169. if ( onLoad !== undefined ) {
  26170. onLoad( texture );
  26171. }
  26172. }, onProgress, onError );
  26173. return texture;
  26174. }
  26175. }
  26176. class Light extends Object3D {
  26177. constructor( color, intensity = 1 ) {
  26178. super();
  26179. this.isLight = true;
  26180. this.type = 'Light';
  26181. this.color = new Color( color );
  26182. this.intensity = intensity;
  26183. }
  26184. dispose() {
  26185. // Empty here in base class; some subclasses override.
  26186. }
  26187. copy( source, recursive ) {
  26188. super.copy( source, recursive );
  26189. this.color.copy( source.color );
  26190. this.intensity = source.intensity;
  26191. return this;
  26192. }
  26193. toJSON( meta ) {
  26194. const data = super.toJSON( meta );
  26195. data.object.color = this.color.getHex();
  26196. data.object.intensity = this.intensity;
  26197. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26198. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26199. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26200. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26201. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26202. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26203. return data;
  26204. }
  26205. }
  26206. class HemisphereLight extends Light {
  26207. constructor( skyColor, groundColor, intensity ) {
  26208. super( skyColor, intensity );
  26209. this.isHemisphereLight = true;
  26210. this.type = 'HemisphereLight';
  26211. this.position.copy( Object3D.DEFAULT_UP );
  26212. this.updateMatrix();
  26213. this.groundColor = new Color( groundColor );
  26214. }
  26215. copy( source, recursive ) {
  26216. super.copy( source, recursive );
  26217. this.groundColor.copy( source.groundColor );
  26218. return this;
  26219. }
  26220. }
  26221. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  26222. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  26223. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  26224. class LightShadow {
  26225. constructor( camera ) {
  26226. this.camera = camera;
  26227. this.bias = 0;
  26228. this.normalBias = 0;
  26229. this.radius = 1;
  26230. this.blurSamples = 8;
  26231. this.mapSize = new Vector2( 512, 512 );
  26232. this.map = null;
  26233. this.mapPass = null;
  26234. this.matrix = new Matrix4();
  26235. this.autoUpdate = true;
  26236. this.needsUpdate = false;
  26237. this._frustum = new Frustum();
  26238. this._frameExtents = new Vector2( 1, 1 );
  26239. this._viewportCount = 1;
  26240. this._viewports = [
  26241. new Vector4( 0, 0, 1, 1 )
  26242. ];
  26243. }
  26244. getViewportCount() {
  26245. return this._viewportCount;
  26246. }
  26247. getFrustum() {
  26248. return this._frustum;
  26249. }
  26250. updateMatrices( light ) {
  26251. const shadowCamera = this.camera;
  26252. const shadowMatrix = this.matrix;
  26253. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  26254. shadowCamera.position.copy( _lightPositionWorld$1 );
  26255. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  26256. shadowCamera.lookAt( _lookTarget$1 );
  26257. shadowCamera.updateMatrixWorld();
  26258. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  26259. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  26260. shadowMatrix.set(
  26261. 0.5, 0.0, 0.0, 0.5,
  26262. 0.0, 0.5, 0.0, 0.5,
  26263. 0.0, 0.0, 0.5, 0.5,
  26264. 0.0, 0.0, 0.0, 1.0
  26265. );
  26266. shadowMatrix.multiply( _projScreenMatrix$1 );
  26267. }
  26268. getViewport( viewportIndex ) {
  26269. return this._viewports[ viewportIndex ];
  26270. }
  26271. getFrameExtents() {
  26272. return this._frameExtents;
  26273. }
  26274. dispose() {
  26275. if ( this.map ) {
  26276. this.map.dispose();
  26277. }
  26278. if ( this.mapPass ) {
  26279. this.mapPass.dispose();
  26280. }
  26281. }
  26282. copy( source ) {
  26283. this.camera = source.camera.clone();
  26284. this.bias = source.bias;
  26285. this.radius = source.radius;
  26286. this.mapSize.copy( source.mapSize );
  26287. return this;
  26288. }
  26289. clone() {
  26290. return new this.constructor().copy( this );
  26291. }
  26292. toJSON() {
  26293. const object = {};
  26294. if ( this.bias !== 0 ) object.bias = this.bias;
  26295. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  26296. if ( this.radius !== 1 ) object.radius = this.radius;
  26297. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26298. object.camera = this.camera.toJSON( false ).object;
  26299. delete object.camera.matrix;
  26300. return object;
  26301. }
  26302. }
  26303. class SpotLightShadow extends LightShadow {
  26304. constructor() {
  26305. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26306. this.isSpotLightShadow = true;
  26307. this.focus = 1;
  26308. }
  26309. updateMatrices( light ) {
  26310. const camera = this.camera;
  26311. const fov = RAD2DEG * 2 * light.angle * this.focus;
  26312. const aspect = this.mapSize.width / this.mapSize.height;
  26313. const far = light.distance || camera.far;
  26314. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  26315. camera.fov = fov;
  26316. camera.aspect = aspect;
  26317. camera.far = far;
  26318. camera.updateProjectionMatrix();
  26319. }
  26320. super.updateMatrices( light );
  26321. }
  26322. copy( source ) {
  26323. super.copy( source );
  26324. this.focus = source.focus;
  26325. return this;
  26326. }
  26327. }
  26328. class SpotLight extends Light {
  26329. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  26330. super( color, intensity );
  26331. this.isSpotLight = true;
  26332. this.type = 'SpotLight';
  26333. this.position.copy( Object3D.DEFAULT_UP );
  26334. this.updateMatrix();
  26335. this.target = new Object3D();
  26336. this.distance = distance;
  26337. this.angle = angle;
  26338. this.penumbra = penumbra;
  26339. this.decay = decay;
  26340. this.map = null;
  26341. this.shadow = new SpotLightShadow();
  26342. }
  26343. get power() {
  26344. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26345. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  26346. return this.intensity * Math.PI;
  26347. }
  26348. set power( power ) {
  26349. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26350. this.intensity = power / Math.PI;
  26351. }
  26352. dispose() {
  26353. this.shadow.dispose();
  26354. }
  26355. copy( source, recursive ) {
  26356. super.copy( source, recursive );
  26357. this.distance = source.distance;
  26358. this.angle = source.angle;
  26359. this.penumbra = source.penumbra;
  26360. this.decay = source.decay;
  26361. this.target = source.target.clone();
  26362. this.shadow = source.shadow.clone();
  26363. return this;
  26364. }
  26365. }
  26366. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  26367. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  26368. const _lookTarget = /*@__PURE__*/ new Vector3();
  26369. class PointLightShadow extends LightShadow {
  26370. constructor() {
  26371. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  26372. this.isPointLightShadow = true;
  26373. this._frameExtents = new Vector2( 4, 2 );
  26374. this._viewportCount = 6;
  26375. this._viewports = [
  26376. // These viewports map a cube-map onto a 2D texture with the
  26377. // following orientation:
  26378. //
  26379. // xzXZ
  26380. // y Y
  26381. //
  26382. // X - Positive x direction
  26383. // x - Negative x direction
  26384. // Y - Positive y direction
  26385. // y - Negative y direction
  26386. // Z - Positive z direction
  26387. // z - Negative z direction
  26388. // positive X
  26389. new Vector4( 2, 1, 1, 1 ),
  26390. // negative X
  26391. new Vector4( 0, 1, 1, 1 ),
  26392. // positive Z
  26393. new Vector4( 3, 1, 1, 1 ),
  26394. // negative Z
  26395. new Vector4( 1, 1, 1, 1 ),
  26396. // positive Y
  26397. new Vector4( 3, 0, 1, 1 ),
  26398. // negative Y
  26399. new Vector4( 1, 0, 1, 1 )
  26400. ];
  26401. this._cubeDirections = [
  26402. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  26403. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  26404. ];
  26405. this._cubeUps = [
  26406. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  26407. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  26408. ];
  26409. }
  26410. updateMatrices( light, viewportIndex = 0 ) {
  26411. const camera = this.camera;
  26412. const shadowMatrix = this.matrix;
  26413. const far = light.distance || camera.far;
  26414. if ( far !== camera.far ) {
  26415. camera.far = far;
  26416. camera.updateProjectionMatrix();
  26417. }
  26418. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  26419. camera.position.copy( _lightPositionWorld );
  26420. _lookTarget.copy( camera.position );
  26421. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  26422. camera.up.copy( this._cubeUps[ viewportIndex ] );
  26423. camera.lookAt( _lookTarget );
  26424. camera.updateMatrixWorld();
  26425. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  26426. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  26427. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  26428. }
  26429. }
  26430. class PointLight extends Light {
  26431. constructor( color, intensity, distance = 0, decay = 2 ) {
  26432. super( color, intensity );
  26433. this.isPointLight = true;
  26434. this.type = 'PointLight';
  26435. this.distance = distance;
  26436. this.decay = decay;
  26437. this.shadow = new PointLightShadow();
  26438. }
  26439. get power() {
  26440. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26441. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  26442. return this.intensity * 4 * Math.PI;
  26443. }
  26444. set power( power ) {
  26445. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26446. this.intensity = power / ( 4 * Math.PI );
  26447. }
  26448. dispose() {
  26449. this.shadow.dispose();
  26450. }
  26451. copy( source, recursive ) {
  26452. super.copy( source, recursive );
  26453. this.distance = source.distance;
  26454. this.decay = source.decay;
  26455. this.shadow = source.shadow.clone();
  26456. return this;
  26457. }
  26458. }
  26459. class DirectionalLightShadow extends LightShadow {
  26460. constructor() {
  26461. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  26462. this.isDirectionalLightShadow = true;
  26463. }
  26464. }
  26465. class DirectionalLight extends Light {
  26466. constructor( color, intensity ) {
  26467. super( color, intensity );
  26468. this.isDirectionalLight = true;
  26469. this.type = 'DirectionalLight';
  26470. this.position.copy( Object3D.DEFAULT_UP );
  26471. this.updateMatrix();
  26472. this.target = new Object3D();
  26473. this.shadow = new DirectionalLightShadow();
  26474. }
  26475. dispose() {
  26476. this.shadow.dispose();
  26477. }
  26478. copy( source ) {
  26479. super.copy( source );
  26480. this.target = source.target.clone();
  26481. this.shadow = source.shadow.clone();
  26482. return this;
  26483. }
  26484. }
  26485. class AmbientLight extends Light {
  26486. constructor( color, intensity ) {
  26487. super( color, intensity );
  26488. this.isAmbientLight = true;
  26489. this.type = 'AmbientLight';
  26490. }
  26491. }
  26492. class RectAreaLight extends Light {
  26493. constructor( color, intensity, width = 10, height = 10 ) {
  26494. super( color, intensity );
  26495. this.isRectAreaLight = true;
  26496. this.type = 'RectAreaLight';
  26497. this.width = width;
  26498. this.height = height;
  26499. }
  26500. get power() {
  26501. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26502. return this.intensity * this.width * this.height * Math.PI;
  26503. }
  26504. set power( power ) {
  26505. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26506. this.intensity = power / ( this.width * this.height * Math.PI );
  26507. }
  26508. copy( source ) {
  26509. super.copy( source );
  26510. this.width = source.width;
  26511. this.height = source.height;
  26512. return this;
  26513. }
  26514. toJSON( meta ) {
  26515. const data = super.toJSON( meta );
  26516. data.object.width = this.width;
  26517. data.object.height = this.height;
  26518. return data;
  26519. }
  26520. }
  26521. /**
  26522. * Primary reference:
  26523. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26524. *
  26525. * Secondary reference:
  26526. * https://www.ppsloan.org/publications/StupidSH36.pdf
  26527. */
  26528. // 3-band SH defined by 9 coefficients
  26529. class SphericalHarmonics3 {
  26530. constructor() {
  26531. this.isSphericalHarmonics3 = true;
  26532. this.coefficients = [];
  26533. for ( let i = 0; i < 9; i ++ ) {
  26534. this.coefficients.push( new Vector3() );
  26535. }
  26536. }
  26537. set( coefficients ) {
  26538. for ( let i = 0; i < 9; i ++ ) {
  26539. this.coefficients[ i ].copy( coefficients[ i ] );
  26540. }
  26541. return this;
  26542. }
  26543. zero() {
  26544. for ( let i = 0; i < 9; i ++ ) {
  26545. this.coefficients[ i ].set( 0, 0, 0 );
  26546. }
  26547. return this;
  26548. }
  26549. // get the radiance in the direction of the normal
  26550. // target is a Vector3
  26551. getAt( normal, target ) {
  26552. // normal is assumed to be unit length
  26553. const x = normal.x, y = normal.y, z = normal.z;
  26554. const coeff = this.coefficients;
  26555. // band 0
  26556. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  26557. // band 1
  26558. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  26559. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  26560. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  26561. // band 2
  26562. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  26563. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  26564. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  26565. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  26566. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  26567. return target;
  26568. }
  26569. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  26570. // target is a Vector3
  26571. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26572. getIrradianceAt( normal, target ) {
  26573. // normal is assumed to be unit length
  26574. const x = normal.x, y = normal.y, z = normal.z;
  26575. const coeff = this.coefficients;
  26576. // band 0
  26577. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  26578. // band 1
  26579. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  26580. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  26581. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  26582. // band 2
  26583. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  26584. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  26585. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  26586. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  26587. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  26588. return target;
  26589. }
  26590. add( sh ) {
  26591. for ( let i = 0; i < 9; i ++ ) {
  26592. this.coefficients[ i ].add( sh.coefficients[ i ] );
  26593. }
  26594. return this;
  26595. }
  26596. addScaledSH( sh, s ) {
  26597. for ( let i = 0; i < 9; i ++ ) {
  26598. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  26599. }
  26600. return this;
  26601. }
  26602. scale( s ) {
  26603. for ( let i = 0; i < 9; i ++ ) {
  26604. this.coefficients[ i ].multiplyScalar( s );
  26605. }
  26606. return this;
  26607. }
  26608. lerp( sh, alpha ) {
  26609. for ( let i = 0; i < 9; i ++ ) {
  26610. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  26611. }
  26612. return this;
  26613. }
  26614. equals( sh ) {
  26615. for ( let i = 0; i < 9; i ++ ) {
  26616. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  26617. return false;
  26618. }
  26619. }
  26620. return true;
  26621. }
  26622. copy( sh ) {
  26623. return this.set( sh.coefficients );
  26624. }
  26625. clone() {
  26626. return new this.constructor().copy( this );
  26627. }
  26628. fromArray( array, offset = 0 ) {
  26629. const coefficients = this.coefficients;
  26630. for ( let i = 0; i < 9; i ++ ) {
  26631. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  26632. }
  26633. return this;
  26634. }
  26635. toArray( array = [], offset = 0 ) {
  26636. const coefficients = this.coefficients;
  26637. for ( let i = 0; i < 9; i ++ ) {
  26638. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  26639. }
  26640. return array;
  26641. }
  26642. // evaluate the basis functions
  26643. // shBasis is an Array[ 9 ]
  26644. static getBasisAt( normal, shBasis ) {
  26645. // normal is assumed to be unit length
  26646. const x = normal.x, y = normal.y, z = normal.z;
  26647. // band 0
  26648. shBasis[ 0 ] = 0.282095;
  26649. // band 1
  26650. shBasis[ 1 ] = 0.488603 * y;
  26651. shBasis[ 2 ] = 0.488603 * z;
  26652. shBasis[ 3 ] = 0.488603 * x;
  26653. // band 2
  26654. shBasis[ 4 ] = 1.092548 * x * y;
  26655. shBasis[ 5 ] = 1.092548 * y * z;
  26656. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  26657. shBasis[ 7 ] = 1.092548 * x * z;
  26658. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  26659. }
  26660. }
  26661. class LightProbe extends Light {
  26662. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  26663. super( undefined, intensity );
  26664. this.isLightProbe = true;
  26665. this.sh = sh;
  26666. }
  26667. copy( source ) {
  26668. super.copy( source );
  26669. this.sh.copy( source.sh );
  26670. return this;
  26671. }
  26672. fromJSON( json ) {
  26673. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  26674. this.sh.fromArray( json.sh );
  26675. return this;
  26676. }
  26677. toJSON( meta ) {
  26678. const data = super.toJSON( meta );
  26679. data.object.sh = this.sh.toArray();
  26680. return data;
  26681. }
  26682. }
  26683. class MaterialLoader extends Loader {
  26684. constructor( manager ) {
  26685. super( manager );
  26686. this.textures = {};
  26687. }
  26688. load( url, onLoad, onProgress, onError ) {
  26689. const scope = this;
  26690. const loader = new FileLoader( scope.manager );
  26691. loader.setPath( scope.path );
  26692. loader.setRequestHeader( scope.requestHeader );
  26693. loader.setWithCredentials( scope.withCredentials );
  26694. loader.load( url, function ( text ) {
  26695. try {
  26696. onLoad( scope.parse( JSON.parse( text ) ) );
  26697. } catch ( e ) {
  26698. if ( onError ) {
  26699. onError( e );
  26700. } else {
  26701. console.error( e );
  26702. }
  26703. scope.manager.itemError( url );
  26704. }
  26705. }, onProgress, onError );
  26706. }
  26707. parse( json ) {
  26708. const textures = this.textures;
  26709. function getTexture( name ) {
  26710. if ( textures[ name ] === undefined ) {
  26711. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26712. }
  26713. return textures[ name ];
  26714. }
  26715. const material = MaterialLoader.createMaterialFromType( json.type );
  26716. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26717. if ( json.name !== undefined ) material.name = json.name;
  26718. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  26719. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26720. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26721. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  26722. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  26723. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  26724. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26725. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  26726. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  26727. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  26728. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26729. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  26730. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  26731. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  26732. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  26733. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  26734. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  26735. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  26736. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  26737. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  26738. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  26739. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  26740. if ( json.fog !== undefined ) material.fog = json.fog;
  26741. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  26742. if ( json.blending !== undefined ) material.blending = json.blending;
  26743. if ( json.combine !== undefined ) material.combine = json.combine;
  26744. if ( json.side !== undefined ) material.side = json.side;
  26745. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  26746. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  26747. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  26748. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  26749. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  26750. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  26751. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  26752. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  26753. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  26754. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  26755. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  26756. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  26757. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  26758. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  26759. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  26760. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  26761. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  26762. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  26763. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  26764. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  26765. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  26766. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  26767. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  26768. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  26769. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  26770. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  26771. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  26772. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  26773. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  26774. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  26775. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  26776. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  26777. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  26778. if ( json.scale !== undefined ) material.scale = json.scale;
  26779. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  26780. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  26781. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  26782. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  26783. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  26784. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  26785. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  26786. if ( json.visible !== undefined ) material.visible = json.visible;
  26787. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  26788. if ( json.userData !== undefined ) material.userData = json.userData;
  26789. if ( json.vertexColors !== undefined ) {
  26790. if ( typeof json.vertexColors === 'number' ) {
  26791. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  26792. } else {
  26793. material.vertexColors = json.vertexColors;
  26794. }
  26795. }
  26796. // Shader Material
  26797. if ( json.uniforms !== undefined ) {
  26798. for ( const name in json.uniforms ) {
  26799. const uniform = json.uniforms[ name ];
  26800. material.uniforms[ name ] = {};
  26801. switch ( uniform.type ) {
  26802. case 't':
  26803. material.uniforms[ name ].value = getTexture( uniform.value );
  26804. break;
  26805. case 'c':
  26806. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  26807. break;
  26808. case 'v2':
  26809. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  26810. break;
  26811. case 'v3':
  26812. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  26813. break;
  26814. case 'v4':
  26815. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  26816. break;
  26817. case 'm3':
  26818. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  26819. break;
  26820. case 'm4':
  26821. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  26822. break;
  26823. default:
  26824. material.uniforms[ name ].value = uniform.value;
  26825. }
  26826. }
  26827. }
  26828. if ( json.defines !== undefined ) material.defines = json.defines;
  26829. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  26830. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  26831. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  26832. if ( json.extensions !== undefined ) {
  26833. for ( const key in json.extensions ) {
  26834. material.extensions[ key ] = json.extensions[ key ];
  26835. }
  26836. }
  26837. if ( json.lights !== undefined ) material.lights = json.lights;
  26838. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  26839. // for PointsMaterial
  26840. if ( json.size !== undefined ) material.size = json.size;
  26841. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  26842. // maps
  26843. if ( json.map !== undefined ) material.map = getTexture( json.map );
  26844. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  26845. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  26846. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  26847. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  26848. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  26849. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  26850. if ( json.normalScale !== undefined ) {
  26851. let normalScale = json.normalScale;
  26852. if ( Array.isArray( normalScale ) === false ) {
  26853. // Blender exporter used to export a scalar. See #7459
  26854. normalScale = [ normalScale, normalScale ];
  26855. }
  26856. material.normalScale = new Vector2().fromArray( normalScale );
  26857. }
  26858. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  26859. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  26860. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  26861. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  26862. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  26863. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  26864. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  26865. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  26866. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  26867. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  26868. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  26869. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  26870. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  26871. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  26872. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  26873. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  26874. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  26875. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  26876. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  26877. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  26878. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  26879. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  26880. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  26881. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  26882. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  26883. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  26884. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  26885. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  26886. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  26887. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  26888. return material;
  26889. }
  26890. setTextures( value ) {
  26891. this.textures = value;
  26892. return this;
  26893. }
  26894. static createMaterialFromType( type ) {
  26895. const materialLib = {
  26896. ShadowMaterial,
  26897. SpriteMaterial,
  26898. RawShaderMaterial,
  26899. ShaderMaterial,
  26900. PointsMaterial,
  26901. MeshPhysicalMaterial,
  26902. MeshStandardMaterial,
  26903. MeshPhongMaterial,
  26904. MeshToonMaterial,
  26905. MeshNormalMaterial,
  26906. MeshLambertMaterial,
  26907. MeshDepthMaterial,
  26908. MeshDistanceMaterial,
  26909. MeshBasicMaterial,
  26910. MeshMatcapMaterial,
  26911. LineDashedMaterial,
  26912. LineBasicMaterial,
  26913. Material
  26914. };
  26915. return new materialLib[ type ]();
  26916. }
  26917. }
  26918. class LoaderUtils {
  26919. static decodeText( array ) {
  26920. if ( typeof TextDecoder !== 'undefined' ) {
  26921. return new TextDecoder().decode( array );
  26922. }
  26923. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26924. // throws a "maximum call stack size exceeded" error for large arrays.
  26925. let s = '';
  26926. for ( let i = 0, il = array.length; i < il; i ++ ) {
  26927. // Implicitly assumes little-endian.
  26928. s += String.fromCharCode( array[ i ] );
  26929. }
  26930. try {
  26931. // merges multi-byte utf-8 characters.
  26932. return decodeURIComponent( escape( s ) );
  26933. } catch ( e ) { // see #16358
  26934. return s;
  26935. }
  26936. }
  26937. static extractUrlBase( url ) {
  26938. const index = url.lastIndexOf( '/' );
  26939. if ( index === - 1 ) return './';
  26940. return url.slice( 0, index + 1 );
  26941. }
  26942. static resolveURL( url, path ) {
  26943. // Invalid URL
  26944. if ( typeof url !== 'string' || url === '' ) return '';
  26945. // Host Relative URL
  26946. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  26947. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  26948. }
  26949. // Absolute URL http://,https://,//
  26950. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  26951. // Data URI
  26952. if ( /^data:.*,.*$/i.test( url ) ) return url;
  26953. // Blob URL
  26954. if ( /^blob:.*$/i.test( url ) ) return url;
  26955. // Relative URL
  26956. return path + url;
  26957. }
  26958. }
  26959. class InstancedBufferGeometry extends BufferGeometry {
  26960. constructor() {
  26961. super();
  26962. this.isInstancedBufferGeometry = true;
  26963. this.type = 'InstancedBufferGeometry';
  26964. this.instanceCount = Infinity;
  26965. }
  26966. copy( source ) {
  26967. super.copy( source );
  26968. this.instanceCount = source.instanceCount;
  26969. return this;
  26970. }
  26971. toJSON() {
  26972. const data = super.toJSON();
  26973. data.instanceCount = this.instanceCount;
  26974. data.isInstancedBufferGeometry = true;
  26975. return data;
  26976. }
  26977. }
  26978. class BufferGeometryLoader extends Loader {
  26979. constructor( manager ) {
  26980. super( manager );
  26981. }
  26982. load( url, onLoad, onProgress, onError ) {
  26983. const scope = this;
  26984. const loader = new FileLoader( scope.manager );
  26985. loader.setPath( scope.path );
  26986. loader.setRequestHeader( scope.requestHeader );
  26987. loader.setWithCredentials( scope.withCredentials );
  26988. loader.load( url, function ( text ) {
  26989. try {
  26990. onLoad( scope.parse( JSON.parse( text ) ) );
  26991. } catch ( e ) {
  26992. if ( onError ) {
  26993. onError( e );
  26994. } else {
  26995. console.error( e );
  26996. }
  26997. scope.manager.itemError( url );
  26998. }
  26999. }, onProgress, onError );
  27000. }
  27001. parse( json ) {
  27002. const interleavedBufferMap = {};
  27003. const arrayBufferMap = {};
  27004. function getInterleavedBuffer( json, uuid ) {
  27005. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  27006. const interleavedBuffers = json.interleavedBuffers;
  27007. const interleavedBuffer = interleavedBuffers[ uuid ];
  27008. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  27009. const array = getTypedArray( interleavedBuffer.type, buffer );
  27010. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  27011. ib.uuid = interleavedBuffer.uuid;
  27012. interleavedBufferMap[ uuid ] = ib;
  27013. return ib;
  27014. }
  27015. function getArrayBuffer( json, uuid ) {
  27016. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  27017. const arrayBuffers = json.arrayBuffers;
  27018. const arrayBuffer = arrayBuffers[ uuid ];
  27019. const ab = new Uint32Array( arrayBuffer ).buffer;
  27020. arrayBufferMap[ uuid ] = ab;
  27021. return ab;
  27022. }
  27023. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  27024. const index = json.data.index;
  27025. if ( index !== undefined ) {
  27026. const typedArray = getTypedArray( index.type, index.array );
  27027. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  27028. }
  27029. const attributes = json.data.attributes;
  27030. for ( const key in attributes ) {
  27031. const attribute = attributes[ key ];
  27032. let bufferAttribute;
  27033. if ( attribute.isInterleavedBufferAttribute ) {
  27034. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27035. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27036. } else {
  27037. const typedArray = getTypedArray( attribute.type, attribute.array );
  27038. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  27039. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  27040. }
  27041. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27042. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  27043. geometry.setAttribute( key, bufferAttribute );
  27044. }
  27045. const morphAttributes = json.data.morphAttributes;
  27046. if ( morphAttributes ) {
  27047. for ( const key in morphAttributes ) {
  27048. const attributeArray = morphAttributes[ key ];
  27049. const array = [];
  27050. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  27051. const attribute = attributeArray[ i ];
  27052. let bufferAttribute;
  27053. if ( attribute.isInterleavedBufferAttribute ) {
  27054. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27055. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27056. } else {
  27057. const typedArray = getTypedArray( attribute.type, attribute.array );
  27058. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27059. }
  27060. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27061. array.push( bufferAttribute );
  27062. }
  27063. geometry.morphAttributes[ key ] = array;
  27064. }
  27065. }
  27066. const morphTargetsRelative = json.data.morphTargetsRelative;
  27067. if ( morphTargetsRelative ) {
  27068. geometry.morphTargetsRelative = true;
  27069. }
  27070. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  27071. if ( groups !== undefined ) {
  27072. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  27073. const group = groups[ i ];
  27074. geometry.addGroup( group.start, group.count, group.materialIndex );
  27075. }
  27076. }
  27077. const boundingSphere = json.data.boundingSphere;
  27078. if ( boundingSphere !== undefined ) {
  27079. const center = new Vector3();
  27080. if ( boundingSphere.center !== undefined ) {
  27081. center.fromArray( boundingSphere.center );
  27082. }
  27083. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  27084. }
  27085. if ( json.name ) geometry.name = json.name;
  27086. if ( json.userData ) geometry.userData = json.userData;
  27087. return geometry;
  27088. }
  27089. }
  27090. class ObjectLoader extends Loader {
  27091. constructor( manager ) {
  27092. super( manager );
  27093. }
  27094. load( url, onLoad, onProgress, onError ) {
  27095. const scope = this;
  27096. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27097. this.resourcePath = this.resourcePath || path;
  27098. const loader = new FileLoader( this.manager );
  27099. loader.setPath( this.path );
  27100. loader.setRequestHeader( this.requestHeader );
  27101. loader.setWithCredentials( this.withCredentials );
  27102. loader.load( url, function ( text ) {
  27103. let json = null;
  27104. try {
  27105. json = JSON.parse( text );
  27106. } catch ( error ) {
  27107. if ( onError !== undefined ) onError( error );
  27108. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  27109. return;
  27110. }
  27111. const metadata = json.metadata;
  27112. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27113. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  27114. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27115. return;
  27116. }
  27117. scope.parse( json, onLoad );
  27118. }, onProgress, onError );
  27119. }
  27120. async loadAsync( url, onProgress ) {
  27121. const scope = this;
  27122. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27123. this.resourcePath = this.resourcePath || path;
  27124. const loader = new FileLoader( this.manager );
  27125. loader.setPath( this.path );
  27126. loader.setRequestHeader( this.requestHeader );
  27127. loader.setWithCredentials( this.withCredentials );
  27128. const text = await loader.loadAsync( url, onProgress );
  27129. const json = JSON.parse( text );
  27130. const metadata = json.metadata;
  27131. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27132. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27133. }
  27134. return await scope.parseAsync( json );
  27135. }
  27136. parse( json, onLoad ) {
  27137. const animations = this.parseAnimations( json.animations );
  27138. const shapes = this.parseShapes( json.shapes );
  27139. const geometries = this.parseGeometries( json.geometries, shapes );
  27140. const images = this.parseImages( json.images, function () {
  27141. if ( onLoad !== undefined ) onLoad( object );
  27142. } );
  27143. const textures = this.parseTextures( json.textures, images );
  27144. const materials = this.parseMaterials( json.materials, textures );
  27145. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27146. const skeletons = this.parseSkeletons( json.skeletons, object );
  27147. this.bindSkeletons( object, skeletons );
  27148. //
  27149. if ( onLoad !== undefined ) {
  27150. let hasImages = false;
  27151. for ( const uuid in images ) {
  27152. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27153. hasImages = true;
  27154. break;
  27155. }
  27156. }
  27157. if ( hasImages === false ) onLoad( object );
  27158. }
  27159. return object;
  27160. }
  27161. async parseAsync( json ) {
  27162. const animations = this.parseAnimations( json.animations );
  27163. const shapes = this.parseShapes( json.shapes );
  27164. const geometries = this.parseGeometries( json.geometries, shapes );
  27165. const images = await this.parseImagesAsync( json.images );
  27166. const textures = this.parseTextures( json.textures, images );
  27167. const materials = this.parseMaterials( json.materials, textures );
  27168. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27169. const skeletons = this.parseSkeletons( json.skeletons, object );
  27170. this.bindSkeletons( object, skeletons );
  27171. return object;
  27172. }
  27173. parseShapes( json ) {
  27174. const shapes = {};
  27175. if ( json !== undefined ) {
  27176. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27177. const shape = new Shape().fromJSON( json[ i ] );
  27178. shapes[ shape.uuid ] = shape;
  27179. }
  27180. }
  27181. return shapes;
  27182. }
  27183. parseSkeletons( json, object ) {
  27184. const skeletons = {};
  27185. const bones = {};
  27186. // generate bone lookup table
  27187. object.traverse( function ( child ) {
  27188. if ( child.isBone ) bones[ child.uuid ] = child;
  27189. } );
  27190. // create skeletons
  27191. if ( json !== undefined ) {
  27192. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27193. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27194. skeletons[ skeleton.uuid ] = skeleton;
  27195. }
  27196. }
  27197. return skeletons;
  27198. }
  27199. parseGeometries( json, shapes ) {
  27200. const geometries = {};
  27201. if ( json !== undefined ) {
  27202. const bufferGeometryLoader = new BufferGeometryLoader();
  27203. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27204. let geometry;
  27205. const data = json[ i ];
  27206. switch ( data.type ) {
  27207. case 'BufferGeometry':
  27208. case 'InstancedBufferGeometry':
  27209. geometry = bufferGeometryLoader.parse( data );
  27210. break;
  27211. default:
  27212. if ( data.type in Geometries ) {
  27213. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27214. } else {
  27215. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27216. }
  27217. }
  27218. geometry.uuid = data.uuid;
  27219. if ( data.name !== undefined ) geometry.name = data.name;
  27220. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27221. geometries[ data.uuid ] = geometry;
  27222. }
  27223. }
  27224. return geometries;
  27225. }
  27226. parseMaterials( json, textures ) {
  27227. const cache = {}; // MultiMaterial
  27228. const materials = {};
  27229. if ( json !== undefined ) {
  27230. const loader = new MaterialLoader();
  27231. loader.setTextures( textures );
  27232. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27233. const data = json[ i ];
  27234. if ( cache[ data.uuid ] === undefined ) {
  27235. cache[ data.uuid ] = loader.parse( data );
  27236. }
  27237. materials[ data.uuid ] = cache[ data.uuid ];
  27238. }
  27239. }
  27240. return materials;
  27241. }
  27242. parseAnimations( json ) {
  27243. const animations = {};
  27244. if ( json !== undefined ) {
  27245. for ( let i = 0; i < json.length; i ++ ) {
  27246. const data = json[ i ];
  27247. const clip = AnimationClip.parse( data );
  27248. animations[ clip.uuid ] = clip;
  27249. }
  27250. }
  27251. return animations;
  27252. }
  27253. parseImages( json, onLoad ) {
  27254. const scope = this;
  27255. const images = {};
  27256. let loader;
  27257. function loadImage( url ) {
  27258. scope.manager.itemStart( url );
  27259. return loader.load( url, function () {
  27260. scope.manager.itemEnd( url );
  27261. }, undefined, function () {
  27262. scope.manager.itemError( url );
  27263. scope.manager.itemEnd( url );
  27264. } );
  27265. }
  27266. function deserializeImage( image ) {
  27267. if ( typeof image === 'string' ) {
  27268. const url = image;
  27269. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27270. return loadImage( path );
  27271. } else {
  27272. if ( image.data ) {
  27273. return {
  27274. data: getTypedArray( image.type, image.data ),
  27275. width: image.width,
  27276. height: image.height
  27277. };
  27278. } else {
  27279. return null;
  27280. }
  27281. }
  27282. }
  27283. if ( json !== undefined && json.length > 0 ) {
  27284. const manager = new LoadingManager( onLoad );
  27285. loader = new ImageLoader( manager );
  27286. loader.setCrossOrigin( this.crossOrigin );
  27287. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27288. const image = json[ i ];
  27289. const url = image.url;
  27290. if ( Array.isArray( url ) ) {
  27291. // load array of images e.g CubeTexture
  27292. const imageArray = [];
  27293. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27294. const currentUrl = url[ j ];
  27295. const deserializedImage = deserializeImage( currentUrl );
  27296. if ( deserializedImage !== null ) {
  27297. if ( deserializedImage instanceof HTMLImageElement ) {
  27298. imageArray.push( deserializedImage );
  27299. } else {
  27300. // special case: handle array of data textures for cube textures
  27301. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27302. }
  27303. }
  27304. }
  27305. images[ image.uuid ] = new Source( imageArray );
  27306. } else {
  27307. // load single image
  27308. const deserializedImage = deserializeImage( image.url );
  27309. images[ image.uuid ] = new Source( deserializedImage );
  27310. }
  27311. }
  27312. }
  27313. return images;
  27314. }
  27315. async parseImagesAsync( json ) {
  27316. const scope = this;
  27317. const images = {};
  27318. let loader;
  27319. async function deserializeImage( image ) {
  27320. if ( typeof image === 'string' ) {
  27321. const url = image;
  27322. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27323. return await loader.loadAsync( path );
  27324. } else {
  27325. if ( image.data ) {
  27326. return {
  27327. data: getTypedArray( image.type, image.data ),
  27328. width: image.width,
  27329. height: image.height
  27330. };
  27331. } else {
  27332. return null;
  27333. }
  27334. }
  27335. }
  27336. if ( json !== undefined && json.length > 0 ) {
  27337. loader = new ImageLoader( this.manager );
  27338. loader.setCrossOrigin( this.crossOrigin );
  27339. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27340. const image = json[ i ];
  27341. const url = image.url;
  27342. if ( Array.isArray( url ) ) {
  27343. // load array of images e.g CubeTexture
  27344. const imageArray = [];
  27345. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27346. const currentUrl = url[ j ];
  27347. const deserializedImage = await deserializeImage( currentUrl );
  27348. if ( deserializedImage !== null ) {
  27349. if ( deserializedImage instanceof HTMLImageElement ) {
  27350. imageArray.push( deserializedImage );
  27351. } else {
  27352. // special case: handle array of data textures for cube textures
  27353. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27354. }
  27355. }
  27356. }
  27357. images[ image.uuid ] = new Source( imageArray );
  27358. } else {
  27359. // load single image
  27360. const deserializedImage = await deserializeImage( image.url );
  27361. images[ image.uuid ] = new Source( deserializedImage );
  27362. }
  27363. }
  27364. }
  27365. return images;
  27366. }
  27367. parseTextures( json, images ) {
  27368. function parseConstant( value, type ) {
  27369. if ( typeof value === 'number' ) return value;
  27370. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27371. return type[ value ];
  27372. }
  27373. const textures = {};
  27374. if ( json !== undefined ) {
  27375. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27376. const data = json[ i ];
  27377. if ( data.image === undefined ) {
  27378. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27379. }
  27380. if ( images[ data.image ] === undefined ) {
  27381. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27382. }
  27383. const source = images[ data.image ];
  27384. const image = source.data;
  27385. let texture;
  27386. if ( Array.isArray( image ) ) {
  27387. texture = new CubeTexture();
  27388. if ( image.length === 6 ) texture.needsUpdate = true;
  27389. } else {
  27390. if ( image && image.data ) {
  27391. texture = new DataTexture();
  27392. } else {
  27393. texture = new Texture();
  27394. }
  27395. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27396. }
  27397. texture.source = source;
  27398. texture.uuid = data.uuid;
  27399. if ( data.name !== undefined ) texture.name = data.name;
  27400. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27401. if ( data.channel !== undefined ) texture.channel = data.channel;
  27402. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27403. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27404. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27405. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27406. if ( data.wrap !== undefined ) {
  27407. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27408. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27409. }
  27410. if ( data.format !== undefined ) texture.format = data.format;
  27411. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27412. if ( data.type !== undefined ) texture.type = data.type;
  27413. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27414. if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152
  27415. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27416. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27417. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27418. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27419. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27420. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27421. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27422. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27423. if ( data.userData !== undefined ) texture.userData = data.userData;
  27424. textures[ data.uuid ] = texture;
  27425. }
  27426. }
  27427. return textures;
  27428. }
  27429. parseObject( data, geometries, materials, textures, animations ) {
  27430. let object;
  27431. function getGeometry( name ) {
  27432. if ( geometries[ name ] === undefined ) {
  27433. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27434. }
  27435. return geometries[ name ];
  27436. }
  27437. function getMaterial( name ) {
  27438. if ( name === undefined ) return undefined;
  27439. if ( Array.isArray( name ) ) {
  27440. const array = [];
  27441. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27442. const uuid = name[ i ];
  27443. if ( materials[ uuid ] === undefined ) {
  27444. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27445. }
  27446. array.push( materials[ uuid ] );
  27447. }
  27448. return array;
  27449. }
  27450. if ( materials[ name ] === undefined ) {
  27451. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27452. }
  27453. return materials[ name ];
  27454. }
  27455. function getTexture( uuid ) {
  27456. if ( textures[ uuid ] === undefined ) {
  27457. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27458. }
  27459. return textures[ uuid ];
  27460. }
  27461. let geometry, material;
  27462. switch ( data.type ) {
  27463. case 'Scene':
  27464. object = new Scene();
  27465. if ( data.background !== undefined ) {
  27466. if ( Number.isInteger( data.background ) ) {
  27467. object.background = new Color( data.background );
  27468. } else {
  27469. object.background = getTexture( data.background );
  27470. }
  27471. }
  27472. if ( data.environment !== undefined ) {
  27473. object.environment = getTexture( data.environment );
  27474. }
  27475. if ( data.fog !== undefined ) {
  27476. if ( data.fog.type === 'Fog' ) {
  27477. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27478. } else if ( data.fog.type === 'FogExp2' ) {
  27479. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27480. }
  27481. if ( data.fog.name !== '' ) {
  27482. object.fog.name = data.fog.name;
  27483. }
  27484. }
  27485. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27486. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27487. break;
  27488. case 'PerspectiveCamera':
  27489. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27490. if ( data.focus !== undefined ) object.focus = data.focus;
  27491. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27492. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27493. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27494. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27495. break;
  27496. case 'OrthographicCamera':
  27497. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27498. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27499. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27500. break;
  27501. case 'AmbientLight':
  27502. object = new AmbientLight( data.color, data.intensity );
  27503. break;
  27504. case 'DirectionalLight':
  27505. object = new DirectionalLight( data.color, data.intensity );
  27506. break;
  27507. case 'PointLight':
  27508. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27509. break;
  27510. case 'RectAreaLight':
  27511. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27512. break;
  27513. case 'SpotLight':
  27514. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27515. break;
  27516. case 'HemisphereLight':
  27517. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27518. break;
  27519. case 'LightProbe':
  27520. object = new LightProbe().fromJSON( data );
  27521. break;
  27522. case 'SkinnedMesh':
  27523. geometry = getGeometry( data.geometry );
  27524. material = getMaterial( data.material );
  27525. object = new SkinnedMesh( geometry, material );
  27526. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27527. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27528. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27529. break;
  27530. case 'Mesh':
  27531. geometry = getGeometry( data.geometry );
  27532. material = getMaterial( data.material );
  27533. object = new Mesh( geometry, material );
  27534. break;
  27535. case 'InstancedMesh':
  27536. geometry = getGeometry( data.geometry );
  27537. material = getMaterial( data.material );
  27538. const count = data.count;
  27539. const instanceMatrix = data.instanceMatrix;
  27540. const instanceColor = data.instanceColor;
  27541. object = new InstancedMesh( geometry, material, count );
  27542. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27543. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27544. break;
  27545. case 'BatchedMesh':
  27546. geometry = getGeometry( data.geometry );
  27547. material = getMaterial( data.material );
  27548. object = new BatchedMesh( data.maxGeometryCount, data.maxVertexCount, data.maxIndexCount, material );
  27549. object.geometry = geometry;
  27550. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  27551. object.sortObjects = data.sortObjects;
  27552. object._drawRanges = data.drawRanges;
  27553. object._reservedRanges = data.reservedRanges;
  27554. object._visibility = data.visibility;
  27555. object._active = data.active;
  27556. object._bounds = data.bounds.map( bound => {
  27557. const box = new Box3();
  27558. box.min.fromArray( bound.boxMin );
  27559. box.max.fromArray( bound.boxMax );
  27560. const sphere = new Sphere();
  27561. sphere.radius = bound.sphereRadius;
  27562. sphere.center.fromArray( bound.sphereCenter );
  27563. return {
  27564. boxInitialized: bound.boxInitialized,
  27565. box: box,
  27566. sphereInitialized: bound.sphereInitialized,
  27567. sphere: sphere
  27568. };
  27569. } );
  27570. object._maxGeometryCount = data.maxGeometryCount;
  27571. object._maxVertexCount = data.maxVertexCount;
  27572. object._maxIndexCount = data.maxIndexCount;
  27573. object._geometryInitialized = data.geometryInitialized;
  27574. object._geometryCount = data.geometryCount;
  27575. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  27576. break;
  27577. case 'LOD':
  27578. object = new LOD();
  27579. break;
  27580. case 'Line':
  27581. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  27582. break;
  27583. case 'LineLoop':
  27584. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27585. break;
  27586. case 'LineSegments':
  27587. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27588. break;
  27589. case 'PointCloud':
  27590. case 'Points':
  27591. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27592. break;
  27593. case 'Sprite':
  27594. object = new Sprite( getMaterial( data.material ) );
  27595. break;
  27596. case 'Group':
  27597. object = new Group();
  27598. break;
  27599. case 'Bone':
  27600. object = new Bone();
  27601. break;
  27602. default:
  27603. object = new Object3D();
  27604. }
  27605. object.uuid = data.uuid;
  27606. if ( data.name !== undefined ) object.name = data.name;
  27607. if ( data.matrix !== undefined ) {
  27608. object.matrix.fromArray( data.matrix );
  27609. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27610. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27611. } else {
  27612. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27613. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27614. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27615. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27616. }
  27617. if ( data.up !== undefined ) object.up.fromArray( data.up );
  27618. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27619. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27620. if ( data.shadow ) {
  27621. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27622. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  27623. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27624. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27625. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27626. }
  27627. if ( data.visible !== undefined ) object.visible = data.visible;
  27628. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27629. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27630. if ( data.userData !== undefined ) object.userData = data.userData;
  27631. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27632. if ( data.children !== undefined ) {
  27633. const children = data.children;
  27634. for ( let i = 0; i < children.length; i ++ ) {
  27635. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  27636. }
  27637. }
  27638. if ( data.animations !== undefined ) {
  27639. const objectAnimations = data.animations;
  27640. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  27641. const uuid = objectAnimations[ i ];
  27642. object.animations.push( animations[ uuid ] );
  27643. }
  27644. }
  27645. if ( data.type === 'LOD' ) {
  27646. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  27647. const levels = data.levels;
  27648. for ( let l = 0; l < levels.length; l ++ ) {
  27649. const level = levels[ l ];
  27650. const child = object.getObjectByProperty( 'uuid', level.object );
  27651. if ( child !== undefined ) {
  27652. object.addLevel( child, level.distance, level.hysteresis );
  27653. }
  27654. }
  27655. }
  27656. return object;
  27657. }
  27658. bindSkeletons( object, skeletons ) {
  27659. if ( Object.keys( skeletons ).length === 0 ) return;
  27660. object.traverse( function ( child ) {
  27661. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  27662. const skeleton = skeletons[ child.skeleton ];
  27663. if ( skeleton === undefined ) {
  27664. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  27665. } else {
  27666. child.bind( skeleton, child.bindMatrix );
  27667. }
  27668. }
  27669. } );
  27670. }
  27671. }
  27672. const TEXTURE_MAPPING = {
  27673. UVMapping: UVMapping,
  27674. CubeReflectionMapping: CubeReflectionMapping,
  27675. CubeRefractionMapping: CubeRefractionMapping,
  27676. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27677. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27678. CubeUVReflectionMapping: CubeUVReflectionMapping
  27679. };
  27680. const TEXTURE_WRAPPING = {
  27681. RepeatWrapping: RepeatWrapping,
  27682. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27683. MirroredRepeatWrapping: MirroredRepeatWrapping
  27684. };
  27685. const TEXTURE_FILTER = {
  27686. NearestFilter: NearestFilter,
  27687. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  27688. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  27689. LinearFilter: LinearFilter,
  27690. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  27691. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  27692. };
  27693. class ImageBitmapLoader extends Loader {
  27694. constructor( manager ) {
  27695. super( manager );
  27696. this.isImageBitmapLoader = true;
  27697. if ( typeof createImageBitmap === 'undefined' ) {
  27698. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27699. }
  27700. if ( typeof fetch === 'undefined' ) {
  27701. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27702. }
  27703. this.options = { premultiplyAlpha: 'none' };
  27704. }
  27705. setOptions( options ) {
  27706. this.options = options;
  27707. return this;
  27708. }
  27709. load( url, onLoad, onProgress, onError ) {
  27710. if ( url === undefined ) url = '';
  27711. if ( this.path !== undefined ) url = this.path + url;
  27712. url = this.manager.resolveURL( url );
  27713. const scope = this;
  27714. const cached = Cache.get( url );
  27715. if ( cached !== undefined ) {
  27716. scope.manager.itemStart( url );
  27717. // If cached is a promise, wait for it to resolve
  27718. if ( cached.then ) {
  27719. cached.then( imageBitmap => {
  27720. if ( onLoad ) onLoad( imageBitmap );
  27721. scope.manager.itemEnd( url );
  27722. } ).catch( e => {
  27723. if ( onError ) onError( e );
  27724. } );
  27725. return;
  27726. }
  27727. // If cached is not a promise (i.e., it's already an imageBitmap)
  27728. setTimeout( function () {
  27729. if ( onLoad ) onLoad( cached );
  27730. scope.manager.itemEnd( url );
  27731. }, 0 );
  27732. return cached;
  27733. }
  27734. const fetchOptions = {};
  27735. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  27736. fetchOptions.headers = this.requestHeader;
  27737. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  27738. return res.blob();
  27739. } ).then( function ( blob ) {
  27740. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  27741. } ).then( function ( imageBitmap ) {
  27742. Cache.add( url, imageBitmap );
  27743. if ( onLoad ) onLoad( imageBitmap );
  27744. scope.manager.itemEnd( url );
  27745. return imageBitmap;
  27746. } ).catch( function ( e ) {
  27747. if ( onError ) onError( e );
  27748. Cache.remove( url );
  27749. scope.manager.itemError( url );
  27750. scope.manager.itemEnd( url );
  27751. } );
  27752. Cache.add( url, promise );
  27753. scope.manager.itemStart( url );
  27754. }
  27755. }
  27756. let _context;
  27757. class AudioContext {
  27758. static getContext() {
  27759. if ( _context === undefined ) {
  27760. _context = new ( window.AudioContext || window.webkitAudioContext )();
  27761. }
  27762. return _context;
  27763. }
  27764. static setContext( value ) {
  27765. _context = value;
  27766. }
  27767. }
  27768. class AudioLoader extends Loader {
  27769. constructor( manager ) {
  27770. super( manager );
  27771. }
  27772. load( url, onLoad, onProgress, onError ) {
  27773. const scope = this;
  27774. const loader = new FileLoader( this.manager );
  27775. loader.setResponseType( 'arraybuffer' );
  27776. loader.setPath( this.path );
  27777. loader.setRequestHeader( this.requestHeader );
  27778. loader.setWithCredentials( this.withCredentials );
  27779. loader.load( url, function ( buffer ) {
  27780. try {
  27781. // Create a copy of the buffer. The `decodeAudioData` method
  27782. // detaches the buffer when complete, preventing reuse.
  27783. const bufferCopy = buffer.slice( 0 );
  27784. const context = AudioContext.getContext();
  27785. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27786. onLoad( audioBuffer );
  27787. } ).catch( handleError );
  27788. } catch ( e ) {
  27789. handleError( e );
  27790. }
  27791. }, onProgress, onError );
  27792. function handleError( e ) {
  27793. if ( onError ) {
  27794. onError( e );
  27795. } else {
  27796. console.error( e );
  27797. }
  27798. scope.manager.itemError( url );
  27799. }
  27800. }
  27801. }
  27802. const _eyeRight = /*@__PURE__*/ new Matrix4();
  27803. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  27804. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  27805. class StereoCamera {
  27806. constructor() {
  27807. this.type = 'StereoCamera';
  27808. this.aspect = 1;
  27809. this.eyeSep = 0.064;
  27810. this.cameraL = new PerspectiveCamera();
  27811. this.cameraL.layers.enable( 1 );
  27812. this.cameraL.matrixAutoUpdate = false;
  27813. this.cameraR = new PerspectiveCamera();
  27814. this.cameraR.layers.enable( 2 );
  27815. this.cameraR.matrixAutoUpdate = false;
  27816. this._cache = {
  27817. focus: null,
  27818. fov: null,
  27819. aspect: null,
  27820. near: null,
  27821. far: null,
  27822. zoom: null,
  27823. eyeSep: null
  27824. };
  27825. }
  27826. update( camera ) {
  27827. const cache = this._cache;
  27828. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  27829. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  27830. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  27831. if ( needsUpdate ) {
  27832. cache.focus = camera.focus;
  27833. cache.fov = camera.fov;
  27834. cache.aspect = camera.aspect * this.aspect;
  27835. cache.near = camera.near;
  27836. cache.far = camera.far;
  27837. cache.zoom = camera.zoom;
  27838. cache.eyeSep = this.eyeSep;
  27839. // Off-axis stereoscopic effect based on
  27840. // http://paulbourke.net/stereographics/stereorender/
  27841. _projectionMatrix.copy( camera.projectionMatrix );
  27842. const eyeSepHalf = cache.eyeSep / 2;
  27843. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  27844. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  27845. let xmin, xmax;
  27846. // translate xOffset
  27847. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  27848. _eyeRight.elements[ 12 ] = eyeSepHalf;
  27849. // for left eye
  27850. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  27851. xmax = ymax * cache.aspect + eyeSepOnProjection;
  27852. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27853. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27854. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  27855. // for right eye
  27856. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  27857. xmax = ymax * cache.aspect - eyeSepOnProjection;
  27858. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27859. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27860. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  27861. }
  27862. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  27863. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  27864. }
  27865. }
  27866. class Clock {
  27867. constructor( autoStart = true ) {
  27868. this.autoStart = autoStart;
  27869. this.startTime = 0;
  27870. this.oldTime = 0;
  27871. this.elapsedTime = 0;
  27872. this.running = false;
  27873. }
  27874. start() {
  27875. this.startTime = now();
  27876. this.oldTime = this.startTime;
  27877. this.elapsedTime = 0;
  27878. this.running = true;
  27879. }
  27880. stop() {
  27881. this.getElapsedTime();
  27882. this.running = false;
  27883. this.autoStart = false;
  27884. }
  27885. getElapsedTime() {
  27886. this.getDelta();
  27887. return this.elapsedTime;
  27888. }
  27889. getDelta() {
  27890. let diff = 0;
  27891. if ( this.autoStart && ! this.running ) {
  27892. this.start();
  27893. return 0;
  27894. }
  27895. if ( this.running ) {
  27896. const newTime = now();
  27897. diff = ( newTime - this.oldTime ) / 1000;
  27898. this.oldTime = newTime;
  27899. this.elapsedTime += diff;
  27900. }
  27901. return diff;
  27902. }
  27903. }
  27904. function now() {
  27905. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  27906. }
  27907. const _position$1 = /*@__PURE__*/ new Vector3();
  27908. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  27909. const _scale$1 = /*@__PURE__*/ new Vector3();
  27910. const _orientation$1 = /*@__PURE__*/ new Vector3();
  27911. class AudioListener extends Object3D {
  27912. constructor() {
  27913. super();
  27914. this.type = 'AudioListener';
  27915. this.context = AudioContext.getContext();
  27916. this.gain = this.context.createGain();
  27917. this.gain.connect( this.context.destination );
  27918. this.filter = null;
  27919. this.timeDelta = 0;
  27920. // private
  27921. this._clock = new Clock();
  27922. }
  27923. getInput() {
  27924. return this.gain;
  27925. }
  27926. removeFilter() {
  27927. if ( this.filter !== null ) {
  27928. this.gain.disconnect( this.filter );
  27929. this.filter.disconnect( this.context.destination );
  27930. this.gain.connect( this.context.destination );
  27931. this.filter = null;
  27932. }
  27933. return this;
  27934. }
  27935. getFilter() {
  27936. return this.filter;
  27937. }
  27938. setFilter( value ) {
  27939. if ( this.filter !== null ) {
  27940. this.gain.disconnect( this.filter );
  27941. this.filter.disconnect( this.context.destination );
  27942. } else {
  27943. this.gain.disconnect( this.context.destination );
  27944. }
  27945. this.filter = value;
  27946. this.gain.connect( this.filter );
  27947. this.filter.connect( this.context.destination );
  27948. return this;
  27949. }
  27950. getMasterVolume() {
  27951. return this.gain.gain.value;
  27952. }
  27953. setMasterVolume( value ) {
  27954. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27955. return this;
  27956. }
  27957. updateMatrixWorld( force ) {
  27958. super.updateMatrixWorld( force );
  27959. const listener = this.context.listener;
  27960. const up = this.up;
  27961. this.timeDelta = this._clock.getDelta();
  27962. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  27963. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  27964. if ( listener.positionX ) {
  27965. // code path for Chrome (see #14393)
  27966. const endTime = this.context.currentTime + this.timeDelta;
  27967. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  27968. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  27969. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  27970. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  27971. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  27972. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  27973. listener.upX.linearRampToValueAtTime( up.x, endTime );
  27974. listener.upY.linearRampToValueAtTime( up.y, endTime );
  27975. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  27976. } else {
  27977. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  27978. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  27979. }
  27980. }
  27981. }
  27982. class Audio extends Object3D {
  27983. constructor( listener ) {
  27984. super();
  27985. this.type = 'Audio';
  27986. this.listener = listener;
  27987. this.context = listener.context;
  27988. this.gain = this.context.createGain();
  27989. this.gain.connect( listener.getInput() );
  27990. this.autoplay = false;
  27991. this.buffer = null;
  27992. this.detune = 0;
  27993. this.loop = false;
  27994. this.loopStart = 0;
  27995. this.loopEnd = 0;
  27996. this.offset = 0;
  27997. this.duration = undefined;
  27998. this.playbackRate = 1;
  27999. this.isPlaying = false;
  28000. this.hasPlaybackControl = true;
  28001. this.source = null;
  28002. this.sourceType = 'empty';
  28003. this._startedAt = 0;
  28004. this._progress = 0;
  28005. this._connected = false;
  28006. this.filters = [];
  28007. }
  28008. getOutput() {
  28009. return this.gain;
  28010. }
  28011. setNodeSource( audioNode ) {
  28012. this.hasPlaybackControl = false;
  28013. this.sourceType = 'audioNode';
  28014. this.source = audioNode;
  28015. this.connect();
  28016. return this;
  28017. }
  28018. setMediaElementSource( mediaElement ) {
  28019. this.hasPlaybackControl = false;
  28020. this.sourceType = 'mediaNode';
  28021. this.source = this.context.createMediaElementSource( mediaElement );
  28022. this.connect();
  28023. return this;
  28024. }
  28025. setMediaStreamSource( mediaStream ) {
  28026. this.hasPlaybackControl = false;
  28027. this.sourceType = 'mediaStreamNode';
  28028. this.source = this.context.createMediaStreamSource( mediaStream );
  28029. this.connect();
  28030. return this;
  28031. }
  28032. setBuffer( audioBuffer ) {
  28033. this.buffer = audioBuffer;
  28034. this.sourceType = 'buffer';
  28035. if ( this.autoplay ) this.play();
  28036. return this;
  28037. }
  28038. play( delay = 0 ) {
  28039. if ( this.isPlaying === true ) {
  28040. console.warn( 'THREE.Audio: Audio is already playing.' );
  28041. return;
  28042. }
  28043. if ( this.hasPlaybackControl === false ) {
  28044. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28045. return;
  28046. }
  28047. this._startedAt = this.context.currentTime + delay;
  28048. const source = this.context.createBufferSource();
  28049. source.buffer = this.buffer;
  28050. source.loop = this.loop;
  28051. source.loopStart = this.loopStart;
  28052. source.loopEnd = this.loopEnd;
  28053. source.onended = this.onEnded.bind( this );
  28054. source.start( this._startedAt, this._progress + this.offset, this.duration );
  28055. this.isPlaying = true;
  28056. this.source = source;
  28057. this.setDetune( this.detune );
  28058. this.setPlaybackRate( this.playbackRate );
  28059. return this.connect();
  28060. }
  28061. pause() {
  28062. if ( this.hasPlaybackControl === false ) {
  28063. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28064. return;
  28065. }
  28066. if ( this.isPlaying === true ) {
  28067. // update current progress
  28068. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  28069. if ( this.loop === true ) {
  28070. // ensure _progress does not exceed duration with looped audios
  28071. this._progress = this._progress % ( this.duration || this.buffer.duration );
  28072. }
  28073. this.source.stop();
  28074. this.source.onended = null;
  28075. this.isPlaying = false;
  28076. }
  28077. return this;
  28078. }
  28079. stop() {
  28080. if ( this.hasPlaybackControl === false ) {
  28081. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28082. return;
  28083. }
  28084. this._progress = 0;
  28085. if ( this.source !== null ) {
  28086. this.source.stop();
  28087. this.source.onended = null;
  28088. }
  28089. this.isPlaying = false;
  28090. return this;
  28091. }
  28092. connect() {
  28093. if ( this.filters.length > 0 ) {
  28094. this.source.connect( this.filters[ 0 ] );
  28095. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28096. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28097. }
  28098. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28099. } else {
  28100. this.source.connect( this.getOutput() );
  28101. }
  28102. this._connected = true;
  28103. return this;
  28104. }
  28105. disconnect() {
  28106. if ( this._connected === false ) {
  28107. return;
  28108. }
  28109. if ( this.filters.length > 0 ) {
  28110. this.source.disconnect( this.filters[ 0 ] );
  28111. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28112. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28113. }
  28114. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28115. } else {
  28116. this.source.disconnect( this.getOutput() );
  28117. }
  28118. this._connected = false;
  28119. return this;
  28120. }
  28121. getFilters() {
  28122. return this.filters;
  28123. }
  28124. setFilters( value ) {
  28125. if ( ! value ) value = [];
  28126. if ( this._connected === true ) {
  28127. this.disconnect();
  28128. this.filters = value.slice();
  28129. this.connect();
  28130. } else {
  28131. this.filters = value.slice();
  28132. }
  28133. return this;
  28134. }
  28135. setDetune( value ) {
  28136. this.detune = value;
  28137. if ( this.source.detune === undefined ) return; // only set detune when available
  28138. if ( this.isPlaying === true ) {
  28139. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28140. }
  28141. return this;
  28142. }
  28143. getDetune() {
  28144. return this.detune;
  28145. }
  28146. getFilter() {
  28147. return this.getFilters()[ 0 ];
  28148. }
  28149. setFilter( filter ) {
  28150. return this.setFilters( filter ? [ filter ] : [] );
  28151. }
  28152. setPlaybackRate( value ) {
  28153. if ( this.hasPlaybackControl === false ) {
  28154. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28155. return;
  28156. }
  28157. this.playbackRate = value;
  28158. if ( this.isPlaying === true ) {
  28159. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28160. }
  28161. return this;
  28162. }
  28163. getPlaybackRate() {
  28164. return this.playbackRate;
  28165. }
  28166. onEnded() {
  28167. this.isPlaying = false;
  28168. }
  28169. getLoop() {
  28170. if ( this.hasPlaybackControl === false ) {
  28171. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28172. return false;
  28173. }
  28174. return this.loop;
  28175. }
  28176. setLoop( value ) {
  28177. if ( this.hasPlaybackControl === false ) {
  28178. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28179. return;
  28180. }
  28181. this.loop = value;
  28182. if ( this.isPlaying === true ) {
  28183. this.source.loop = this.loop;
  28184. }
  28185. return this;
  28186. }
  28187. setLoopStart( value ) {
  28188. this.loopStart = value;
  28189. return this;
  28190. }
  28191. setLoopEnd( value ) {
  28192. this.loopEnd = value;
  28193. return this;
  28194. }
  28195. getVolume() {
  28196. return this.gain.gain.value;
  28197. }
  28198. setVolume( value ) {
  28199. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28200. return this;
  28201. }
  28202. }
  28203. const _position = /*@__PURE__*/ new Vector3();
  28204. const _quaternion = /*@__PURE__*/ new Quaternion();
  28205. const _scale = /*@__PURE__*/ new Vector3();
  28206. const _orientation = /*@__PURE__*/ new Vector3();
  28207. class PositionalAudio extends Audio {
  28208. constructor( listener ) {
  28209. super( listener );
  28210. this.panner = this.context.createPanner();
  28211. this.panner.panningModel = 'HRTF';
  28212. this.panner.connect( this.gain );
  28213. }
  28214. connect() {
  28215. super.connect();
  28216. this.panner.connect( this.gain );
  28217. }
  28218. disconnect() {
  28219. super.disconnect();
  28220. this.panner.disconnect( this.gain );
  28221. }
  28222. getOutput() {
  28223. return this.panner;
  28224. }
  28225. getRefDistance() {
  28226. return this.panner.refDistance;
  28227. }
  28228. setRefDistance( value ) {
  28229. this.panner.refDistance = value;
  28230. return this;
  28231. }
  28232. getRolloffFactor() {
  28233. return this.panner.rolloffFactor;
  28234. }
  28235. setRolloffFactor( value ) {
  28236. this.panner.rolloffFactor = value;
  28237. return this;
  28238. }
  28239. getDistanceModel() {
  28240. return this.panner.distanceModel;
  28241. }
  28242. setDistanceModel( value ) {
  28243. this.panner.distanceModel = value;
  28244. return this;
  28245. }
  28246. getMaxDistance() {
  28247. return this.panner.maxDistance;
  28248. }
  28249. setMaxDistance( value ) {
  28250. this.panner.maxDistance = value;
  28251. return this;
  28252. }
  28253. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28254. this.panner.coneInnerAngle = coneInnerAngle;
  28255. this.panner.coneOuterAngle = coneOuterAngle;
  28256. this.panner.coneOuterGain = coneOuterGain;
  28257. return this;
  28258. }
  28259. updateMatrixWorld( force ) {
  28260. super.updateMatrixWorld( force );
  28261. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28262. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28263. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28264. const panner = this.panner;
  28265. if ( panner.positionX ) {
  28266. // code path for Chrome and Firefox (see #14393)
  28267. const endTime = this.context.currentTime + this.listener.timeDelta;
  28268. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28269. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28270. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28271. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28272. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28273. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28274. } else {
  28275. panner.setPosition( _position.x, _position.y, _position.z );
  28276. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28277. }
  28278. }
  28279. }
  28280. class AudioAnalyser {
  28281. constructor( audio, fftSize = 2048 ) {
  28282. this.analyser = audio.context.createAnalyser();
  28283. this.analyser.fftSize = fftSize;
  28284. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28285. audio.getOutput().connect( this.analyser );
  28286. }
  28287. getFrequencyData() {
  28288. this.analyser.getByteFrequencyData( this.data );
  28289. return this.data;
  28290. }
  28291. getAverageFrequency() {
  28292. let value = 0;
  28293. const data = this.getFrequencyData();
  28294. for ( let i = 0; i < data.length; i ++ ) {
  28295. value += data[ i ];
  28296. }
  28297. return value / data.length;
  28298. }
  28299. }
  28300. class PropertyMixer {
  28301. constructor( binding, typeName, valueSize ) {
  28302. this.binding = binding;
  28303. this.valueSize = valueSize;
  28304. let mixFunction,
  28305. mixFunctionAdditive,
  28306. setIdentity;
  28307. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28308. //
  28309. // interpolators can use .buffer as their .result
  28310. // the data then goes to 'incoming'
  28311. //
  28312. // 'accu0' and 'accu1' are used frame-interleaved for
  28313. // the cumulative result and are compared to detect
  28314. // changes
  28315. //
  28316. // 'orig' stores the original state of the property
  28317. //
  28318. // 'add' is used for additive cumulative results
  28319. //
  28320. // 'work' is optional and is only present for quaternion types. It is used
  28321. // to store intermediate quaternion multiplication results
  28322. switch ( typeName ) {
  28323. case 'quaternion':
  28324. mixFunction = this._slerp;
  28325. mixFunctionAdditive = this._slerpAdditive;
  28326. setIdentity = this._setAdditiveIdentityQuaternion;
  28327. this.buffer = new Float64Array( valueSize * 6 );
  28328. this._workIndex = 5;
  28329. break;
  28330. case 'string':
  28331. case 'bool':
  28332. mixFunction = this._select;
  28333. // Use the regular mix function and for additive on these types,
  28334. // additive is not relevant for non-numeric types
  28335. mixFunctionAdditive = this._select;
  28336. setIdentity = this._setAdditiveIdentityOther;
  28337. this.buffer = new Array( valueSize * 5 );
  28338. break;
  28339. default:
  28340. mixFunction = this._lerp;
  28341. mixFunctionAdditive = this._lerpAdditive;
  28342. setIdentity = this._setAdditiveIdentityNumeric;
  28343. this.buffer = new Float64Array( valueSize * 5 );
  28344. }
  28345. this._mixBufferRegion = mixFunction;
  28346. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28347. this._setIdentity = setIdentity;
  28348. this._origIndex = 3;
  28349. this._addIndex = 4;
  28350. this.cumulativeWeight = 0;
  28351. this.cumulativeWeightAdditive = 0;
  28352. this.useCount = 0;
  28353. this.referenceCount = 0;
  28354. }
  28355. // accumulate data in the 'incoming' region into 'accu<i>'
  28356. accumulate( accuIndex, weight ) {
  28357. // note: happily accumulating nothing when weight = 0, the caller knows
  28358. // the weight and shouldn't have made the call in the first place
  28359. const buffer = this.buffer,
  28360. stride = this.valueSize,
  28361. offset = accuIndex * stride + stride;
  28362. let currentWeight = this.cumulativeWeight;
  28363. if ( currentWeight === 0 ) {
  28364. // accuN := incoming * weight
  28365. for ( let i = 0; i !== stride; ++ i ) {
  28366. buffer[ offset + i ] = buffer[ i ];
  28367. }
  28368. currentWeight = weight;
  28369. } else {
  28370. // accuN := accuN + incoming * weight
  28371. currentWeight += weight;
  28372. const mix = weight / currentWeight;
  28373. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28374. }
  28375. this.cumulativeWeight = currentWeight;
  28376. }
  28377. // accumulate data in the 'incoming' region into 'add'
  28378. accumulateAdditive( weight ) {
  28379. const buffer = this.buffer,
  28380. stride = this.valueSize,
  28381. offset = stride * this._addIndex;
  28382. if ( this.cumulativeWeightAdditive === 0 ) {
  28383. // add = identity
  28384. this._setIdentity();
  28385. }
  28386. // add := add + incoming * weight
  28387. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28388. this.cumulativeWeightAdditive += weight;
  28389. }
  28390. // apply the state of 'accu<i>' to the binding when accus differ
  28391. apply( accuIndex ) {
  28392. const stride = this.valueSize,
  28393. buffer = this.buffer,
  28394. offset = accuIndex * stride + stride,
  28395. weight = this.cumulativeWeight,
  28396. weightAdditive = this.cumulativeWeightAdditive,
  28397. binding = this.binding;
  28398. this.cumulativeWeight = 0;
  28399. this.cumulativeWeightAdditive = 0;
  28400. if ( weight < 1 ) {
  28401. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28402. const originalValueOffset = stride * this._origIndex;
  28403. this._mixBufferRegion(
  28404. buffer, offset, originalValueOffset, 1 - weight, stride );
  28405. }
  28406. if ( weightAdditive > 0 ) {
  28407. // accuN := accuN + additive accuN
  28408. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28409. }
  28410. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28411. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28412. // value has changed -> update scene graph
  28413. binding.setValue( buffer, offset );
  28414. break;
  28415. }
  28416. }
  28417. }
  28418. // remember the state of the bound property and copy it to both accus
  28419. saveOriginalState() {
  28420. const binding = this.binding;
  28421. const buffer = this.buffer,
  28422. stride = this.valueSize,
  28423. originalValueOffset = stride * this._origIndex;
  28424. binding.getValue( buffer, originalValueOffset );
  28425. // accu[0..1] := orig -- initially detect changes against the original
  28426. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28427. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28428. }
  28429. // Add to identity for additive
  28430. this._setIdentity();
  28431. this.cumulativeWeight = 0;
  28432. this.cumulativeWeightAdditive = 0;
  28433. }
  28434. // apply the state previously taken via 'saveOriginalState' to the binding
  28435. restoreOriginalState() {
  28436. const originalValueOffset = this.valueSize * 3;
  28437. this.binding.setValue( this.buffer, originalValueOffset );
  28438. }
  28439. _setAdditiveIdentityNumeric() {
  28440. const startIndex = this._addIndex * this.valueSize;
  28441. const endIndex = startIndex + this.valueSize;
  28442. for ( let i = startIndex; i < endIndex; i ++ ) {
  28443. this.buffer[ i ] = 0;
  28444. }
  28445. }
  28446. _setAdditiveIdentityQuaternion() {
  28447. this._setAdditiveIdentityNumeric();
  28448. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  28449. }
  28450. _setAdditiveIdentityOther() {
  28451. const startIndex = this._origIndex * this.valueSize;
  28452. const targetIndex = this._addIndex * this.valueSize;
  28453. for ( let i = 0; i < this.valueSize; i ++ ) {
  28454. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  28455. }
  28456. }
  28457. // mix functions
  28458. _select( buffer, dstOffset, srcOffset, t, stride ) {
  28459. if ( t >= 0.5 ) {
  28460. for ( let i = 0; i !== stride; ++ i ) {
  28461. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  28462. }
  28463. }
  28464. }
  28465. _slerp( buffer, dstOffset, srcOffset, t ) {
  28466. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  28467. }
  28468. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28469. const workOffset = this._workIndex * stride;
  28470. // Store result in intermediate buffer offset
  28471. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  28472. // Slerp to the intermediate result
  28473. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  28474. }
  28475. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  28476. const s = 1 - t;
  28477. for ( let i = 0; i !== stride; ++ i ) {
  28478. const j = dstOffset + i;
  28479. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  28480. }
  28481. }
  28482. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28483. for ( let i = 0; i !== stride; ++ i ) {
  28484. const j = dstOffset + i;
  28485. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  28486. }
  28487. }
  28488. }
  28489. // Characters [].:/ are reserved for track binding syntax.
  28490. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  28491. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  28492. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  28493. // only latin characters, and the unicode \p{L} is not yet supported. So
  28494. // instead, we exclude reserved characters and match everything else.
  28495. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  28496. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28497. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28498. // be matched to parse the rest of the track name.
  28499. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  28500. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28501. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  28502. // Object on target node, and accessor. May not contain reserved
  28503. // characters. Accessor may contain any character except closing bracket.
  28504. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  28505. // Property and accessor. May not contain reserved characters. Accessor may
  28506. // contain any non-bracket characters.
  28507. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  28508. const _trackRe = new RegExp( ''
  28509. + '^'
  28510. + _directoryRe
  28511. + _nodeRe
  28512. + _objectRe
  28513. + _propertyRe
  28514. + '$'
  28515. );
  28516. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  28517. class Composite {
  28518. constructor( targetGroup, path, optionalParsedPath ) {
  28519. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  28520. this._targetGroup = targetGroup;
  28521. this._bindings = targetGroup.subscribe_( path, parsedPath );
  28522. }
  28523. getValue( array, offset ) {
  28524. this.bind(); // bind all binding
  28525. const firstValidIndex = this._targetGroup.nCachedObjects_,
  28526. binding = this._bindings[ firstValidIndex ];
  28527. // and only call .getValue on the first
  28528. if ( binding !== undefined ) binding.getValue( array, offset );
  28529. }
  28530. setValue( array, offset ) {
  28531. const bindings = this._bindings;
  28532. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28533. bindings[ i ].setValue( array, offset );
  28534. }
  28535. }
  28536. bind() {
  28537. const bindings = this._bindings;
  28538. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28539. bindings[ i ].bind();
  28540. }
  28541. }
  28542. unbind() {
  28543. const bindings = this._bindings;
  28544. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28545. bindings[ i ].unbind();
  28546. }
  28547. }
  28548. }
  28549. // Note: This class uses a State pattern on a per-method basis:
  28550. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28551. // prototype version of these methods with one that represents
  28552. // the bound state. When the property is not found, the methods
  28553. // become no-ops.
  28554. class PropertyBinding {
  28555. constructor( rootNode, path, parsedPath ) {
  28556. this.path = path;
  28557. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  28558. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  28559. this.rootNode = rootNode;
  28560. // initial state of these methods that calls 'bind'
  28561. this.getValue = this._getValue_unbound;
  28562. this.setValue = this._setValue_unbound;
  28563. }
  28564. static create( root, path, parsedPath ) {
  28565. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  28566. return new PropertyBinding( root, path, parsedPath );
  28567. } else {
  28568. return new PropertyBinding.Composite( root, path, parsedPath );
  28569. }
  28570. }
  28571. /**
  28572. * Replaces spaces with underscores and removes unsupported characters from
  28573. * node names, to ensure compatibility with parseTrackName().
  28574. *
  28575. * @param {string} name Node name to be sanitized.
  28576. * @return {string}
  28577. */
  28578. static sanitizeNodeName( name ) {
  28579. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  28580. }
  28581. static parseTrackName( trackName ) {
  28582. const matches = _trackRe.exec( trackName );
  28583. if ( matches === null ) {
  28584. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  28585. }
  28586. const results = {
  28587. // directoryName: matches[ 1 ], // (tschw) currently unused
  28588. nodeName: matches[ 2 ],
  28589. objectName: matches[ 3 ],
  28590. objectIndex: matches[ 4 ],
  28591. propertyName: matches[ 5 ], // required
  28592. propertyIndex: matches[ 6 ]
  28593. };
  28594. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  28595. if ( lastDot !== undefined && lastDot !== - 1 ) {
  28596. const objectName = results.nodeName.substring( lastDot + 1 );
  28597. // Object names must be checked against an allowlist. Otherwise, there
  28598. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  28599. // 'bar' could be the objectName, or part of a nodeName (which can
  28600. // include '.' characters).
  28601. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  28602. results.nodeName = results.nodeName.substring( 0, lastDot );
  28603. results.objectName = objectName;
  28604. }
  28605. }
  28606. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  28607. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  28608. }
  28609. return results;
  28610. }
  28611. static findNode( root, nodeName ) {
  28612. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  28613. return root;
  28614. }
  28615. // search into skeleton bones.
  28616. if ( root.skeleton ) {
  28617. const bone = root.skeleton.getBoneByName( nodeName );
  28618. if ( bone !== undefined ) {
  28619. return bone;
  28620. }
  28621. }
  28622. // search into node subtree.
  28623. if ( root.children ) {
  28624. const searchNodeSubtree = function ( children ) {
  28625. for ( let i = 0; i < children.length; i ++ ) {
  28626. const childNode = children[ i ];
  28627. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  28628. return childNode;
  28629. }
  28630. const result = searchNodeSubtree( childNode.children );
  28631. if ( result ) return result;
  28632. }
  28633. return null;
  28634. };
  28635. const subTreeNode = searchNodeSubtree( root.children );
  28636. if ( subTreeNode ) {
  28637. return subTreeNode;
  28638. }
  28639. }
  28640. return null;
  28641. }
  28642. // these are used to "bind" a nonexistent property
  28643. _getValue_unavailable() {}
  28644. _setValue_unavailable() {}
  28645. // Getters
  28646. _getValue_direct( buffer, offset ) {
  28647. buffer[ offset ] = this.targetObject[ this.propertyName ];
  28648. }
  28649. _getValue_array( buffer, offset ) {
  28650. const source = this.resolvedProperty;
  28651. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  28652. buffer[ offset ++ ] = source[ i ];
  28653. }
  28654. }
  28655. _getValue_arrayElement( buffer, offset ) {
  28656. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  28657. }
  28658. _getValue_toArray( buffer, offset ) {
  28659. this.resolvedProperty.toArray( buffer, offset );
  28660. }
  28661. // Direct
  28662. _setValue_direct( buffer, offset ) {
  28663. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28664. }
  28665. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  28666. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28667. this.targetObject.needsUpdate = true;
  28668. }
  28669. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28670. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28671. this.targetObject.matrixWorldNeedsUpdate = true;
  28672. }
  28673. // EntireArray
  28674. _setValue_array( buffer, offset ) {
  28675. const dest = this.resolvedProperty;
  28676. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28677. dest[ i ] = buffer[ offset ++ ];
  28678. }
  28679. }
  28680. _setValue_array_setNeedsUpdate( buffer, offset ) {
  28681. const dest = this.resolvedProperty;
  28682. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28683. dest[ i ] = buffer[ offset ++ ];
  28684. }
  28685. this.targetObject.needsUpdate = true;
  28686. }
  28687. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28688. const dest = this.resolvedProperty;
  28689. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28690. dest[ i ] = buffer[ offset ++ ];
  28691. }
  28692. this.targetObject.matrixWorldNeedsUpdate = true;
  28693. }
  28694. // ArrayElement
  28695. _setValue_arrayElement( buffer, offset ) {
  28696. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28697. }
  28698. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28699. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28700. this.targetObject.needsUpdate = true;
  28701. }
  28702. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28703. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28704. this.targetObject.matrixWorldNeedsUpdate = true;
  28705. }
  28706. // HasToFromArray
  28707. _setValue_fromArray( buffer, offset ) {
  28708. this.resolvedProperty.fromArray( buffer, offset );
  28709. }
  28710. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28711. this.resolvedProperty.fromArray( buffer, offset );
  28712. this.targetObject.needsUpdate = true;
  28713. }
  28714. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28715. this.resolvedProperty.fromArray( buffer, offset );
  28716. this.targetObject.matrixWorldNeedsUpdate = true;
  28717. }
  28718. _getValue_unbound( targetArray, offset ) {
  28719. this.bind();
  28720. this.getValue( targetArray, offset );
  28721. }
  28722. _setValue_unbound( sourceArray, offset ) {
  28723. this.bind();
  28724. this.setValue( sourceArray, offset );
  28725. }
  28726. // create getter / setter pair for a property in the scene graph
  28727. bind() {
  28728. let targetObject = this.node;
  28729. const parsedPath = this.parsedPath;
  28730. const objectName = parsedPath.objectName;
  28731. const propertyName = parsedPath.propertyName;
  28732. let propertyIndex = parsedPath.propertyIndex;
  28733. if ( ! targetObject ) {
  28734. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  28735. this.node = targetObject;
  28736. }
  28737. // set fail state so we can just 'return' on error
  28738. this.getValue = this._getValue_unavailable;
  28739. this.setValue = this._setValue_unavailable;
  28740. // ensure there is a value node
  28741. if ( ! targetObject ) {
  28742. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  28743. return;
  28744. }
  28745. if ( objectName ) {
  28746. let objectIndex = parsedPath.objectIndex;
  28747. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28748. switch ( objectName ) {
  28749. case 'materials':
  28750. if ( ! targetObject.material ) {
  28751. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28752. return;
  28753. }
  28754. if ( ! targetObject.material.materials ) {
  28755. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28756. return;
  28757. }
  28758. targetObject = targetObject.material.materials;
  28759. break;
  28760. case 'bones':
  28761. if ( ! targetObject.skeleton ) {
  28762. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28763. return;
  28764. }
  28765. // potential future optimization: skip this if propertyIndex is already an integer
  28766. // and convert the integer string to a true integer.
  28767. targetObject = targetObject.skeleton.bones;
  28768. // support resolving morphTarget names into indices.
  28769. for ( let i = 0; i < targetObject.length; i ++ ) {
  28770. if ( targetObject[ i ].name === objectIndex ) {
  28771. objectIndex = i;
  28772. break;
  28773. }
  28774. }
  28775. break;
  28776. case 'map':
  28777. if ( 'map' in targetObject ) {
  28778. targetObject = targetObject.map;
  28779. break;
  28780. }
  28781. if ( ! targetObject.material ) {
  28782. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28783. return;
  28784. }
  28785. if ( ! targetObject.material.map ) {
  28786. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  28787. return;
  28788. }
  28789. targetObject = targetObject.material.map;
  28790. break;
  28791. default:
  28792. if ( targetObject[ objectName ] === undefined ) {
  28793. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28794. return;
  28795. }
  28796. targetObject = targetObject[ objectName ];
  28797. }
  28798. if ( objectIndex !== undefined ) {
  28799. if ( targetObject[ objectIndex ] === undefined ) {
  28800. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28801. return;
  28802. }
  28803. targetObject = targetObject[ objectIndex ];
  28804. }
  28805. }
  28806. // resolve property
  28807. const nodeProperty = targetObject[ propertyName ];
  28808. if ( nodeProperty === undefined ) {
  28809. const nodeName = parsedPath.nodeName;
  28810. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28811. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28812. return;
  28813. }
  28814. // determine versioning scheme
  28815. let versioning = this.Versioning.None;
  28816. this.targetObject = targetObject;
  28817. if ( targetObject.needsUpdate !== undefined ) { // material
  28818. versioning = this.Versioning.NeedsUpdate;
  28819. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28820. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28821. }
  28822. // determine how the property gets bound
  28823. let bindingType = this.BindingType.Direct;
  28824. if ( propertyIndex !== undefined ) {
  28825. // access a sub element of the property array (only primitives are supported right now)
  28826. if ( propertyName === 'morphTargetInfluences' ) {
  28827. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28828. // support resolving morphTarget names into indices.
  28829. if ( ! targetObject.geometry ) {
  28830. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28831. return;
  28832. }
  28833. if ( ! targetObject.geometry.morphAttributes ) {
  28834. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28835. return;
  28836. }
  28837. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  28838. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  28839. }
  28840. }
  28841. bindingType = this.BindingType.ArrayElement;
  28842. this.resolvedProperty = nodeProperty;
  28843. this.propertyIndex = propertyIndex;
  28844. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28845. // must use copy for Object3D.Euler/Quaternion
  28846. bindingType = this.BindingType.HasFromToArray;
  28847. this.resolvedProperty = nodeProperty;
  28848. } else if ( Array.isArray( nodeProperty ) ) {
  28849. bindingType = this.BindingType.EntireArray;
  28850. this.resolvedProperty = nodeProperty;
  28851. } else {
  28852. this.propertyName = propertyName;
  28853. }
  28854. // select getter / setter
  28855. this.getValue = this.GetterByBindingType[ bindingType ];
  28856. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28857. }
  28858. unbind() {
  28859. this.node = null;
  28860. // back to the prototype version of getValue / setValue
  28861. // note: avoiding to mutate the shape of 'this' via 'delete'
  28862. this.getValue = this._getValue_unbound;
  28863. this.setValue = this._setValue_unbound;
  28864. }
  28865. }
  28866. PropertyBinding.Composite = Composite;
  28867. PropertyBinding.prototype.BindingType = {
  28868. Direct: 0,
  28869. EntireArray: 1,
  28870. ArrayElement: 2,
  28871. HasFromToArray: 3
  28872. };
  28873. PropertyBinding.prototype.Versioning = {
  28874. None: 0,
  28875. NeedsUpdate: 1,
  28876. MatrixWorldNeedsUpdate: 2
  28877. };
  28878. PropertyBinding.prototype.GetterByBindingType = [
  28879. PropertyBinding.prototype._getValue_direct,
  28880. PropertyBinding.prototype._getValue_array,
  28881. PropertyBinding.prototype._getValue_arrayElement,
  28882. PropertyBinding.prototype._getValue_toArray,
  28883. ];
  28884. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  28885. [
  28886. // Direct
  28887. PropertyBinding.prototype._setValue_direct,
  28888. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  28889. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  28890. ], [
  28891. // EntireArray
  28892. PropertyBinding.prototype._setValue_array,
  28893. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  28894. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  28895. ], [
  28896. // ArrayElement
  28897. PropertyBinding.prototype._setValue_arrayElement,
  28898. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  28899. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  28900. ], [
  28901. // HasToFromArray
  28902. PropertyBinding.prototype._setValue_fromArray,
  28903. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  28904. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  28905. ]
  28906. ];
  28907. /**
  28908. *
  28909. * A group of objects that receives a shared animation state.
  28910. *
  28911. * Usage:
  28912. *
  28913. * - Add objects you would otherwise pass as 'root' to the
  28914. * constructor or the .clipAction method of AnimationMixer.
  28915. *
  28916. * - Instead pass this object as 'root'.
  28917. *
  28918. * - You can also add and remove objects later when the mixer
  28919. * is running.
  28920. *
  28921. * Note:
  28922. *
  28923. * Objects of this class appear as one object to the mixer,
  28924. * so cache control of the individual objects must be done
  28925. * on the group.
  28926. *
  28927. * Limitation:
  28928. *
  28929. * - The animated properties must be compatible among the
  28930. * all objects in the group.
  28931. *
  28932. * - A single property can either be controlled through a
  28933. * target group or directly, but not both.
  28934. */
  28935. class AnimationObjectGroup {
  28936. constructor() {
  28937. this.isAnimationObjectGroup = true;
  28938. this.uuid = generateUUID();
  28939. // cached objects followed by the active ones
  28940. this._objects = Array.prototype.slice.call( arguments );
  28941. this.nCachedObjects_ = 0; // threshold
  28942. // note: read by PropertyBinding.Composite
  28943. const indices = {};
  28944. this._indicesByUUID = indices; // for bookkeeping
  28945. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28946. indices[ arguments[ i ].uuid ] = i;
  28947. }
  28948. this._paths = []; // inside: string
  28949. this._parsedPaths = []; // inside: { we don't care, here }
  28950. this._bindings = []; // inside: Array< PropertyBinding >
  28951. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  28952. const scope = this;
  28953. this.stats = {
  28954. objects: {
  28955. get total() {
  28956. return scope._objects.length;
  28957. },
  28958. get inUse() {
  28959. return this.total - scope.nCachedObjects_;
  28960. }
  28961. },
  28962. get bindingsPerObject() {
  28963. return scope._bindings.length;
  28964. }
  28965. };
  28966. }
  28967. add() {
  28968. const objects = this._objects,
  28969. indicesByUUID = this._indicesByUUID,
  28970. paths = this._paths,
  28971. parsedPaths = this._parsedPaths,
  28972. bindings = this._bindings,
  28973. nBindings = bindings.length;
  28974. let knownObject = undefined,
  28975. nObjects = objects.length,
  28976. nCachedObjects = this.nCachedObjects_;
  28977. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28978. const object = arguments[ i ],
  28979. uuid = object.uuid;
  28980. let index = indicesByUUID[ uuid ];
  28981. if ( index === undefined ) {
  28982. // unknown object -> add it to the ACTIVE region
  28983. index = nObjects ++;
  28984. indicesByUUID[ uuid ] = index;
  28985. objects.push( object );
  28986. // accounting is done, now do the same for all bindings
  28987. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28988. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28989. }
  28990. } else if ( index < nCachedObjects ) {
  28991. knownObject = objects[ index ];
  28992. // move existing object to the ACTIVE region
  28993. const firstActiveIndex = -- nCachedObjects,
  28994. lastCachedObject = objects[ firstActiveIndex ];
  28995. indicesByUUID[ lastCachedObject.uuid ] = index;
  28996. objects[ index ] = lastCachedObject;
  28997. indicesByUUID[ uuid ] = firstActiveIndex;
  28998. objects[ firstActiveIndex ] = object;
  28999. // accounting is done, now do the same for all bindings
  29000. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29001. const bindingsForPath = bindings[ j ],
  29002. lastCached = bindingsForPath[ firstActiveIndex ];
  29003. let binding = bindingsForPath[ index ];
  29004. bindingsForPath[ index ] = lastCached;
  29005. if ( binding === undefined ) {
  29006. // since we do not bother to create new bindings
  29007. // for objects that are cached, the binding may
  29008. // or may not exist
  29009. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29010. }
  29011. bindingsForPath[ firstActiveIndex ] = binding;
  29012. }
  29013. } else if ( objects[ index ] !== knownObject ) {
  29014. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29015. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29016. } // else the object is already where we want it to be
  29017. } // for arguments
  29018. this.nCachedObjects_ = nCachedObjects;
  29019. }
  29020. remove() {
  29021. const objects = this._objects,
  29022. indicesByUUID = this._indicesByUUID,
  29023. bindings = this._bindings,
  29024. nBindings = bindings.length;
  29025. let nCachedObjects = this.nCachedObjects_;
  29026. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29027. const object = arguments[ i ],
  29028. uuid = object.uuid,
  29029. index = indicesByUUID[ uuid ];
  29030. if ( index !== undefined && index >= nCachedObjects ) {
  29031. // move existing object into the CACHED region
  29032. const lastCachedIndex = nCachedObjects ++,
  29033. firstActiveObject = objects[ lastCachedIndex ];
  29034. indicesByUUID[ firstActiveObject.uuid ] = index;
  29035. objects[ index ] = firstActiveObject;
  29036. indicesByUUID[ uuid ] = lastCachedIndex;
  29037. objects[ lastCachedIndex ] = object;
  29038. // accounting is done, now do the same for all bindings
  29039. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29040. const bindingsForPath = bindings[ j ],
  29041. firstActive = bindingsForPath[ lastCachedIndex ],
  29042. binding = bindingsForPath[ index ];
  29043. bindingsForPath[ index ] = firstActive;
  29044. bindingsForPath[ lastCachedIndex ] = binding;
  29045. }
  29046. }
  29047. } // for arguments
  29048. this.nCachedObjects_ = nCachedObjects;
  29049. }
  29050. // remove & forget
  29051. uncache() {
  29052. const objects = this._objects,
  29053. indicesByUUID = this._indicesByUUID,
  29054. bindings = this._bindings,
  29055. nBindings = bindings.length;
  29056. let nCachedObjects = this.nCachedObjects_,
  29057. nObjects = objects.length;
  29058. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29059. const object = arguments[ i ],
  29060. uuid = object.uuid,
  29061. index = indicesByUUID[ uuid ];
  29062. if ( index !== undefined ) {
  29063. delete indicesByUUID[ uuid ];
  29064. if ( index < nCachedObjects ) {
  29065. // object is cached, shrink the CACHED region
  29066. const firstActiveIndex = -- nCachedObjects,
  29067. lastCachedObject = objects[ firstActiveIndex ],
  29068. lastIndex = -- nObjects,
  29069. lastObject = objects[ lastIndex ];
  29070. // last cached object takes this object's place
  29071. indicesByUUID[ lastCachedObject.uuid ] = index;
  29072. objects[ index ] = lastCachedObject;
  29073. // last object goes to the activated slot and pop
  29074. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29075. objects[ firstActiveIndex ] = lastObject;
  29076. objects.pop();
  29077. // accounting is done, now do the same for all bindings
  29078. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29079. const bindingsForPath = bindings[ j ],
  29080. lastCached = bindingsForPath[ firstActiveIndex ],
  29081. last = bindingsForPath[ lastIndex ];
  29082. bindingsForPath[ index ] = lastCached;
  29083. bindingsForPath[ firstActiveIndex ] = last;
  29084. bindingsForPath.pop();
  29085. }
  29086. } else {
  29087. // object is active, just swap with the last and pop
  29088. const lastIndex = -- nObjects,
  29089. lastObject = objects[ lastIndex ];
  29090. if ( lastIndex > 0 ) {
  29091. indicesByUUID[ lastObject.uuid ] = index;
  29092. }
  29093. objects[ index ] = lastObject;
  29094. objects.pop();
  29095. // accounting is done, now do the same for all bindings
  29096. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29097. const bindingsForPath = bindings[ j ];
  29098. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29099. bindingsForPath.pop();
  29100. }
  29101. } // cached or active
  29102. } // if object is known
  29103. } // for arguments
  29104. this.nCachedObjects_ = nCachedObjects;
  29105. }
  29106. // Internal interface used by befriended PropertyBinding.Composite:
  29107. subscribe_( path, parsedPath ) {
  29108. // returns an array of bindings for the given path that is changed
  29109. // according to the contained objects in the group
  29110. const indicesByPath = this._bindingsIndicesByPath;
  29111. let index = indicesByPath[ path ];
  29112. const bindings = this._bindings;
  29113. if ( index !== undefined ) return bindings[ index ];
  29114. const paths = this._paths,
  29115. parsedPaths = this._parsedPaths,
  29116. objects = this._objects,
  29117. nObjects = objects.length,
  29118. nCachedObjects = this.nCachedObjects_,
  29119. bindingsForPath = new Array( nObjects );
  29120. index = bindings.length;
  29121. indicesByPath[ path ] = index;
  29122. paths.push( path );
  29123. parsedPaths.push( parsedPath );
  29124. bindings.push( bindingsForPath );
  29125. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29126. const object = objects[ i ];
  29127. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29128. }
  29129. return bindingsForPath;
  29130. }
  29131. unsubscribe_( path ) {
  29132. // tells the group to forget about a property path and no longer
  29133. // update the array previously obtained with 'subscribe_'
  29134. const indicesByPath = this._bindingsIndicesByPath,
  29135. index = indicesByPath[ path ];
  29136. if ( index !== undefined ) {
  29137. const paths = this._paths,
  29138. parsedPaths = this._parsedPaths,
  29139. bindings = this._bindings,
  29140. lastBindingsIndex = bindings.length - 1,
  29141. lastBindings = bindings[ lastBindingsIndex ],
  29142. lastBindingsPath = path[ lastBindingsIndex ];
  29143. indicesByPath[ lastBindingsPath ] = index;
  29144. bindings[ index ] = lastBindings;
  29145. bindings.pop();
  29146. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29147. parsedPaths.pop();
  29148. paths[ index ] = paths[ lastBindingsIndex ];
  29149. paths.pop();
  29150. }
  29151. }
  29152. }
  29153. class AnimationAction {
  29154. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29155. this._mixer = mixer;
  29156. this._clip = clip;
  29157. this._localRoot = localRoot;
  29158. this.blendMode = blendMode;
  29159. const tracks = clip.tracks,
  29160. nTracks = tracks.length,
  29161. interpolants = new Array( nTracks );
  29162. const interpolantSettings = {
  29163. endingStart: ZeroCurvatureEnding,
  29164. endingEnd: ZeroCurvatureEnding
  29165. };
  29166. for ( let i = 0; i !== nTracks; ++ i ) {
  29167. const interpolant = tracks[ i ].createInterpolant( null );
  29168. interpolants[ i ] = interpolant;
  29169. interpolant.settings = interpolantSettings;
  29170. }
  29171. this._interpolantSettings = interpolantSettings;
  29172. this._interpolants = interpolants; // bound by the mixer
  29173. // inside: PropertyMixer (managed by the mixer)
  29174. this._propertyBindings = new Array( nTracks );
  29175. this._cacheIndex = null; // for the memory manager
  29176. this._byClipCacheIndex = null; // for the memory manager
  29177. this._timeScaleInterpolant = null;
  29178. this._weightInterpolant = null;
  29179. this.loop = LoopRepeat;
  29180. this._loopCount = - 1;
  29181. // global mixer time when the action is to be started
  29182. // it's set back to 'null' upon start of the action
  29183. this._startTime = null;
  29184. // scaled local time of the action
  29185. // gets clamped or wrapped to 0..clip.duration according to loop
  29186. this.time = 0;
  29187. this.timeScale = 1;
  29188. this._effectiveTimeScale = 1;
  29189. this.weight = 1;
  29190. this._effectiveWeight = 1;
  29191. this.repetitions = Infinity; // no. of repetitions when looping
  29192. this.paused = false; // true -> zero effective time scale
  29193. this.enabled = true; // false -> zero effective weight
  29194. this.clampWhenFinished = false;// keep feeding the last frame?
  29195. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29196. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29197. }
  29198. // State & Scheduling
  29199. play() {
  29200. this._mixer._activateAction( this );
  29201. return this;
  29202. }
  29203. stop() {
  29204. this._mixer._deactivateAction( this );
  29205. return this.reset();
  29206. }
  29207. reset() {
  29208. this.paused = false;
  29209. this.enabled = true;
  29210. this.time = 0; // restart clip
  29211. this._loopCount = - 1;// forget previous loops
  29212. this._startTime = null;// forget scheduling
  29213. return this.stopFading().stopWarping();
  29214. }
  29215. isRunning() {
  29216. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29217. this._startTime === null && this._mixer._isActiveAction( this );
  29218. }
  29219. // return true when play has been called
  29220. isScheduled() {
  29221. return this._mixer._isActiveAction( this );
  29222. }
  29223. startAt( time ) {
  29224. this._startTime = time;
  29225. return this;
  29226. }
  29227. setLoop( mode, repetitions ) {
  29228. this.loop = mode;
  29229. this.repetitions = repetitions;
  29230. return this;
  29231. }
  29232. // Weight
  29233. // set the weight stopping any scheduled fading
  29234. // although .enabled = false yields an effective weight of zero, this
  29235. // method does *not* change .enabled, because it would be confusing
  29236. setEffectiveWeight( weight ) {
  29237. this.weight = weight;
  29238. // note: same logic as when updated at runtime
  29239. this._effectiveWeight = this.enabled ? weight : 0;
  29240. return this.stopFading();
  29241. }
  29242. // return the weight considering fading and .enabled
  29243. getEffectiveWeight() {
  29244. return this._effectiveWeight;
  29245. }
  29246. fadeIn( duration ) {
  29247. return this._scheduleFading( duration, 0, 1 );
  29248. }
  29249. fadeOut( duration ) {
  29250. return this._scheduleFading( duration, 1, 0 );
  29251. }
  29252. crossFadeFrom( fadeOutAction, duration, warp ) {
  29253. fadeOutAction.fadeOut( duration );
  29254. this.fadeIn( duration );
  29255. if ( warp ) {
  29256. const fadeInDuration = this._clip.duration,
  29257. fadeOutDuration = fadeOutAction._clip.duration,
  29258. startEndRatio = fadeOutDuration / fadeInDuration,
  29259. endStartRatio = fadeInDuration / fadeOutDuration;
  29260. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29261. this.warp( endStartRatio, 1.0, duration );
  29262. }
  29263. return this;
  29264. }
  29265. crossFadeTo( fadeInAction, duration, warp ) {
  29266. return fadeInAction.crossFadeFrom( this, duration, warp );
  29267. }
  29268. stopFading() {
  29269. const weightInterpolant = this._weightInterpolant;
  29270. if ( weightInterpolant !== null ) {
  29271. this._weightInterpolant = null;
  29272. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29273. }
  29274. return this;
  29275. }
  29276. // Time Scale Control
  29277. // set the time scale stopping any scheduled warping
  29278. // although .paused = true yields an effective time scale of zero, this
  29279. // method does *not* change .paused, because it would be confusing
  29280. setEffectiveTimeScale( timeScale ) {
  29281. this.timeScale = timeScale;
  29282. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29283. return this.stopWarping();
  29284. }
  29285. // return the time scale considering warping and .paused
  29286. getEffectiveTimeScale() {
  29287. return this._effectiveTimeScale;
  29288. }
  29289. setDuration( duration ) {
  29290. this.timeScale = this._clip.duration / duration;
  29291. return this.stopWarping();
  29292. }
  29293. syncWith( action ) {
  29294. this.time = action.time;
  29295. this.timeScale = action.timeScale;
  29296. return this.stopWarping();
  29297. }
  29298. halt( duration ) {
  29299. return this.warp( this._effectiveTimeScale, 0, duration );
  29300. }
  29301. warp( startTimeScale, endTimeScale, duration ) {
  29302. const mixer = this._mixer,
  29303. now = mixer.time,
  29304. timeScale = this.timeScale;
  29305. let interpolant = this._timeScaleInterpolant;
  29306. if ( interpolant === null ) {
  29307. interpolant = mixer._lendControlInterpolant();
  29308. this._timeScaleInterpolant = interpolant;
  29309. }
  29310. const times = interpolant.parameterPositions,
  29311. values = interpolant.sampleValues;
  29312. times[ 0 ] = now;
  29313. times[ 1 ] = now + duration;
  29314. values[ 0 ] = startTimeScale / timeScale;
  29315. values[ 1 ] = endTimeScale / timeScale;
  29316. return this;
  29317. }
  29318. stopWarping() {
  29319. const timeScaleInterpolant = this._timeScaleInterpolant;
  29320. if ( timeScaleInterpolant !== null ) {
  29321. this._timeScaleInterpolant = null;
  29322. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29323. }
  29324. return this;
  29325. }
  29326. // Object Accessors
  29327. getMixer() {
  29328. return this._mixer;
  29329. }
  29330. getClip() {
  29331. return this._clip;
  29332. }
  29333. getRoot() {
  29334. return this._localRoot || this._mixer._root;
  29335. }
  29336. // Interna
  29337. _update( time, deltaTime, timeDirection, accuIndex ) {
  29338. // called by the mixer
  29339. if ( ! this.enabled ) {
  29340. // call ._updateWeight() to update ._effectiveWeight
  29341. this._updateWeight( time );
  29342. return;
  29343. }
  29344. const startTime = this._startTime;
  29345. if ( startTime !== null ) {
  29346. // check for scheduled start of action
  29347. const timeRunning = ( time - startTime ) * timeDirection;
  29348. if ( timeRunning < 0 || timeDirection === 0 ) {
  29349. deltaTime = 0;
  29350. } else {
  29351. this._startTime = null; // unschedule
  29352. deltaTime = timeDirection * timeRunning;
  29353. }
  29354. }
  29355. // apply time scale and advance time
  29356. deltaTime *= this._updateTimeScale( time );
  29357. const clipTime = this._updateTime( deltaTime );
  29358. // note: _updateTime may disable the action resulting in
  29359. // an effective weight of 0
  29360. const weight = this._updateWeight( time );
  29361. if ( weight > 0 ) {
  29362. const interpolants = this._interpolants;
  29363. const propertyMixers = this._propertyBindings;
  29364. switch ( this.blendMode ) {
  29365. case AdditiveAnimationBlendMode:
  29366. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29367. interpolants[ j ].evaluate( clipTime );
  29368. propertyMixers[ j ].accumulateAdditive( weight );
  29369. }
  29370. break;
  29371. case NormalAnimationBlendMode:
  29372. default:
  29373. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29374. interpolants[ j ].evaluate( clipTime );
  29375. propertyMixers[ j ].accumulate( accuIndex, weight );
  29376. }
  29377. }
  29378. }
  29379. }
  29380. _updateWeight( time ) {
  29381. let weight = 0;
  29382. if ( this.enabled ) {
  29383. weight = this.weight;
  29384. const interpolant = this._weightInterpolant;
  29385. if ( interpolant !== null ) {
  29386. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29387. weight *= interpolantValue;
  29388. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29389. this.stopFading();
  29390. if ( interpolantValue === 0 ) {
  29391. // faded out, disable
  29392. this.enabled = false;
  29393. }
  29394. }
  29395. }
  29396. }
  29397. this._effectiveWeight = weight;
  29398. return weight;
  29399. }
  29400. _updateTimeScale( time ) {
  29401. let timeScale = 0;
  29402. if ( ! this.paused ) {
  29403. timeScale = this.timeScale;
  29404. const interpolant = this._timeScaleInterpolant;
  29405. if ( interpolant !== null ) {
  29406. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29407. timeScale *= interpolantValue;
  29408. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29409. this.stopWarping();
  29410. if ( timeScale === 0 ) {
  29411. // motion has halted, pause
  29412. this.paused = true;
  29413. } else {
  29414. // warp done - apply final time scale
  29415. this.timeScale = timeScale;
  29416. }
  29417. }
  29418. }
  29419. }
  29420. this._effectiveTimeScale = timeScale;
  29421. return timeScale;
  29422. }
  29423. _updateTime( deltaTime ) {
  29424. const duration = this._clip.duration;
  29425. const loop = this.loop;
  29426. let time = this.time + deltaTime;
  29427. let loopCount = this._loopCount;
  29428. const pingPong = ( loop === LoopPingPong );
  29429. if ( deltaTime === 0 ) {
  29430. if ( loopCount === - 1 ) return time;
  29431. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29432. }
  29433. if ( loop === LoopOnce ) {
  29434. if ( loopCount === - 1 ) {
  29435. // just started
  29436. this._loopCount = 0;
  29437. this._setEndings( true, true, false );
  29438. }
  29439. handle_stop: {
  29440. if ( time >= duration ) {
  29441. time = duration;
  29442. } else if ( time < 0 ) {
  29443. time = 0;
  29444. } else {
  29445. this.time = time;
  29446. break handle_stop;
  29447. }
  29448. if ( this.clampWhenFinished ) this.paused = true;
  29449. else this.enabled = false;
  29450. this.time = time;
  29451. this._mixer.dispatchEvent( {
  29452. type: 'finished', action: this,
  29453. direction: deltaTime < 0 ? - 1 : 1
  29454. } );
  29455. }
  29456. } else { // repetitive Repeat or PingPong
  29457. if ( loopCount === - 1 ) {
  29458. // just started
  29459. if ( deltaTime >= 0 ) {
  29460. loopCount = 0;
  29461. this._setEndings( true, this.repetitions === 0, pingPong );
  29462. } else {
  29463. // when looping in reverse direction, the initial
  29464. // transition through zero counts as a repetition,
  29465. // so leave loopCount at -1
  29466. this._setEndings( this.repetitions === 0, true, pingPong );
  29467. }
  29468. }
  29469. if ( time >= duration || time < 0 ) {
  29470. // wrap around
  29471. const loopDelta = Math.floor( time / duration ); // signed
  29472. time -= duration * loopDelta;
  29473. loopCount += Math.abs( loopDelta );
  29474. const pending = this.repetitions - loopCount;
  29475. if ( pending <= 0 ) {
  29476. // have to stop (switch state, clamp time, fire event)
  29477. if ( this.clampWhenFinished ) this.paused = true;
  29478. else this.enabled = false;
  29479. time = deltaTime > 0 ? duration : 0;
  29480. this.time = time;
  29481. this._mixer.dispatchEvent( {
  29482. type: 'finished', action: this,
  29483. direction: deltaTime > 0 ? 1 : - 1
  29484. } );
  29485. } else {
  29486. // keep running
  29487. if ( pending === 1 ) {
  29488. // entering the last round
  29489. const atStart = deltaTime < 0;
  29490. this._setEndings( atStart, ! atStart, pingPong );
  29491. } else {
  29492. this._setEndings( false, false, pingPong );
  29493. }
  29494. this._loopCount = loopCount;
  29495. this.time = time;
  29496. this._mixer.dispatchEvent( {
  29497. type: 'loop', action: this, loopDelta: loopDelta
  29498. } );
  29499. }
  29500. } else {
  29501. this.time = time;
  29502. }
  29503. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  29504. // invert time for the "pong round"
  29505. return duration - time;
  29506. }
  29507. }
  29508. return time;
  29509. }
  29510. _setEndings( atStart, atEnd, pingPong ) {
  29511. const settings = this._interpolantSettings;
  29512. if ( pingPong ) {
  29513. settings.endingStart = ZeroSlopeEnding;
  29514. settings.endingEnd = ZeroSlopeEnding;
  29515. } else {
  29516. // assuming for LoopOnce atStart == atEnd == true
  29517. if ( atStart ) {
  29518. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29519. } else {
  29520. settings.endingStart = WrapAroundEnding;
  29521. }
  29522. if ( atEnd ) {
  29523. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29524. } else {
  29525. settings.endingEnd = WrapAroundEnding;
  29526. }
  29527. }
  29528. }
  29529. _scheduleFading( duration, weightNow, weightThen ) {
  29530. const mixer = this._mixer, now = mixer.time;
  29531. let interpolant = this._weightInterpolant;
  29532. if ( interpolant === null ) {
  29533. interpolant = mixer._lendControlInterpolant();
  29534. this._weightInterpolant = interpolant;
  29535. }
  29536. const times = interpolant.parameterPositions,
  29537. values = interpolant.sampleValues;
  29538. times[ 0 ] = now;
  29539. values[ 0 ] = weightNow;
  29540. times[ 1 ] = now + duration;
  29541. values[ 1 ] = weightThen;
  29542. return this;
  29543. }
  29544. }
  29545. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  29546. class AnimationMixer extends EventDispatcher {
  29547. constructor( root ) {
  29548. super();
  29549. this._root = root;
  29550. this._initMemoryManager();
  29551. this._accuIndex = 0;
  29552. this.time = 0;
  29553. this.timeScale = 1.0;
  29554. }
  29555. _bindAction( action, prototypeAction ) {
  29556. const root = action._localRoot || this._root,
  29557. tracks = action._clip.tracks,
  29558. nTracks = tracks.length,
  29559. bindings = action._propertyBindings,
  29560. interpolants = action._interpolants,
  29561. rootUuid = root.uuid,
  29562. bindingsByRoot = this._bindingsByRootAndName;
  29563. let bindingsByName = bindingsByRoot[ rootUuid ];
  29564. if ( bindingsByName === undefined ) {
  29565. bindingsByName = {};
  29566. bindingsByRoot[ rootUuid ] = bindingsByName;
  29567. }
  29568. for ( let i = 0; i !== nTracks; ++ i ) {
  29569. const track = tracks[ i ],
  29570. trackName = track.name;
  29571. let binding = bindingsByName[ trackName ];
  29572. if ( binding !== undefined ) {
  29573. ++ binding.referenceCount;
  29574. bindings[ i ] = binding;
  29575. } else {
  29576. binding = bindings[ i ];
  29577. if ( binding !== undefined ) {
  29578. // existing binding, make sure the cache knows
  29579. if ( binding._cacheIndex === null ) {
  29580. ++ binding.referenceCount;
  29581. this._addInactiveBinding( binding, rootUuid, trackName );
  29582. }
  29583. continue;
  29584. }
  29585. const path = prototypeAction && prototypeAction.
  29586. _propertyBindings[ i ].binding.parsedPath;
  29587. binding = new PropertyMixer(
  29588. PropertyBinding.create( root, trackName, path ),
  29589. track.ValueTypeName, track.getValueSize() );
  29590. ++ binding.referenceCount;
  29591. this._addInactiveBinding( binding, rootUuid, trackName );
  29592. bindings[ i ] = binding;
  29593. }
  29594. interpolants[ i ].resultBuffer = binding.buffer;
  29595. }
  29596. }
  29597. _activateAction( action ) {
  29598. if ( ! this._isActiveAction( action ) ) {
  29599. if ( action._cacheIndex === null ) {
  29600. // this action has been forgotten by the cache, but the user
  29601. // appears to be still using it -> rebind
  29602. const rootUuid = ( action._localRoot || this._root ).uuid,
  29603. clipUuid = action._clip.uuid,
  29604. actionsForClip = this._actionsByClip[ clipUuid ];
  29605. this._bindAction( action,
  29606. actionsForClip && actionsForClip.knownActions[ 0 ] );
  29607. this._addInactiveAction( action, clipUuid, rootUuid );
  29608. }
  29609. const bindings = action._propertyBindings;
  29610. // increment reference counts / sort out state
  29611. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29612. const binding = bindings[ i ];
  29613. if ( binding.useCount ++ === 0 ) {
  29614. this._lendBinding( binding );
  29615. binding.saveOriginalState();
  29616. }
  29617. }
  29618. this._lendAction( action );
  29619. }
  29620. }
  29621. _deactivateAction( action ) {
  29622. if ( this._isActiveAction( action ) ) {
  29623. const bindings = action._propertyBindings;
  29624. // decrement reference counts / sort out state
  29625. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29626. const binding = bindings[ i ];
  29627. if ( -- binding.useCount === 0 ) {
  29628. binding.restoreOriginalState();
  29629. this._takeBackBinding( binding );
  29630. }
  29631. }
  29632. this._takeBackAction( action );
  29633. }
  29634. }
  29635. // Memory manager
  29636. _initMemoryManager() {
  29637. this._actions = []; // 'nActiveActions' followed by inactive ones
  29638. this._nActiveActions = 0;
  29639. this._actionsByClip = {};
  29640. // inside:
  29641. // {
  29642. // knownActions: Array< AnimationAction > - used as prototypes
  29643. // actionByRoot: AnimationAction - lookup
  29644. // }
  29645. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  29646. this._nActiveBindings = 0;
  29647. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  29648. this._controlInterpolants = []; // same game as above
  29649. this._nActiveControlInterpolants = 0;
  29650. const scope = this;
  29651. this.stats = {
  29652. actions: {
  29653. get total() {
  29654. return scope._actions.length;
  29655. },
  29656. get inUse() {
  29657. return scope._nActiveActions;
  29658. }
  29659. },
  29660. bindings: {
  29661. get total() {
  29662. return scope._bindings.length;
  29663. },
  29664. get inUse() {
  29665. return scope._nActiveBindings;
  29666. }
  29667. },
  29668. controlInterpolants: {
  29669. get total() {
  29670. return scope._controlInterpolants.length;
  29671. },
  29672. get inUse() {
  29673. return scope._nActiveControlInterpolants;
  29674. }
  29675. }
  29676. };
  29677. }
  29678. // Memory management for AnimationAction objects
  29679. _isActiveAction( action ) {
  29680. const index = action._cacheIndex;
  29681. return index !== null && index < this._nActiveActions;
  29682. }
  29683. _addInactiveAction( action, clipUuid, rootUuid ) {
  29684. const actions = this._actions,
  29685. actionsByClip = this._actionsByClip;
  29686. let actionsForClip = actionsByClip[ clipUuid ];
  29687. if ( actionsForClip === undefined ) {
  29688. actionsForClip = {
  29689. knownActions: [ action ],
  29690. actionByRoot: {}
  29691. };
  29692. action._byClipCacheIndex = 0;
  29693. actionsByClip[ clipUuid ] = actionsForClip;
  29694. } else {
  29695. const knownActions = actionsForClip.knownActions;
  29696. action._byClipCacheIndex = knownActions.length;
  29697. knownActions.push( action );
  29698. }
  29699. action._cacheIndex = actions.length;
  29700. actions.push( action );
  29701. actionsForClip.actionByRoot[ rootUuid ] = action;
  29702. }
  29703. _removeInactiveAction( action ) {
  29704. const actions = this._actions,
  29705. lastInactiveAction = actions[ actions.length - 1 ],
  29706. cacheIndex = action._cacheIndex;
  29707. lastInactiveAction._cacheIndex = cacheIndex;
  29708. actions[ cacheIndex ] = lastInactiveAction;
  29709. actions.pop();
  29710. action._cacheIndex = null;
  29711. const clipUuid = action._clip.uuid,
  29712. actionsByClip = this._actionsByClip,
  29713. actionsForClip = actionsByClip[ clipUuid ],
  29714. knownActionsForClip = actionsForClip.knownActions,
  29715. lastKnownAction =
  29716. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29717. byClipCacheIndex = action._byClipCacheIndex;
  29718. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29719. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29720. knownActionsForClip.pop();
  29721. action._byClipCacheIndex = null;
  29722. const actionByRoot = actionsForClip.actionByRoot,
  29723. rootUuid = ( action._localRoot || this._root ).uuid;
  29724. delete actionByRoot[ rootUuid ];
  29725. if ( knownActionsForClip.length === 0 ) {
  29726. delete actionsByClip[ clipUuid ];
  29727. }
  29728. this._removeInactiveBindingsForAction( action );
  29729. }
  29730. _removeInactiveBindingsForAction( action ) {
  29731. const bindings = action._propertyBindings;
  29732. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29733. const binding = bindings[ i ];
  29734. if ( -- binding.referenceCount === 0 ) {
  29735. this._removeInactiveBinding( binding );
  29736. }
  29737. }
  29738. }
  29739. _lendAction( action ) {
  29740. // [ active actions | inactive actions ]
  29741. // [ active actions >| inactive actions ]
  29742. // s a
  29743. // <-swap->
  29744. // a s
  29745. const actions = this._actions,
  29746. prevIndex = action._cacheIndex,
  29747. lastActiveIndex = this._nActiveActions ++,
  29748. firstInactiveAction = actions[ lastActiveIndex ];
  29749. action._cacheIndex = lastActiveIndex;
  29750. actions[ lastActiveIndex ] = action;
  29751. firstInactiveAction._cacheIndex = prevIndex;
  29752. actions[ prevIndex ] = firstInactiveAction;
  29753. }
  29754. _takeBackAction( action ) {
  29755. // [ active actions | inactive actions ]
  29756. // [ active actions |< inactive actions ]
  29757. // a s
  29758. // <-swap->
  29759. // s a
  29760. const actions = this._actions,
  29761. prevIndex = action._cacheIndex,
  29762. firstInactiveIndex = -- this._nActiveActions,
  29763. lastActiveAction = actions[ firstInactiveIndex ];
  29764. action._cacheIndex = firstInactiveIndex;
  29765. actions[ firstInactiveIndex ] = action;
  29766. lastActiveAction._cacheIndex = prevIndex;
  29767. actions[ prevIndex ] = lastActiveAction;
  29768. }
  29769. // Memory management for PropertyMixer objects
  29770. _addInactiveBinding( binding, rootUuid, trackName ) {
  29771. const bindingsByRoot = this._bindingsByRootAndName,
  29772. bindings = this._bindings;
  29773. let bindingByName = bindingsByRoot[ rootUuid ];
  29774. if ( bindingByName === undefined ) {
  29775. bindingByName = {};
  29776. bindingsByRoot[ rootUuid ] = bindingByName;
  29777. }
  29778. bindingByName[ trackName ] = binding;
  29779. binding._cacheIndex = bindings.length;
  29780. bindings.push( binding );
  29781. }
  29782. _removeInactiveBinding( binding ) {
  29783. const bindings = this._bindings,
  29784. propBinding = binding.binding,
  29785. rootUuid = propBinding.rootNode.uuid,
  29786. trackName = propBinding.path,
  29787. bindingsByRoot = this._bindingsByRootAndName,
  29788. bindingByName = bindingsByRoot[ rootUuid ],
  29789. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29790. cacheIndex = binding._cacheIndex;
  29791. lastInactiveBinding._cacheIndex = cacheIndex;
  29792. bindings[ cacheIndex ] = lastInactiveBinding;
  29793. bindings.pop();
  29794. delete bindingByName[ trackName ];
  29795. if ( Object.keys( bindingByName ).length === 0 ) {
  29796. delete bindingsByRoot[ rootUuid ];
  29797. }
  29798. }
  29799. _lendBinding( binding ) {
  29800. const bindings = this._bindings,
  29801. prevIndex = binding._cacheIndex,
  29802. lastActiveIndex = this._nActiveBindings ++,
  29803. firstInactiveBinding = bindings[ lastActiveIndex ];
  29804. binding._cacheIndex = lastActiveIndex;
  29805. bindings[ lastActiveIndex ] = binding;
  29806. firstInactiveBinding._cacheIndex = prevIndex;
  29807. bindings[ prevIndex ] = firstInactiveBinding;
  29808. }
  29809. _takeBackBinding( binding ) {
  29810. const bindings = this._bindings,
  29811. prevIndex = binding._cacheIndex,
  29812. firstInactiveIndex = -- this._nActiveBindings,
  29813. lastActiveBinding = bindings[ firstInactiveIndex ];
  29814. binding._cacheIndex = firstInactiveIndex;
  29815. bindings[ firstInactiveIndex ] = binding;
  29816. lastActiveBinding._cacheIndex = prevIndex;
  29817. bindings[ prevIndex ] = lastActiveBinding;
  29818. }
  29819. // Memory management of Interpolants for weight and time scale
  29820. _lendControlInterpolant() {
  29821. const interpolants = this._controlInterpolants,
  29822. lastActiveIndex = this._nActiveControlInterpolants ++;
  29823. let interpolant = interpolants[ lastActiveIndex ];
  29824. if ( interpolant === undefined ) {
  29825. interpolant = new LinearInterpolant(
  29826. new Float32Array( 2 ), new Float32Array( 2 ),
  29827. 1, _controlInterpolantsResultBuffer );
  29828. interpolant.__cacheIndex = lastActiveIndex;
  29829. interpolants[ lastActiveIndex ] = interpolant;
  29830. }
  29831. return interpolant;
  29832. }
  29833. _takeBackControlInterpolant( interpolant ) {
  29834. const interpolants = this._controlInterpolants,
  29835. prevIndex = interpolant.__cacheIndex,
  29836. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29837. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29838. interpolant.__cacheIndex = firstInactiveIndex;
  29839. interpolants[ firstInactiveIndex ] = interpolant;
  29840. lastActiveInterpolant.__cacheIndex = prevIndex;
  29841. interpolants[ prevIndex ] = lastActiveInterpolant;
  29842. }
  29843. // return an action for a clip optionally using a custom root target
  29844. // object (this method allocates a lot of dynamic memory in case a
  29845. // previously unknown clip/root combination is specified)
  29846. clipAction( clip, optionalRoot, blendMode ) {
  29847. const root = optionalRoot || this._root,
  29848. rootUuid = root.uuid;
  29849. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  29850. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  29851. const actionsForClip = this._actionsByClip[ clipUuid ];
  29852. let prototypeAction = null;
  29853. if ( blendMode === undefined ) {
  29854. if ( clipObject !== null ) {
  29855. blendMode = clipObject.blendMode;
  29856. } else {
  29857. blendMode = NormalAnimationBlendMode;
  29858. }
  29859. }
  29860. if ( actionsForClip !== undefined ) {
  29861. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  29862. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  29863. return existingAction;
  29864. }
  29865. // we know the clip, so we don't have to parse all
  29866. // the bindings again but can just copy
  29867. prototypeAction = actionsForClip.knownActions[ 0 ];
  29868. // also, take the clip from the prototype action
  29869. if ( clipObject === null )
  29870. clipObject = prototypeAction._clip;
  29871. }
  29872. // clip must be known when specified via string
  29873. if ( clipObject === null ) return null;
  29874. // allocate all resources required to run it
  29875. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  29876. this._bindAction( newAction, prototypeAction );
  29877. // and make the action known to the memory manager
  29878. this._addInactiveAction( newAction, clipUuid, rootUuid );
  29879. return newAction;
  29880. }
  29881. // get an existing action
  29882. existingAction( clip, optionalRoot ) {
  29883. const root = optionalRoot || this._root,
  29884. rootUuid = root.uuid,
  29885. clipObject = typeof clip === 'string' ?
  29886. AnimationClip.findByName( root, clip ) : clip,
  29887. clipUuid = clipObject ? clipObject.uuid : clip,
  29888. actionsForClip = this._actionsByClip[ clipUuid ];
  29889. if ( actionsForClip !== undefined ) {
  29890. return actionsForClip.actionByRoot[ rootUuid ] || null;
  29891. }
  29892. return null;
  29893. }
  29894. // deactivates all previously scheduled actions
  29895. stopAllAction() {
  29896. const actions = this._actions,
  29897. nActions = this._nActiveActions;
  29898. for ( let i = nActions - 1; i >= 0; -- i ) {
  29899. actions[ i ].stop();
  29900. }
  29901. return this;
  29902. }
  29903. // advance the time and update apply the animation
  29904. update( deltaTime ) {
  29905. deltaTime *= this.timeScale;
  29906. const actions = this._actions,
  29907. nActions = this._nActiveActions,
  29908. time = this.time += deltaTime,
  29909. timeDirection = Math.sign( deltaTime ),
  29910. accuIndex = this._accuIndex ^= 1;
  29911. // run active actions
  29912. for ( let i = 0; i !== nActions; ++ i ) {
  29913. const action = actions[ i ];
  29914. action._update( time, deltaTime, timeDirection, accuIndex );
  29915. }
  29916. // update scene graph
  29917. const bindings = this._bindings,
  29918. nBindings = this._nActiveBindings;
  29919. for ( let i = 0; i !== nBindings; ++ i ) {
  29920. bindings[ i ].apply( accuIndex );
  29921. }
  29922. return this;
  29923. }
  29924. // Allows you to seek to a specific time in an animation.
  29925. setTime( timeInSeconds ) {
  29926. this.time = 0; // Zero out time attribute for AnimationMixer object;
  29927. for ( let i = 0; i < this._actions.length; i ++ ) {
  29928. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  29929. }
  29930. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  29931. }
  29932. // return this mixer's root target object
  29933. getRoot() {
  29934. return this._root;
  29935. }
  29936. // free all resources specific to a particular clip
  29937. uncacheClip( clip ) {
  29938. const actions = this._actions,
  29939. clipUuid = clip.uuid,
  29940. actionsByClip = this._actionsByClip,
  29941. actionsForClip = actionsByClip[ clipUuid ];
  29942. if ( actionsForClip !== undefined ) {
  29943. // note: just calling _removeInactiveAction would mess up the
  29944. // iteration state and also require updating the state we can
  29945. // just throw away
  29946. const actionsToRemove = actionsForClip.knownActions;
  29947. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  29948. const action = actionsToRemove[ i ];
  29949. this._deactivateAction( action );
  29950. const cacheIndex = action._cacheIndex,
  29951. lastInactiveAction = actions[ actions.length - 1 ];
  29952. action._cacheIndex = null;
  29953. action._byClipCacheIndex = null;
  29954. lastInactiveAction._cacheIndex = cacheIndex;
  29955. actions[ cacheIndex ] = lastInactiveAction;
  29956. actions.pop();
  29957. this._removeInactiveBindingsForAction( action );
  29958. }
  29959. delete actionsByClip[ clipUuid ];
  29960. }
  29961. }
  29962. // free all resources specific to a particular root target object
  29963. uncacheRoot( root ) {
  29964. const rootUuid = root.uuid,
  29965. actionsByClip = this._actionsByClip;
  29966. for ( const clipUuid in actionsByClip ) {
  29967. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  29968. action = actionByRoot[ rootUuid ];
  29969. if ( action !== undefined ) {
  29970. this._deactivateAction( action );
  29971. this._removeInactiveAction( action );
  29972. }
  29973. }
  29974. const bindingsByRoot = this._bindingsByRootAndName,
  29975. bindingByName = bindingsByRoot[ rootUuid ];
  29976. if ( bindingByName !== undefined ) {
  29977. for ( const trackName in bindingByName ) {
  29978. const binding = bindingByName[ trackName ];
  29979. binding.restoreOriginalState();
  29980. this._removeInactiveBinding( binding );
  29981. }
  29982. }
  29983. }
  29984. // remove a targeted clip from the cache
  29985. uncacheAction( clip, optionalRoot ) {
  29986. const action = this.existingAction( clip, optionalRoot );
  29987. if ( action !== null ) {
  29988. this._deactivateAction( action );
  29989. this._removeInactiveAction( action );
  29990. }
  29991. }
  29992. }
  29993. class Uniform {
  29994. constructor( value ) {
  29995. this.value = value;
  29996. }
  29997. clone() {
  29998. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29999. }
  30000. }
  30001. let _id = 0;
  30002. class UniformsGroup extends EventDispatcher {
  30003. constructor() {
  30004. super();
  30005. this.isUniformsGroup = true;
  30006. Object.defineProperty( this, 'id', { value: _id ++ } );
  30007. this.name = '';
  30008. this.usage = StaticDrawUsage;
  30009. this.uniforms = [];
  30010. }
  30011. add( uniform ) {
  30012. this.uniforms.push( uniform );
  30013. return this;
  30014. }
  30015. remove( uniform ) {
  30016. const index = this.uniforms.indexOf( uniform );
  30017. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  30018. return this;
  30019. }
  30020. setName( name ) {
  30021. this.name = name;
  30022. return this;
  30023. }
  30024. setUsage( value ) {
  30025. this.usage = value;
  30026. return this;
  30027. }
  30028. dispose() {
  30029. this.dispatchEvent( { type: 'dispose' } );
  30030. return this;
  30031. }
  30032. copy( source ) {
  30033. this.name = source.name;
  30034. this.usage = source.usage;
  30035. const uniformsSource = source.uniforms;
  30036. this.uniforms.length = 0;
  30037. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  30038. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  30039. for ( let j = 0; j < uniforms.length; j ++ ) {
  30040. this.uniforms.push( uniforms[ j ].clone() );
  30041. }
  30042. }
  30043. return this;
  30044. }
  30045. clone() {
  30046. return new this.constructor().copy( this );
  30047. }
  30048. }
  30049. class InstancedInterleavedBuffer extends InterleavedBuffer {
  30050. constructor( array, stride, meshPerAttribute = 1 ) {
  30051. super( array, stride );
  30052. this.isInstancedInterleavedBuffer = true;
  30053. this.meshPerAttribute = meshPerAttribute;
  30054. }
  30055. copy( source ) {
  30056. super.copy( source );
  30057. this.meshPerAttribute = source.meshPerAttribute;
  30058. return this;
  30059. }
  30060. clone( data ) {
  30061. const ib = super.clone( data );
  30062. ib.meshPerAttribute = this.meshPerAttribute;
  30063. return ib;
  30064. }
  30065. toJSON( data ) {
  30066. const json = super.toJSON( data );
  30067. json.isInstancedInterleavedBuffer = true;
  30068. json.meshPerAttribute = this.meshPerAttribute;
  30069. return json;
  30070. }
  30071. }
  30072. class GLBufferAttribute {
  30073. constructor( buffer, type, itemSize, elementSize, count ) {
  30074. this.isGLBufferAttribute = true;
  30075. this.name = '';
  30076. this.buffer = buffer;
  30077. this.type = type;
  30078. this.itemSize = itemSize;
  30079. this.elementSize = elementSize;
  30080. this.count = count;
  30081. this.version = 0;
  30082. }
  30083. set needsUpdate( value ) {
  30084. if ( value === true ) this.version ++;
  30085. }
  30086. setBuffer( buffer ) {
  30087. this.buffer = buffer;
  30088. return this;
  30089. }
  30090. setType( type, elementSize ) {
  30091. this.type = type;
  30092. this.elementSize = elementSize;
  30093. return this;
  30094. }
  30095. setItemSize( itemSize ) {
  30096. this.itemSize = itemSize;
  30097. return this;
  30098. }
  30099. setCount( count ) {
  30100. this.count = count;
  30101. return this;
  30102. }
  30103. }
  30104. class Raycaster {
  30105. constructor( origin, direction, near = 0, far = Infinity ) {
  30106. this.ray = new Ray( origin, direction );
  30107. // direction is assumed to be normalized (for accurate distance calculations)
  30108. this.near = near;
  30109. this.far = far;
  30110. this.camera = null;
  30111. this.layers = new Layers();
  30112. this.params = {
  30113. Mesh: {},
  30114. Line: { threshold: 1 },
  30115. LOD: {},
  30116. Points: { threshold: 1 },
  30117. Sprite: {}
  30118. };
  30119. }
  30120. set( origin, direction ) {
  30121. // direction is assumed to be normalized (for accurate distance calculations)
  30122. this.ray.set( origin, direction );
  30123. }
  30124. setFromCamera( coords, camera ) {
  30125. if ( camera.isPerspectiveCamera ) {
  30126. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30127. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30128. this.camera = camera;
  30129. } else if ( camera.isOrthographicCamera ) {
  30130. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30131. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30132. this.camera = camera;
  30133. } else {
  30134. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30135. }
  30136. }
  30137. intersectObject( object, recursive = true, intersects = [] ) {
  30138. intersectObject( object, this, intersects, recursive );
  30139. intersects.sort( ascSort );
  30140. return intersects;
  30141. }
  30142. intersectObjects( objects, recursive = true, intersects = [] ) {
  30143. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30144. intersectObject( objects[ i ], this, intersects, recursive );
  30145. }
  30146. intersects.sort( ascSort );
  30147. return intersects;
  30148. }
  30149. }
  30150. function ascSort( a, b ) {
  30151. return a.distance - b.distance;
  30152. }
  30153. function intersectObject( object, raycaster, intersects, recursive ) {
  30154. if ( object.layers.test( raycaster.layers ) ) {
  30155. object.raycast( raycaster, intersects );
  30156. }
  30157. if ( recursive === true ) {
  30158. const children = object.children;
  30159. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30160. intersectObject( children[ i ], raycaster, intersects, true );
  30161. }
  30162. }
  30163. }
  30164. /**
  30165. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30166. *
  30167. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  30168. * The azimuthal angle (theta) is measured from the positive z-axis.
  30169. */
  30170. class Spherical {
  30171. constructor( radius = 1, phi = 0, theta = 0 ) {
  30172. this.radius = radius;
  30173. this.phi = phi; // polar angle
  30174. this.theta = theta; // azimuthal angle
  30175. return this;
  30176. }
  30177. set( radius, phi, theta ) {
  30178. this.radius = radius;
  30179. this.phi = phi;
  30180. this.theta = theta;
  30181. return this;
  30182. }
  30183. copy( other ) {
  30184. this.radius = other.radius;
  30185. this.phi = other.phi;
  30186. this.theta = other.theta;
  30187. return this;
  30188. }
  30189. // restrict phi to be between EPS and PI-EPS
  30190. makeSafe() {
  30191. const EPS = 0.000001;
  30192. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30193. return this;
  30194. }
  30195. setFromVector3( v ) {
  30196. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30197. }
  30198. setFromCartesianCoords( x, y, z ) {
  30199. this.radius = Math.sqrt( x * x + y * y + z * z );
  30200. if ( this.radius === 0 ) {
  30201. this.theta = 0;
  30202. this.phi = 0;
  30203. } else {
  30204. this.theta = Math.atan2( x, z );
  30205. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  30206. }
  30207. return this;
  30208. }
  30209. clone() {
  30210. return new this.constructor().copy( this );
  30211. }
  30212. }
  30213. /**
  30214. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30215. */
  30216. class Cylindrical {
  30217. constructor( radius = 1, theta = 0, y = 0 ) {
  30218. this.radius = radius; // distance from the origin to a point in the x-z plane
  30219. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30220. this.y = y; // height above the x-z plane
  30221. return this;
  30222. }
  30223. set( radius, theta, y ) {
  30224. this.radius = radius;
  30225. this.theta = theta;
  30226. this.y = y;
  30227. return this;
  30228. }
  30229. copy( other ) {
  30230. this.radius = other.radius;
  30231. this.theta = other.theta;
  30232. this.y = other.y;
  30233. return this;
  30234. }
  30235. setFromVector3( v ) {
  30236. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30237. }
  30238. setFromCartesianCoords( x, y, z ) {
  30239. this.radius = Math.sqrt( x * x + z * z );
  30240. this.theta = Math.atan2( x, z );
  30241. this.y = y;
  30242. return this;
  30243. }
  30244. clone() {
  30245. return new this.constructor().copy( this );
  30246. }
  30247. }
  30248. const _vector$4 = /*@__PURE__*/ new Vector2();
  30249. class Box2 {
  30250. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  30251. this.isBox2 = true;
  30252. this.min = min;
  30253. this.max = max;
  30254. }
  30255. set( min, max ) {
  30256. this.min.copy( min );
  30257. this.max.copy( max );
  30258. return this;
  30259. }
  30260. setFromPoints( points ) {
  30261. this.makeEmpty();
  30262. for ( let i = 0, il = points.length; i < il; i ++ ) {
  30263. this.expandByPoint( points[ i ] );
  30264. }
  30265. return this;
  30266. }
  30267. setFromCenterAndSize( center, size ) {
  30268. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  30269. this.min.copy( center ).sub( halfSize );
  30270. this.max.copy( center ).add( halfSize );
  30271. return this;
  30272. }
  30273. clone() {
  30274. return new this.constructor().copy( this );
  30275. }
  30276. copy( box ) {
  30277. this.min.copy( box.min );
  30278. this.max.copy( box.max );
  30279. return this;
  30280. }
  30281. makeEmpty() {
  30282. this.min.x = this.min.y = + Infinity;
  30283. this.max.x = this.max.y = - Infinity;
  30284. return this;
  30285. }
  30286. isEmpty() {
  30287. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30288. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30289. }
  30290. getCenter( target ) {
  30291. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30292. }
  30293. getSize( target ) {
  30294. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30295. }
  30296. expandByPoint( point ) {
  30297. this.min.min( point );
  30298. this.max.max( point );
  30299. return this;
  30300. }
  30301. expandByVector( vector ) {
  30302. this.min.sub( vector );
  30303. this.max.add( vector );
  30304. return this;
  30305. }
  30306. expandByScalar( scalar ) {
  30307. this.min.addScalar( - scalar );
  30308. this.max.addScalar( scalar );
  30309. return this;
  30310. }
  30311. containsPoint( point ) {
  30312. return point.x < this.min.x || point.x > this.max.x ||
  30313. point.y < this.min.y || point.y > this.max.y ? false : true;
  30314. }
  30315. containsBox( box ) {
  30316. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30317. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30318. }
  30319. getParameter( point, target ) {
  30320. // This can potentially have a divide by zero if the box
  30321. // has a size dimension of 0.
  30322. return target.set(
  30323. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30324. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30325. );
  30326. }
  30327. intersectsBox( box ) {
  30328. // using 4 splitting planes to rule out intersections
  30329. return box.max.x < this.min.x || box.min.x > this.max.x ||
  30330. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  30331. }
  30332. clampPoint( point, target ) {
  30333. return target.copy( point ).clamp( this.min, this.max );
  30334. }
  30335. distanceToPoint( point ) {
  30336. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  30337. }
  30338. intersect( box ) {
  30339. this.min.max( box.min );
  30340. this.max.min( box.max );
  30341. if ( this.isEmpty() ) this.makeEmpty();
  30342. return this;
  30343. }
  30344. union( box ) {
  30345. this.min.min( box.min );
  30346. this.max.max( box.max );
  30347. return this;
  30348. }
  30349. translate( offset ) {
  30350. this.min.add( offset );
  30351. this.max.add( offset );
  30352. return this;
  30353. }
  30354. equals( box ) {
  30355. return box.min.equals( this.min ) && box.max.equals( this.max );
  30356. }
  30357. }
  30358. const _startP = /*@__PURE__*/ new Vector3();
  30359. const _startEnd = /*@__PURE__*/ new Vector3();
  30360. class Line3 {
  30361. constructor( start = new Vector3(), end = new Vector3() ) {
  30362. this.start = start;
  30363. this.end = end;
  30364. }
  30365. set( start, end ) {
  30366. this.start.copy( start );
  30367. this.end.copy( end );
  30368. return this;
  30369. }
  30370. copy( line ) {
  30371. this.start.copy( line.start );
  30372. this.end.copy( line.end );
  30373. return this;
  30374. }
  30375. getCenter( target ) {
  30376. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30377. }
  30378. delta( target ) {
  30379. return target.subVectors( this.end, this.start );
  30380. }
  30381. distanceSq() {
  30382. return this.start.distanceToSquared( this.end );
  30383. }
  30384. distance() {
  30385. return this.start.distanceTo( this.end );
  30386. }
  30387. at( t, target ) {
  30388. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30389. }
  30390. closestPointToPointParameter( point, clampToLine ) {
  30391. _startP.subVectors( point, this.start );
  30392. _startEnd.subVectors( this.end, this.start );
  30393. const startEnd2 = _startEnd.dot( _startEnd );
  30394. const startEnd_startP = _startEnd.dot( _startP );
  30395. let t = startEnd_startP / startEnd2;
  30396. if ( clampToLine ) {
  30397. t = clamp( t, 0, 1 );
  30398. }
  30399. return t;
  30400. }
  30401. closestPointToPoint( point, clampToLine, target ) {
  30402. const t = this.closestPointToPointParameter( point, clampToLine );
  30403. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30404. }
  30405. applyMatrix4( matrix ) {
  30406. this.start.applyMatrix4( matrix );
  30407. this.end.applyMatrix4( matrix );
  30408. return this;
  30409. }
  30410. equals( line ) {
  30411. return line.start.equals( this.start ) && line.end.equals( this.end );
  30412. }
  30413. clone() {
  30414. return new this.constructor().copy( this );
  30415. }
  30416. }
  30417. const _vector$3 = /*@__PURE__*/ new Vector3();
  30418. class SpotLightHelper extends Object3D {
  30419. constructor( light, color ) {
  30420. super();
  30421. this.light = light;
  30422. this.matrix = light.matrixWorld;
  30423. this.matrixAutoUpdate = false;
  30424. this.color = color;
  30425. this.type = 'SpotLightHelper';
  30426. const geometry = new BufferGeometry();
  30427. const positions = [
  30428. 0, 0, 0, 0, 0, 1,
  30429. 0, 0, 0, 1, 0, 1,
  30430. 0, 0, 0, - 1, 0, 1,
  30431. 0, 0, 0, 0, 1, 1,
  30432. 0, 0, 0, 0, - 1, 1
  30433. ];
  30434. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30435. const p1 = ( i / l ) * Math.PI * 2;
  30436. const p2 = ( j / l ) * Math.PI * 2;
  30437. positions.push(
  30438. Math.cos( p1 ), Math.sin( p1 ), 1,
  30439. Math.cos( p2 ), Math.sin( p2 ), 1
  30440. );
  30441. }
  30442. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30443. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30444. this.cone = new LineSegments( geometry, material );
  30445. this.add( this.cone );
  30446. this.update();
  30447. }
  30448. dispose() {
  30449. this.cone.geometry.dispose();
  30450. this.cone.material.dispose();
  30451. }
  30452. update() {
  30453. this.light.updateWorldMatrix( true, false );
  30454. this.light.target.updateWorldMatrix( true, false );
  30455. const coneLength = this.light.distance ? this.light.distance : 1000;
  30456. const coneWidth = coneLength * Math.tan( this.light.angle );
  30457. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30458. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  30459. this.cone.lookAt( _vector$3 );
  30460. if ( this.color !== undefined ) {
  30461. this.cone.material.color.set( this.color );
  30462. } else {
  30463. this.cone.material.color.copy( this.light.color );
  30464. }
  30465. }
  30466. }
  30467. const _vector$2 = /*@__PURE__*/ new Vector3();
  30468. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  30469. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  30470. class SkeletonHelper extends LineSegments {
  30471. constructor( object ) {
  30472. const bones = getBoneList( object );
  30473. const geometry = new BufferGeometry();
  30474. const vertices = [];
  30475. const colors = [];
  30476. const color1 = new Color( 0, 0, 1 );
  30477. const color2 = new Color( 0, 1, 0 );
  30478. for ( let i = 0; i < bones.length; i ++ ) {
  30479. const bone = bones[ i ];
  30480. if ( bone.parent && bone.parent.isBone ) {
  30481. vertices.push( 0, 0, 0 );
  30482. vertices.push( 0, 0, 0 );
  30483. colors.push( color1.r, color1.g, color1.b );
  30484. colors.push( color2.r, color2.g, color2.b );
  30485. }
  30486. }
  30487. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30488. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30489. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  30490. super( geometry, material );
  30491. this.isSkeletonHelper = true;
  30492. this.type = 'SkeletonHelper';
  30493. this.root = object;
  30494. this.bones = bones;
  30495. this.matrix = object.matrixWorld;
  30496. this.matrixAutoUpdate = false;
  30497. }
  30498. updateMatrixWorld( force ) {
  30499. const bones = this.bones;
  30500. const geometry = this.geometry;
  30501. const position = geometry.getAttribute( 'position' );
  30502. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  30503. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  30504. const bone = bones[ i ];
  30505. if ( bone.parent && bone.parent.isBone ) {
  30506. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  30507. _vector$2.setFromMatrixPosition( _boneMatrix );
  30508. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  30509. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  30510. _vector$2.setFromMatrixPosition( _boneMatrix );
  30511. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  30512. j += 2;
  30513. }
  30514. }
  30515. geometry.getAttribute( 'position' ).needsUpdate = true;
  30516. super.updateMatrixWorld( force );
  30517. }
  30518. dispose() {
  30519. this.geometry.dispose();
  30520. this.material.dispose();
  30521. }
  30522. }
  30523. function getBoneList( object ) {
  30524. const boneList = [];
  30525. if ( object.isBone === true ) {
  30526. boneList.push( object );
  30527. }
  30528. for ( let i = 0; i < object.children.length; i ++ ) {
  30529. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  30530. }
  30531. return boneList;
  30532. }
  30533. class PointLightHelper extends Mesh {
  30534. constructor( light, sphereSize, color ) {
  30535. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  30536. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30537. super( geometry, material );
  30538. this.light = light;
  30539. this.color = color;
  30540. this.type = 'PointLightHelper';
  30541. this.matrix = this.light.matrixWorld;
  30542. this.matrixAutoUpdate = false;
  30543. this.update();
  30544. /*
  30545. // TODO: delete this comment?
  30546. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  30547. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30548. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30549. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30550. const d = light.distance;
  30551. if ( d === 0.0 ) {
  30552. this.lightDistance.visible = false;
  30553. } else {
  30554. this.lightDistance.scale.set( d, d, d );
  30555. }
  30556. this.add( this.lightDistance );
  30557. */
  30558. }
  30559. dispose() {
  30560. this.geometry.dispose();
  30561. this.material.dispose();
  30562. }
  30563. update() {
  30564. this.light.updateWorldMatrix( true, false );
  30565. if ( this.color !== undefined ) {
  30566. this.material.color.set( this.color );
  30567. } else {
  30568. this.material.color.copy( this.light.color );
  30569. }
  30570. /*
  30571. const d = this.light.distance;
  30572. if ( d === 0.0 ) {
  30573. this.lightDistance.visible = false;
  30574. } else {
  30575. this.lightDistance.visible = true;
  30576. this.lightDistance.scale.set( d, d, d );
  30577. }
  30578. */
  30579. }
  30580. }
  30581. const _vector$1 = /*@__PURE__*/ new Vector3();
  30582. const _color1 = /*@__PURE__*/ new Color();
  30583. const _color2 = /*@__PURE__*/ new Color();
  30584. class HemisphereLightHelper extends Object3D {
  30585. constructor( light, size, color ) {
  30586. super();
  30587. this.light = light;
  30588. this.matrix = light.matrixWorld;
  30589. this.matrixAutoUpdate = false;
  30590. this.color = color;
  30591. this.type = 'HemisphereLightHelper';
  30592. const geometry = new OctahedronGeometry( size );
  30593. geometry.rotateY( Math.PI * 0.5 );
  30594. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30595. if ( this.color === undefined ) this.material.vertexColors = true;
  30596. const position = geometry.getAttribute( 'position' );
  30597. const colors = new Float32Array( position.count * 3 );
  30598. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30599. this.add( new Mesh( geometry, this.material ) );
  30600. this.update();
  30601. }
  30602. dispose() {
  30603. this.children[ 0 ].geometry.dispose();
  30604. this.children[ 0 ].material.dispose();
  30605. }
  30606. update() {
  30607. const mesh = this.children[ 0 ];
  30608. if ( this.color !== undefined ) {
  30609. this.material.color.set( this.color );
  30610. } else {
  30611. const colors = mesh.geometry.getAttribute( 'color' );
  30612. _color1.copy( this.light.color );
  30613. _color2.copy( this.light.groundColor );
  30614. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  30615. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  30616. colors.setXYZ( i, color.r, color.g, color.b );
  30617. }
  30618. colors.needsUpdate = true;
  30619. }
  30620. this.light.updateWorldMatrix( true, false );
  30621. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30622. }
  30623. }
  30624. class GridHelper extends LineSegments {
  30625. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  30626. color1 = new Color( color1 );
  30627. color2 = new Color( color2 );
  30628. const center = divisions / 2;
  30629. const step = size / divisions;
  30630. const halfSize = size / 2;
  30631. const vertices = [], colors = [];
  30632. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30633. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30634. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30635. const color = i === center ? color1 : color2;
  30636. color.toArray( colors, j ); j += 3;
  30637. color.toArray( colors, j ); j += 3;
  30638. color.toArray( colors, j ); j += 3;
  30639. color.toArray( colors, j ); j += 3;
  30640. }
  30641. const geometry = new BufferGeometry();
  30642. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30643. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30644. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30645. super( geometry, material );
  30646. this.type = 'GridHelper';
  30647. }
  30648. dispose() {
  30649. this.geometry.dispose();
  30650. this.material.dispose();
  30651. }
  30652. }
  30653. class PolarGridHelper extends LineSegments {
  30654. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  30655. color1 = new Color( color1 );
  30656. color2 = new Color( color2 );
  30657. const vertices = [];
  30658. const colors = [];
  30659. // create the sectors
  30660. if ( sectors > 1 ) {
  30661. for ( let i = 0; i < sectors; i ++ ) {
  30662. const v = ( i / sectors ) * ( Math.PI * 2 );
  30663. const x = Math.sin( v ) * radius;
  30664. const z = Math.cos( v ) * radius;
  30665. vertices.push( 0, 0, 0 );
  30666. vertices.push( x, 0, z );
  30667. const color = ( i & 1 ) ? color1 : color2;
  30668. colors.push( color.r, color.g, color.b );
  30669. colors.push( color.r, color.g, color.b );
  30670. }
  30671. }
  30672. // create the rings
  30673. for ( let i = 0; i < rings; i ++ ) {
  30674. const color = ( i & 1 ) ? color1 : color2;
  30675. const r = radius - ( radius / rings * i );
  30676. for ( let j = 0; j < divisions; j ++ ) {
  30677. // first vertex
  30678. let v = ( j / divisions ) * ( Math.PI * 2 );
  30679. let x = Math.sin( v ) * r;
  30680. let z = Math.cos( v ) * r;
  30681. vertices.push( x, 0, z );
  30682. colors.push( color.r, color.g, color.b );
  30683. // second vertex
  30684. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30685. x = Math.sin( v ) * r;
  30686. z = Math.cos( v ) * r;
  30687. vertices.push( x, 0, z );
  30688. colors.push( color.r, color.g, color.b );
  30689. }
  30690. }
  30691. const geometry = new BufferGeometry();
  30692. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30693. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30694. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30695. super( geometry, material );
  30696. this.type = 'PolarGridHelper';
  30697. }
  30698. dispose() {
  30699. this.geometry.dispose();
  30700. this.material.dispose();
  30701. }
  30702. }
  30703. const _v1 = /*@__PURE__*/ new Vector3();
  30704. const _v2 = /*@__PURE__*/ new Vector3();
  30705. const _v3 = /*@__PURE__*/ new Vector3();
  30706. class DirectionalLightHelper extends Object3D {
  30707. constructor( light, size, color ) {
  30708. super();
  30709. this.light = light;
  30710. this.matrix = light.matrixWorld;
  30711. this.matrixAutoUpdate = false;
  30712. this.color = color;
  30713. this.type = 'DirectionalLightHelper';
  30714. if ( size === undefined ) size = 1;
  30715. let geometry = new BufferGeometry();
  30716. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  30717. - size, size, 0,
  30718. size, size, 0,
  30719. size, - size, 0,
  30720. - size, - size, 0,
  30721. - size, size, 0
  30722. ], 3 ) );
  30723. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30724. this.lightPlane = new Line( geometry, material );
  30725. this.add( this.lightPlane );
  30726. geometry = new BufferGeometry();
  30727. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30728. this.targetLine = new Line( geometry, material );
  30729. this.add( this.targetLine );
  30730. this.update();
  30731. }
  30732. dispose() {
  30733. this.lightPlane.geometry.dispose();
  30734. this.lightPlane.material.dispose();
  30735. this.targetLine.geometry.dispose();
  30736. this.targetLine.material.dispose();
  30737. }
  30738. update() {
  30739. this.light.updateWorldMatrix( true, false );
  30740. this.light.target.updateWorldMatrix( true, false );
  30741. _v1.setFromMatrixPosition( this.light.matrixWorld );
  30742. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30743. _v3.subVectors( _v2, _v1 );
  30744. this.lightPlane.lookAt( _v2 );
  30745. if ( this.color !== undefined ) {
  30746. this.lightPlane.material.color.set( this.color );
  30747. this.targetLine.material.color.set( this.color );
  30748. } else {
  30749. this.lightPlane.material.color.copy( this.light.color );
  30750. this.targetLine.material.color.copy( this.light.color );
  30751. }
  30752. this.targetLine.lookAt( _v2 );
  30753. this.targetLine.scale.z = _v3.length();
  30754. }
  30755. }
  30756. const _vector = /*@__PURE__*/ new Vector3();
  30757. const _camera = /*@__PURE__*/ new Camera();
  30758. /**
  30759. * - shows frustum, line of sight and up of the camera
  30760. * - suitable for fast updates
  30761. * - based on frustum visualization in lightgl.js shadowmap example
  30762. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  30763. */
  30764. class CameraHelper extends LineSegments {
  30765. constructor( camera ) {
  30766. const geometry = new BufferGeometry();
  30767. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  30768. const vertices = [];
  30769. const colors = [];
  30770. const pointMap = {};
  30771. // near
  30772. addLine( 'n1', 'n2' );
  30773. addLine( 'n2', 'n4' );
  30774. addLine( 'n4', 'n3' );
  30775. addLine( 'n3', 'n1' );
  30776. // far
  30777. addLine( 'f1', 'f2' );
  30778. addLine( 'f2', 'f4' );
  30779. addLine( 'f4', 'f3' );
  30780. addLine( 'f3', 'f1' );
  30781. // sides
  30782. addLine( 'n1', 'f1' );
  30783. addLine( 'n2', 'f2' );
  30784. addLine( 'n3', 'f3' );
  30785. addLine( 'n4', 'f4' );
  30786. // cone
  30787. addLine( 'p', 'n1' );
  30788. addLine( 'p', 'n2' );
  30789. addLine( 'p', 'n3' );
  30790. addLine( 'p', 'n4' );
  30791. // up
  30792. addLine( 'u1', 'u2' );
  30793. addLine( 'u2', 'u3' );
  30794. addLine( 'u3', 'u1' );
  30795. // target
  30796. addLine( 'c', 't' );
  30797. addLine( 'p', 'c' );
  30798. // cross
  30799. addLine( 'cn1', 'cn2' );
  30800. addLine( 'cn3', 'cn4' );
  30801. addLine( 'cf1', 'cf2' );
  30802. addLine( 'cf3', 'cf4' );
  30803. function addLine( a, b ) {
  30804. addPoint( a );
  30805. addPoint( b );
  30806. }
  30807. function addPoint( id ) {
  30808. vertices.push( 0, 0, 0 );
  30809. colors.push( 0, 0, 0 );
  30810. if ( pointMap[ id ] === undefined ) {
  30811. pointMap[ id ] = [];
  30812. }
  30813. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30814. }
  30815. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30816. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30817. super( geometry, material );
  30818. this.type = 'CameraHelper';
  30819. this.camera = camera;
  30820. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30821. this.matrix = camera.matrixWorld;
  30822. this.matrixAutoUpdate = false;
  30823. this.pointMap = pointMap;
  30824. this.update();
  30825. // colors
  30826. const colorFrustum = new Color( 0xffaa00 );
  30827. const colorCone = new Color( 0xff0000 );
  30828. const colorUp = new Color( 0x00aaff );
  30829. const colorTarget = new Color( 0xffffff );
  30830. const colorCross = new Color( 0x333333 );
  30831. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  30832. }
  30833. setColors( frustum, cone, up, target, cross ) {
  30834. const geometry = this.geometry;
  30835. const colorAttribute = geometry.getAttribute( 'color' );
  30836. // near
  30837. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  30838. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  30839. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  30840. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  30841. // far
  30842. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  30843. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  30844. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  30845. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  30846. // sides
  30847. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  30848. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  30849. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  30850. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  30851. // cone
  30852. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  30853. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  30854. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  30855. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  30856. // up
  30857. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  30858. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  30859. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  30860. // target
  30861. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  30862. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  30863. // cross
  30864. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  30865. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  30866. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  30867. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  30868. colorAttribute.needsUpdate = true;
  30869. }
  30870. update() {
  30871. const geometry = this.geometry;
  30872. const pointMap = this.pointMap;
  30873. const w = 1, h = 1;
  30874. // we need just camera projection matrix inverse
  30875. // world matrix must be identity
  30876. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  30877. // center / target
  30878. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  30879. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  30880. // near
  30881. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  30882. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  30883. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  30884. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  30885. // far
  30886. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  30887. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  30888. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  30889. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  30890. // up
  30891. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  30892. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  30893. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  30894. // cross
  30895. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  30896. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  30897. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  30898. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  30899. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  30900. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  30901. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  30902. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  30903. geometry.getAttribute( 'position' ).needsUpdate = true;
  30904. }
  30905. dispose() {
  30906. this.geometry.dispose();
  30907. this.material.dispose();
  30908. }
  30909. }
  30910. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  30911. _vector.set( x, y, z ).unproject( camera );
  30912. const points = pointMap[ point ];
  30913. if ( points !== undefined ) {
  30914. const position = geometry.getAttribute( 'position' );
  30915. for ( let i = 0, l = points.length; i < l; i ++ ) {
  30916. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  30917. }
  30918. }
  30919. }
  30920. const _box = /*@__PURE__*/ new Box3();
  30921. class BoxHelper extends LineSegments {
  30922. constructor( object, color = 0xffff00 ) {
  30923. 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 ] );
  30924. const positions = new Float32Array( 8 * 3 );
  30925. const geometry = new BufferGeometry();
  30926. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30927. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  30928. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30929. this.object = object;
  30930. this.type = 'BoxHelper';
  30931. this.matrixAutoUpdate = false;
  30932. this.update();
  30933. }
  30934. update( object ) {
  30935. if ( object !== undefined ) {
  30936. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  30937. }
  30938. if ( this.object !== undefined ) {
  30939. _box.setFromObject( this.object );
  30940. }
  30941. if ( _box.isEmpty() ) return;
  30942. const min = _box.min;
  30943. const max = _box.max;
  30944. /*
  30945. 5____4
  30946. 1/___0/|
  30947. | 6__|_7
  30948. 2/___3/
  30949. 0: max.x, max.y, max.z
  30950. 1: min.x, max.y, max.z
  30951. 2: min.x, min.y, max.z
  30952. 3: max.x, min.y, max.z
  30953. 4: max.x, max.y, min.z
  30954. 5: min.x, max.y, min.z
  30955. 6: min.x, min.y, min.z
  30956. 7: max.x, min.y, min.z
  30957. */
  30958. const position = this.geometry.attributes.position;
  30959. const array = position.array;
  30960. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  30961. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  30962. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  30963. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  30964. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  30965. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  30966. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  30967. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  30968. position.needsUpdate = true;
  30969. this.geometry.computeBoundingSphere();
  30970. }
  30971. setFromObject( object ) {
  30972. this.object = object;
  30973. this.update();
  30974. return this;
  30975. }
  30976. copy( source, recursive ) {
  30977. super.copy( source, recursive );
  30978. this.object = source.object;
  30979. return this;
  30980. }
  30981. dispose() {
  30982. this.geometry.dispose();
  30983. this.material.dispose();
  30984. }
  30985. }
  30986. class Box3Helper extends LineSegments {
  30987. constructor( box, color = 0xffff00 ) {
  30988. 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 ] );
  30989. 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 ];
  30990. const geometry = new BufferGeometry();
  30991. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30992. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30993. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30994. this.box = box;
  30995. this.type = 'Box3Helper';
  30996. this.geometry.computeBoundingSphere();
  30997. }
  30998. updateMatrixWorld( force ) {
  30999. const box = this.box;
  31000. if ( box.isEmpty() ) return;
  31001. box.getCenter( this.position );
  31002. box.getSize( this.scale );
  31003. this.scale.multiplyScalar( 0.5 );
  31004. super.updateMatrixWorld( force );
  31005. }
  31006. dispose() {
  31007. this.geometry.dispose();
  31008. this.material.dispose();
  31009. }
  31010. }
  31011. class PlaneHelper extends Line {
  31012. constructor( plane, size = 1, hex = 0xffff00 ) {
  31013. const color = hex;
  31014. 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 ];
  31015. const geometry = new BufferGeometry();
  31016. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31017. geometry.computeBoundingSphere();
  31018. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31019. this.type = 'PlaneHelper';
  31020. this.plane = plane;
  31021. this.size = size;
  31022. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  31023. const geometry2 = new BufferGeometry();
  31024. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31025. geometry2.computeBoundingSphere();
  31026. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  31027. }
  31028. updateMatrixWorld( force ) {
  31029. this.position.set( 0, 0, 0 );
  31030. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  31031. this.lookAt( this.plane.normal );
  31032. this.translateZ( - this.plane.constant );
  31033. super.updateMatrixWorld( force );
  31034. }
  31035. dispose() {
  31036. this.geometry.dispose();
  31037. this.material.dispose();
  31038. this.children[ 0 ].geometry.dispose();
  31039. this.children[ 0 ].material.dispose();
  31040. }
  31041. }
  31042. const _axis = /*@__PURE__*/ new Vector3();
  31043. let _lineGeometry, _coneGeometry;
  31044. class ArrowHelper extends Object3D {
  31045. // dir is assumed to be normalized
  31046. 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 ) {
  31047. super();
  31048. this.type = 'ArrowHelper';
  31049. if ( _lineGeometry === undefined ) {
  31050. _lineGeometry = new BufferGeometry();
  31051. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  31052. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  31053. _coneGeometry.translate( 0, - 0.5, 0 );
  31054. }
  31055. this.position.copy( origin );
  31056. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31057. this.line.matrixAutoUpdate = false;
  31058. this.add( this.line );
  31059. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  31060. this.cone.matrixAutoUpdate = false;
  31061. this.add( this.cone );
  31062. this.setDirection( dir );
  31063. this.setLength( length, headLength, headWidth );
  31064. }
  31065. setDirection( dir ) {
  31066. // dir is assumed to be normalized
  31067. if ( dir.y > 0.99999 ) {
  31068. this.quaternion.set( 0, 0, 0, 1 );
  31069. } else if ( dir.y < - 0.99999 ) {
  31070. this.quaternion.set( 1, 0, 0, 0 );
  31071. } else {
  31072. _axis.set( dir.z, 0, - dir.x ).normalize();
  31073. const radians = Math.acos( dir.y );
  31074. this.quaternion.setFromAxisAngle( _axis, radians );
  31075. }
  31076. }
  31077. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  31078. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  31079. this.line.updateMatrix();
  31080. this.cone.scale.set( headWidth, headLength, headWidth );
  31081. this.cone.position.y = length;
  31082. this.cone.updateMatrix();
  31083. }
  31084. setColor( color ) {
  31085. this.line.material.color.set( color );
  31086. this.cone.material.color.set( color );
  31087. }
  31088. copy( source ) {
  31089. super.copy( source, false );
  31090. this.line.copy( source.line );
  31091. this.cone.copy( source.cone );
  31092. return this;
  31093. }
  31094. dispose() {
  31095. this.line.geometry.dispose();
  31096. this.line.material.dispose();
  31097. this.cone.geometry.dispose();
  31098. this.cone.material.dispose();
  31099. }
  31100. }
  31101. class AxesHelper extends LineSegments {
  31102. constructor( size = 1 ) {
  31103. const vertices = [
  31104. 0, 0, 0, size, 0, 0,
  31105. 0, 0, 0, 0, size, 0,
  31106. 0, 0, 0, 0, 0, size
  31107. ];
  31108. const colors = [
  31109. 1, 0, 0, 1, 0.6, 0,
  31110. 0, 1, 0, 0.6, 1, 0,
  31111. 0, 0, 1, 0, 0.6, 1
  31112. ];
  31113. const geometry = new BufferGeometry();
  31114. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31115. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31116. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31117. super( geometry, material );
  31118. this.type = 'AxesHelper';
  31119. }
  31120. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  31121. const color = new Color();
  31122. const array = this.geometry.attributes.color.array;
  31123. color.set( xAxisColor );
  31124. color.toArray( array, 0 );
  31125. color.toArray( array, 3 );
  31126. color.set( yAxisColor );
  31127. color.toArray( array, 6 );
  31128. color.toArray( array, 9 );
  31129. color.set( zAxisColor );
  31130. color.toArray( array, 12 );
  31131. color.toArray( array, 15 );
  31132. this.geometry.attributes.color.needsUpdate = true;
  31133. return this;
  31134. }
  31135. dispose() {
  31136. this.geometry.dispose();
  31137. this.material.dispose();
  31138. }
  31139. }
  31140. class ShapePath {
  31141. constructor() {
  31142. this.type = 'ShapePath';
  31143. this.color = new Color();
  31144. this.subPaths = [];
  31145. this.currentPath = null;
  31146. }
  31147. moveTo( x, y ) {
  31148. this.currentPath = new Path();
  31149. this.subPaths.push( this.currentPath );
  31150. this.currentPath.moveTo( x, y );
  31151. return this;
  31152. }
  31153. lineTo( x, y ) {
  31154. this.currentPath.lineTo( x, y );
  31155. return this;
  31156. }
  31157. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  31158. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  31159. return this;
  31160. }
  31161. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  31162. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  31163. return this;
  31164. }
  31165. splineThru( pts ) {
  31166. this.currentPath.splineThru( pts );
  31167. return this;
  31168. }
  31169. toShapes( isCCW ) {
  31170. function toShapesNoHoles( inSubpaths ) {
  31171. const shapes = [];
  31172. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  31173. const tmpPath = inSubpaths[ i ];
  31174. const tmpShape = new Shape();
  31175. tmpShape.curves = tmpPath.curves;
  31176. shapes.push( tmpShape );
  31177. }
  31178. return shapes;
  31179. }
  31180. function isPointInsidePolygon( inPt, inPolygon ) {
  31181. const polyLen = inPolygon.length;
  31182. // inPt on polygon contour => immediate success or
  31183. // toggling of inside/outside at every single! intersection point of an edge
  31184. // with the horizontal line through inPt, left of inPt
  31185. // not counting lowerY endpoints of edges and whole edges on that line
  31186. let inside = false;
  31187. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  31188. let edgeLowPt = inPolygon[ p ];
  31189. let edgeHighPt = inPolygon[ q ];
  31190. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  31191. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  31192. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  31193. // not parallel
  31194. if ( edgeDy < 0 ) {
  31195. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  31196. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  31197. }
  31198. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  31199. if ( inPt.y === edgeLowPt.y ) {
  31200. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  31201. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31202. } else {
  31203. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  31204. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  31205. if ( perpEdge < 0 ) continue;
  31206. inside = ! inside; // true intersection left of inPt
  31207. }
  31208. } else {
  31209. // parallel or collinear
  31210. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  31211. // edge lies on the same horizontal line as inPt
  31212. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  31213. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  31214. // continue;
  31215. }
  31216. }
  31217. return inside;
  31218. }
  31219. const isClockWise = ShapeUtils.isClockWise;
  31220. const subPaths = this.subPaths;
  31221. if ( subPaths.length === 0 ) return [];
  31222. let solid, tmpPath, tmpShape;
  31223. const shapes = [];
  31224. if ( subPaths.length === 1 ) {
  31225. tmpPath = subPaths[ 0 ];
  31226. tmpShape = new Shape();
  31227. tmpShape.curves = tmpPath.curves;
  31228. shapes.push( tmpShape );
  31229. return shapes;
  31230. }
  31231. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  31232. holesFirst = isCCW ? ! holesFirst : holesFirst;
  31233. // console.log("Holes first", holesFirst);
  31234. const betterShapeHoles = [];
  31235. const newShapes = [];
  31236. let newShapeHoles = [];
  31237. let mainIdx = 0;
  31238. let tmpPoints;
  31239. newShapes[ mainIdx ] = undefined;
  31240. newShapeHoles[ mainIdx ] = [];
  31241. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  31242. tmpPath = subPaths[ i ];
  31243. tmpPoints = tmpPath.getPoints();
  31244. solid = isClockWise( tmpPoints );
  31245. solid = isCCW ? ! solid : solid;
  31246. if ( solid ) {
  31247. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  31248. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  31249. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  31250. if ( holesFirst ) mainIdx ++;
  31251. newShapeHoles[ mainIdx ] = [];
  31252. //console.log('cw', i);
  31253. } else {
  31254. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  31255. //console.log('ccw', i);
  31256. }
  31257. }
  31258. // only Holes? -> probably all Shapes with wrong orientation
  31259. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  31260. if ( newShapes.length > 1 ) {
  31261. let ambiguous = false;
  31262. let toChange = 0;
  31263. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31264. betterShapeHoles[ sIdx ] = [];
  31265. }
  31266. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31267. const sho = newShapeHoles[ sIdx ];
  31268. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  31269. const ho = sho[ hIdx ];
  31270. let hole_unassigned = true;
  31271. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  31272. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  31273. if ( sIdx !== s2Idx ) toChange ++;
  31274. if ( hole_unassigned ) {
  31275. hole_unassigned = false;
  31276. betterShapeHoles[ s2Idx ].push( ho );
  31277. } else {
  31278. ambiguous = true;
  31279. }
  31280. }
  31281. }
  31282. if ( hole_unassigned ) {
  31283. betterShapeHoles[ sIdx ].push( ho );
  31284. }
  31285. }
  31286. }
  31287. if ( toChange > 0 && ambiguous === false ) {
  31288. newShapeHoles = betterShapeHoles;
  31289. }
  31290. }
  31291. let tmpHoles;
  31292. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  31293. tmpShape = newShapes[ i ].s;
  31294. shapes.push( tmpShape );
  31295. tmpHoles = newShapeHoles[ i ];
  31296. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  31297. tmpShape.holes.push( tmpHoles[ j ].h );
  31298. }
  31299. }
  31300. //console.log("shape", shapes);
  31301. return shapes;
  31302. }
  31303. }
  31304. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31305. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31306. revision: REVISION,
  31307. } } ) );
  31308. }
  31309. if ( typeof window !== 'undefined' ) {
  31310. if ( window.__THREE__ ) {
  31311. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  31312. } else {
  31313. window.__THREE__ = REVISION;
  31314. }
  31315. }
  31316. 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, Float64BufferAttribute, 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, LinearEncoding, 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, 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, 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, TwoPassDoubleSide, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, createCanvasElement, sRGBEncoding };