three.module.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '163dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const 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. const BasicDepthPacking = 3200;
  155. const RGBADepthPacking = 3201;
  156. const TangentSpaceNormalMap = 0;
  157. const ObjectSpaceNormalMap = 1;
  158. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  159. const NoColorSpace = '';
  160. const SRGBColorSpace = 'srgb';
  161. const LinearSRGBColorSpace = 'srgb-linear';
  162. const DisplayP3ColorSpace = 'display-p3';
  163. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  164. const LinearTransfer = 'linear';
  165. const SRGBTransfer = 'srgb';
  166. const Rec709Primaries = 'rec709';
  167. const P3Primaries = 'p3';
  168. const ZeroStencilOp = 0;
  169. const KeepStencilOp = 7680;
  170. const ReplaceStencilOp = 7681;
  171. const IncrementStencilOp = 7682;
  172. const DecrementStencilOp = 7683;
  173. const IncrementWrapStencilOp = 34055;
  174. const DecrementWrapStencilOp = 34056;
  175. const InvertStencilOp = 5386;
  176. const NeverStencilFunc = 512;
  177. const LessStencilFunc = 513;
  178. const EqualStencilFunc = 514;
  179. const LessEqualStencilFunc = 515;
  180. const GreaterStencilFunc = 516;
  181. const NotEqualStencilFunc = 517;
  182. const GreaterEqualStencilFunc = 518;
  183. const AlwaysStencilFunc = 519;
  184. const NeverCompare = 512;
  185. const LessCompare = 513;
  186. const EqualCompare = 514;
  187. const LessEqualCompare = 515;
  188. const GreaterCompare = 516;
  189. const NotEqualCompare = 517;
  190. const GreaterEqualCompare = 518;
  191. const AlwaysCompare = 519;
  192. const StaticDrawUsage = 35044;
  193. const DynamicDrawUsage = 35048;
  194. const StreamDrawUsage = 35040;
  195. const StaticReadUsage = 35045;
  196. const DynamicReadUsage = 35049;
  197. const StreamReadUsage = 35041;
  198. const StaticCopyUsage = 35046;
  199. const DynamicCopyUsage = 35050;
  200. const StreamCopyUsage = 35042;
  201. const GLSL1 = '100';
  202. const GLSL3 = '300 es';
  203. const WebGLCoordinateSystem = 2000;
  204. const WebGPUCoordinateSystem = 2001;
  205. /**
  206. * https://github.com/mrdoob/eventdispatcher.js/
  207. */
  208. class EventDispatcher {
  209. addEventListener( type, listener ) {
  210. if ( this._listeners === undefined ) this._listeners = {};
  211. const listeners = this._listeners;
  212. if ( listeners[ type ] === undefined ) {
  213. listeners[ type ] = [];
  214. }
  215. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  216. listeners[ type ].push( listener );
  217. }
  218. }
  219. hasEventListener( type, listener ) {
  220. if ( this._listeners === undefined ) return false;
  221. const listeners = this._listeners;
  222. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  223. }
  224. removeEventListener( type, listener ) {
  225. if ( this._listeners === undefined ) return;
  226. const listeners = this._listeners;
  227. const listenerArray = listeners[ type ];
  228. if ( listenerArray !== undefined ) {
  229. const index = listenerArray.indexOf( listener );
  230. if ( index !== - 1 ) {
  231. listenerArray.splice( index, 1 );
  232. }
  233. }
  234. }
  235. dispatchEvent( event ) {
  236. if ( this._listeners === undefined ) return;
  237. const listeners = this._listeners;
  238. const listenerArray = listeners[ event.type ];
  239. if ( listenerArray !== undefined ) {
  240. event.target = this;
  241. // Make a copy, in case listeners are removed while iterating.
  242. const array = listenerArray.slice( 0 );
  243. for ( let i = 0, l = array.length; i < l; i ++ ) {
  244. array[ i ].call( this, event );
  245. }
  246. event.target = null;
  247. }
  248. }
  249. }
  250. 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' ];
  251. let _seed = 1234567;
  252. const DEG2RAD = Math.PI / 180;
  253. const RAD2DEG = 180 / Math.PI;
  254. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  255. function generateUUID() {
  256. const d0 = Math.random() * 0xffffffff | 0;
  257. const d1 = Math.random() * 0xffffffff | 0;
  258. const d2 = Math.random() * 0xffffffff | 0;
  259. const d3 = Math.random() * 0xffffffff | 0;
  260. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  261. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  262. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  263. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  264. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  265. return uuid.toLowerCase();
  266. }
  267. function clamp( value, min, max ) {
  268. return Math.max( min, Math.min( max, value ) );
  269. }
  270. // compute euclidean modulo of m % n
  271. // https://en.wikipedia.org/wiki/Modulo_operation
  272. function euclideanModulo( n, m ) {
  273. return ( ( n % m ) + m ) % m;
  274. }
  275. // Linear mapping from range <a1, a2> to range <b1, b2>
  276. function mapLinear( x, a1, a2, b1, b2 ) {
  277. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  278. }
  279. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  280. function inverseLerp( x, y, value ) {
  281. if ( x !== y ) {
  282. return ( value - x ) / ( y - x );
  283. } else {
  284. return 0;
  285. }
  286. }
  287. // https://en.wikipedia.org/wiki/Linear_interpolation
  288. function lerp( x, y, t ) {
  289. return ( 1 - t ) * x + t * y;
  290. }
  291. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  292. function damp( x, y, lambda, dt ) {
  293. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  294. }
  295. // https://www.desmos.com/calculator/vcsjnyz7x4
  296. function pingpong( x, length = 1 ) {
  297. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  298. }
  299. // http://en.wikipedia.org/wiki/Smoothstep
  300. function smoothstep( x, min, max ) {
  301. if ( x <= min ) return 0;
  302. if ( x >= max ) return 1;
  303. x = ( x - min ) / ( max - min );
  304. return x * x * ( 3 - 2 * x );
  305. }
  306. function smootherstep( x, min, max ) {
  307. if ( x <= min ) return 0;
  308. if ( x >= max ) return 1;
  309. x = ( x - min ) / ( max - min );
  310. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  311. }
  312. // Random integer from <low, high> interval
  313. function randInt( low, high ) {
  314. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  315. }
  316. // Random float from <low, high> interval
  317. function randFloat( low, high ) {
  318. return low + Math.random() * ( high - low );
  319. }
  320. // Random float from <-range/2, range/2> interval
  321. function randFloatSpread( range ) {
  322. return range * ( 0.5 - Math.random() );
  323. }
  324. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  325. function seededRandom( s ) {
  326. if ( s !== undefined ) _seed = s;
  327. // Mulberry32 generator
  328. let t = _seed += 0x6D2B79F5;
  329. t = Math.imul( t ^ t >>> 15, t | 1 );
  330. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  331. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  332. }
  333. function degToRad( degrees ) {
  334. return degrees * DEG2RAD;
  335. }
  336. function radToDeg( radians ) {
  337. return radians * RAD2DEG;
  338. }
  339. function isPowerOfTwo( value ) {
  340. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  341. }
  342. function ceilPowerOfTwo( value ) {
  343. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  344. }
  345. function floorPowerOfTwo( value ) {
  346. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  347. }
  348. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  349. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  350. // rotations are applied to the axes in the order specified by 'order'
  351. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  352. // angles are in radians
  353. const cos = Math.cos;
  354. const sin = Math.sin;
  355. const c2 = cos( b / 2 );
  356. const s2 = sin( b / 2 );
  357. const c13 = cos( ( a + c ) / 2 );
  358. const s13 = sin( ( a + c ) / 2 );
  359. const c1_3 = cos( ( a - c ) / 2 );
  360. const s1_3 = sin( ( a - c ) / 2 );
  361. const c3_1 = cos( ( c - a ) / 2 );
  362. const s3_1 = sin( ( c - a ) / 2 );
  363. switch ( order ) {
  364. case 'XYX':
  365. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  366. break;
  367. case 'YZY':
  368. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  369. break;
  370. case 'ZXZ':
  371. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  372. break;
  373. case 'XZX':
  374. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  375. break;
  376. case 'YXY':
  377. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  378. break;
  379. case 'ZYZ':
  380. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  381. break;
  382. default:
  383. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  384. }
  385. }
  386. function denormalize( value, array ) {
  387. switch ( array.constructor ) {
  388. case Float32Array:
  389. return value;
  390. case Uint32Array:
  391. return value / 4294967295.0;
  392. case Uint16Array:
  393. return value / 65535.0;
  394. case Uint8Array:
  395. return value / 255.0;
  396. case Int32Array:
  397. return Math.max( value / 2147483647.0, - 1.0 );
  398. case Int16Array:
  399. return Math.max( value / 32767.0, - 1.0 );
  400. case Int8Array:
  401. return Math.max( value / 127.0, - 1.0 );
  402. default:
  403. throw new Error( 'Invalid component type.' );
  404. }
  405. }
  406. function normalize( value, array ) {
  407. switch ( array.constructor ) {
  408. case Float32Array:
  409. return value;
  410. case Uint32Array:
  411. return Math.round( value * 4294967295.0 );
  412. case Uint16Array:
  413. return Math.round( value * 65535.0 );
  414. case Uint8Array:
  415. return Math.round( value * 255.0 );
  416. case Int32Array:
  417. return Math.round( value * 2147483647.0 );
  418. case Int16Array:
  419. return Math.round( value * 32767.0 );
  420. case Int8Array:
  421. return Math.round( value * 127.0 );
  422. default:
  423. throw new Error( 'Invalid component type.' );
  424. }
  425. }
  426. const MathUtils = {
  427. DEG2RAD: DEG2RAD,
  428. RAD2DEG: RAD2DEG,
  429. generateUUID: generateUUID,
  430. clamp: clamp,
  431. euclideanModulo: euclideanModulo,
  432. mapLinear: mapLinear,
  433. inverseLerp: inverseLerp,
  434. lerp: lerp,
  435. damp: damp,
  436. pingpong: pingpong,
  437. smoothstep: smoothstep,
  438. smootherstep: smootherstep,
  439. randInt: randInt,
  440. randFloat: randFloat,
  441. randFloatSpread: randFloatSpread,
  442. seededRandom: seededRandom,
  443. degToRad: degToRad,
  444. radToDeg: radToDeg,
  445. isPowerOfTwo: isPowerOfTwo,
  446. ceilPowerOfTwo: ceilPowerOfTwo,
  447. floorPowerOfTwo: floorPowerOfTwo,
  448. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  449. normalize: normalize,
  450. denormalize: denormalize
  451. };
  452. class Vector2 {
  453. constructor( x = 0, y = 0 ) {
  454. Vector2.prototype.isVector2 = true;
  455. this.x = x;
  456. this.y = y;
  457. }
  458. get width() {
  459. return this.x;
  460. }
  461. set width( value ) {
  462. this.x = value;
  463. }
  464. get height() {
  465. return this.y;
  466. }
  467. set height( value ) {
  468. this.y = value;
  469. }
  470. set( x, y ) {
  471. this.x = x;
  472. this.y = y;
  473. return this;
  474. }
  475. setScalar( scalar ) {
  476. this.x = scalar;
  477. this.y = scalar;
  478. return this;
  479. }
  480. setX( x ) {
  481. this.x = x;
  482. return this;
  483. }
  484. setY( y ) {
  485. this.y = y;
  486. return this;
  487. }
  488. setComponent( index, value ) {
  489. switch ( index ) {
  490. case 0: this.x = value; break;
  491. case 1: this.y = value; break;
  492. default: throw new Error( 'index is out of range: ' + index );
  493. }
  494. return this;
  495. }
  496. getComponent( index ) {
  497. switch ( index ) {
  498. case 0: return this.x;
  499. case 1: return this.y;
  500. default: throw new Error( 'index is out of range: ' + index );
  501. }
  502. }
  503. clone() {
  504. return new this.constructor( this.x, this.y );
  505. }
  506. copy( v ) {
  507. this.x = v.x;
  508. this.y = v.y;
  509. return this;
  510. }
  511. add( v ) {
  512. this.x += v.x;
  513. this.y += v.y;
  514. return this;
  515. }
  516. addScalar( s ) {
  517. this.x += s;
  518. this.y += s;
  519. return this;
  520. }
  521. addVectors( a, b ) {
  522. this.x = a.x + b.x;
  523. this.y = a.y + b.y;
  524. return this;
  525. }
  526. addScaledVector( v, s ) {
  527. this.x += v.x * s;
  528. this.y += v.y * s;
  529. return this;
  530. }
  531. sub( v ) {
  532. this.x -= v.x;
  533. this.y -= v.y;
  534. return this;
  535. }
  536. subScalar( s ) {
  537. this.x -= s;
  538. this.y -= s;
  539. return this;
  540. }
  541. subVectors( a, b ) {
  542. this.x = a.x - b.x;
  543. this.y = a.y - b.y;
  544. return this;
  545. }
  546. multiply( v ) {
  547. this.x *= v.x;
  548. this.y *= v.y;
  549. return this;
  550. }
  551. multiplyScalar( scalar ) {
  552. this.x *= scalar;
  553. this.y *= scalar;
  554. return this;
  555. }
  556. divide( v ) {
  557. this.x /= v.x;
  558. this.y /= v.y;
  559. return this;
  560. }
  561. divideScalar( scalar ) {
  562. return this.multiplyScalar( 1 / scalar );
  563. }
  564. applyMatrix3( m ) {
  565. const x = this.x, y = this.y;
  566. const e = m.elements;
  567. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  568. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  569. return this;
  570. }
  571. min( v ) {
  572. this.x = Math.min( this.x, v.x );
  573. this.y = Math.min( this.y, v.y );
  574. return this;
  575. }
  576. max( v ) {
  577. this.x = Math.max( this.x, v.x );
  578. this.y = Math.max( this.y, v.y );
  579. return this;
  580. }
  581. clamp( min, max ) {
  582. // assumes min < max, componentwise
  583. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  584. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  585. return this;
  586. }
  587. clampScalar( minVal, maxVal ) {
  588. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  589. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  590. return this;
  591. }
  592. clampLength( min, max ) {
  593. const length = this.length();
  594. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  595. }
  596. floor() {
  597. this.x = Math.floor( this.x );
  598. this.y = Math.floor( this.y );
  599. return this;
  600. }
  601. ceil() {
  602. this.x = Math.ceil( this.x );
  603. this.y = Math.ceil( this.y );
  604. return this;
  605. }
  606. round() {
  607. this.x = Math.round( this.x );
  608. this.y = Math.round( this.y );
  609. return this;
  610. }
  611. roundToZero() {
  612. this.x = Math.trunc( this.x );
  613. this.y = Math.trunc( this.y );
  614. return this;
  615. }
  616. negate() {
  617. this.x = - this.x;
  618. this.y = - this.y;
  619. return this;
  620. }
  621. dot( v ) {
  622. return this.x * v.x + this.y * v.y;
  623. }
  624. cross( v ) {
  625. return this.x * v.y - this.y * v.x;
  626. }
  627. lengthSq() {
  628. return this.x * this.x + this.y * this.y;
  629. }
  630. length() {
  631. return Math.sqrt( this.x * this.x + this.y * this.y );
  632. }
  633. manhattanLength() {
  634. return Math.abs( this.x ) + Math.abs( this.y );
  635. }
  636. normalize() {
  637. return this.divideScalar( this.length() || 1 );
  638. }
  639. angle() {
  640. // computes the angle in radians with respect to the positive x-axis
  641. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  642. return angle;
  643. }
  644. angleTo( v ) {
  645. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  646. if ( denominator === 0 ) return Math.PI / 2;
  647. const theta = this.dot( v ) / denominator;
  648. // clamp, to handle numerical problems
  649. return Math.acos( clamp( theta, - 1, 1 ) );
  650. }
  651. distanceTo( v ) {
  652. return Math.sqrt( this.distanceToSquared( v ) );
  653. }
  654. distanceToSquared( v ) {
  655. const dx = this.x - v.x, dy = this.y - v.y;
  656. return dx * dx + dy * dy;
  657. }
  658. manhattanDistanceTo( v ) {
  659. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  660. }
  661. setLength( length ) {
  662. return this.normalize().multiplyScalar( length );
  663. }
  664. lerp( v, alpha ) {
  665. this.x += ( v.x - this.x ) * alpha;
  666. this.y += ( v.y - this.y ) * alpha;
  667. return this;
  668. }
  669. lerpVectors( v1, v2, alpha ) {
  670. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  671. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  672. return this;
  673. }
  674. equals( v ) {
  675. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  676. }
  677. fromArray( array, offset = 0 ) {
  678. this.x = array[ offset ];
  679. this.y = array[ offset + 1 ];
  680. return this;
  681. }
  682. toArray( array = [], offset = 0 ) {
  683. array[ offset ] = this.x;
  684. array[ offset + 1 ] = this.y;
  685. return array;
  686. }
  687. fromBufferAttribute( attribute, index ) {
  688. this.x = attribute.getX( index );
  689. this.y = attribute.getY( index );
  690. return this;
  691. }
  692. rotateAround( center, angle ) {
  693. const c = Math.cos( angle ), s = Math.sin( angle );
  694. const x = this.x - center.x;
  695. const y = this.y - center.y;
  696. this.x = x * c - y * s + center.x;
  697. this.y = x * s + y * c + center.y;
  698. return this;
  699. }
  700. random() {
  701. this.x = Math.random();
  702. this.y = Math.random();
  703. return this;
  704. }
  705. *[ Symbol.iterator ]() {
  706. yield this.x;
  707. yield this.y;
  708. }
  709. }
  710. class Matrix3 {
  711. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  712. Matrix3.prototype.isMatrix3 = true;
  713. this.elements = [
  714. 1, 0, 0,
  715. 0, 1, 0,
  716. 0, 0, 1
  717. ];
  718. if ( n11 !== undefined ) {
  719. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  720. }
  721. }
  722. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  723. const te = this.elements;
  724. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  725. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  726. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  727. return this;
  728. }
  729. identity() {
  730. this.set(
  731. 1, 0, 0,
  732. 0, 1, 0,
  733. 0, 0, 1
  734. );
  735. return this;
  736. }
  737. copy( m ) {
  738. const te = this.elements;
  739. const me = m.elements;
  740. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  741. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  742. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  743. return this;
  744. }
  745. extractBasis( xAxis, yAxis, zAxis ) {
  746. xAxis.setFromMatrix3Column( this, 0 );
  747. yAxis.setFromMatrix3Column( this, 1 );
  748. zAxis.setFromMatrix3Column( this, 2 );
  749. return this;
  750. }
  751. setFromMatrix4( m ) {
  752. const me = m.elements;
  753. this.set(
  754. me[ 0 ], me[ 4 ], me[ 8 ],
  755. me[ 1 ], me[ 5 ], me[ 9 ],
  756. me[ 2 ], me[ 6 ], me[ 10 ]
  757. );
  758. return this;
  759. }
  760. multiply( m ) {
  761. return this.multiplyMatrices( this, m );
  762. }
  763. premultiply( m ) {
  764. return this.multiplyMatrices( m, this );
  765. }
  766. multiplyMatrices( a, b ) {
  767. const ae = a.elements;
  768. const be = b.elements;
  769. const te = this.elements;
  770. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  771. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  772. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  773. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  774. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  775. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  776. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  777. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  778. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  779. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  780. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  781. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  782. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  783. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  784. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  785. return this;
  786. }
  787. multiplyScalar( s ) {
  788. const te = this.elements;
  789. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  790. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  791. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  792. return this;
  793. }
  794. determinant() {
  795. const te = this.elements;
  796. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  797. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  798. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  799. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  800. }
  801. invert() {
  802. const te = this.elements,
  803. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  804. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  805. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  806. t11 = n33 * n22 - n32 * n23,
  807. t12 = n32 * n13 - n33 * n12,
  808. t13 = n23 * n12 - n22 * n13,
  809. det = n11 * t11 + n21 * t12 + n31 * t13;
  810. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  811. const detInv = 1 / det;
  812. te[ 0 ] = t11 * detInv;
  813. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  814. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  815. te[ 3 ] = t12 * detInv;
  816. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  817. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  818. te[ 6 ] = t13 * detInv;
  819. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  820. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  821. return this;
  822. }
  823. transpose() {
  824. let tmp;
  825. const m = this.elements;
  826. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  827. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  828. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  829. return this;
  830. }
  831. getNormalMatrix( matrix4 ) {
  832. return this.setFromMatrix4( matrix4 ).invert().transpose();
  833. }
  834. transposeIntoArray( r ) {
  835. const m = this.elements;
  836. r[ 0 ] = m[ 0 ];
  837. r[ 1 ] = m[ 3 ];
  838. r[ 2 ] = m[ 6 ];
  839. r[ 3 ] = m[ 1 ];
  840. r[ 4 ] = m[ 4 ];
  841. r[ 5 ] = m[ 7 ];
  842. r[ 6 ] = m[ 2 ];
  843. r[ 7 ] = m[ 5 ];
  844. r[ 8 ] = m[ 8 ];
  845. return this;
  846. }
  847. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  848. const c = Math.cos( rotation );
  849. const s = Math.sin( rotation );
  850. this.set(
  851. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  852. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  853. 0, 0, 1
  854. );
  855. return this;
  856. }
  857. //
  858. scale( sx, sy ) {
  859. this.premultiply( _m3.makeScale( sx, sy ) );
  860. return this;
  861. }
  862. rotate( theta ) {
  863. this.premultiply( _m3.makeRotation( - theta ) );
  864. return this;
  865. }
  866. translate( tx, ty ) {
  867. this.premultiply( _m3.makeTranslation( tx, ty ) );
  868. return this;
  869. }
  870. // for 2D Transforms
  871. makeTranslation( x, y ) {
  872. if ( x.isVector2 ) {
  873. this.set(
  874. 1, 0, x.x,
  875. 0, 1, x.y,
  876. 0, 0, 1
  877. );
  878. } else {
  879. this.set(
  880. 1, 0, x,
  881. 0, 1, y,
  882. 0, 0, 1
  883. );
  884. }
  885. return this;
  886. }
  887. makeRotation( theta ) {
  888. // counterclockwise
  889. const c = Math.cos( theta );
  890. const s = Math.sin( theta );
  891. this.set(
  892. c, - s, 0,
  893. s, c, 0,
  894. 0, 0, 1
  895. );
  896. return this;
  897. }
  898. makeScale( x, y ) {
  899. this.set(
  900. x, 0, 0,
  901. 0, y, 0,
  902. 0, 0, 1
  903. );
  904. return this;
  905. }
  906. //
  907. equals( matrix ) {
  908. const te = this.elements;
  909. const me = matrix.elements;
  910. for ( let i = 0; i < 9; i ++ ) {
  911. if ( te[ i ] !== me[ i ] ) return false;
  912. }
  913. return true;
  914. }
  915. fromArray( array, offset = 0 ) {
  916. for ( let i = 0; i < 9; i ++ ) {
  917. this.elements[ i ] = array[ i + offset ];
  918. }
  919. return this;
  920. }
  921. toArray( array = [], offset = 0 ) {
  922. const te = this.elements;
  923. array[ offset ] = te[ 0 ];
  924. array[ offset + 1 ] = te[ 1 ];
  925. array[ offset + 2 ] = te[ 2 ];
  926. array[ offset + 3 ] = te[ 3 ];
  927. array[ offset + 4 ] = te[ 4 ];
  928. array[ offset + 5 ] = te[ 5 ];
  929. array[ offset + 6 ] = te[ 6 ];
  930. array[ offset + 7 ] = te[ 7 ];
  931. array[ offset + 8 ] = te[ 8 ];
  932. return array;
  933. }
  934. clone() {
  935. return new this.constructor().fromArray( this.elements );
  936. }
  937. }
  938. const _m3 = /*@__PURE__*/ new Matrix3();
  939. function arrayNeedsUint32( array ) {
  940. // assumes larger values usually on last
  941. for ( let i = array.length - 1; i >= 0; -- i ) {
  942. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  943. }
  944. return false;
  945. }
  946. const TYPED_ARRAYS = {
  947. Int8Array: Int8Array,
  948. Uint8Array: Uint8Array,
  949. Uint8ClampedArray: Uint8ClampedArray,
  950. Int16Array: Int16Array,
  951. Uint16Array: Uint16Array,
  952. Int32Array: Int32Array,
  953. Uint32Array: Uint32Array,
  954. Float32Array: Float32Array,
  955. Float64Array: Float64Array
  956. };
  957. function getTypedArray( type, buffer ) {
  958. return new TYPED_ARRAYS[ type ]( buffer );
  959. }
  960. function createElementNS( name ) {
  961. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  962. }
  963. function createCanvasElement() {
  964. const canvas = createElementNS( 'canvas' );
  965. canvas.style.display = 'block';
  966. return canvas;
  967. }
  968. const _cache = {};
  969. function warnOnce( message ) {
  970. if ( message in _cache ) return;
  971. _cache[ message ] = true;
  972. console.warn( message );
  973. }
  974. /**
  975. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  976. * or clipping. Based on W3C specifications for sRGB and Display P3,
  977. * and ICC specifications for the D50 connection space. Values in/out
  978. * are _linear_ sRGB and _linear_ Display P3.
  979. *
  980. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  981. *
  982. * Reference:
  983. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  984. */
  985. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  986. 0.8224621, 0.177538, 0.0,
  987. 0.0331941, 0.9668058, 0.0,
  988. 0.0170827, 0.0723974, 0.9105199,
  989. );
  990. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  991. 1.2249401, - 0.2249404, 0.0,
  992. - 0.0420569, 1.0420571, 0.0,
  993. - 0.0196376, - 0.0786361, 1.0982735
  994. );
  995. /**
  996. * Defines supported color spaces by transfer function and primaries,
  997. * and provides conversions to/from the Linear-sRGB reference space.
  998. */
  999. const COLOR_SPACES = {
  1000. [ LinearSRGBColorSpace ]: {
  1001. transfer: LinearTransfer,
  1002. primaries: Rec709Primaries,
  1003. toReference: ( color ) => color,
  1004. fromReference: ( color ) => color,
  1005. },
  1006. [ SRGBColorSpace ]: {
  1007. transfer: SRGBTransfer,
  1008. primaries: Rec709Primaries,
  1009. toReference: ( color ) => color.convertSRGBToLinear(),
  1010. fromReference: ( color ) => color.convertLinearToSRGB(),
  1011. },
  1012. [ LinearDisplayP3ColorSpace ]: {
  1013. transfer: LinearTransfer,
  1014. primaries: P3Primaries,
  1015. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1016. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1017. },
  1018. [ DisplayP3ColorSpace ]: {
  1019. transfer: SRGBTransfer,
  1020. primaries: P3Primaries,
  1021. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1022. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1023. },
  1024. };
  1025. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1026. const ColorManagement = {
  1027. enabled: true,
  1028. _workingColorSpace: LinearSRGBColorSpace,
  1029. get workingColorSpace() {
  1030. return this._workingColorSpace;
  1031. },
  1032. set workingColorSpace( colorSpace ) {
  1033. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1034. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1035. }
  1036. this._workingColorSpace = colorSpace;
  1037. },
  1038. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1039. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1040. return color;
  1041. }
  1042. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1043. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1044. return targetFromReference( sourceToReference( color ) );
  1045. },
  1046. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1047. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1048. },
  1049. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1050. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1051. },
  1052. getPrimaries: function ( colorSpace ) {
  1053. return COLOR_SPACES[ colorSpace ].primaries;
  1054. },
  1055. getTransfer: function ( colorSpace ) {
  1056. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1057. return COLOR_SPACES[ colorSpace ].transfer;
  1058. },
  1059. };
  1060. function SRGBToLinear( c ) {
  1061. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1062. }
  1063. function LinearToSRGB( c ) {
  1064. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1065. }
  1066. let _canvas;
  1067. class ImageUtils {
  1068. static getDataURL( image ) {
  1069. if ( /^data:/i.test( image.src ) ) {
  1070. return image.src;
  1071. }
  1072. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1073. return image.src;
  1074. }
  1075. let canvas;
  1076. if ( image instanceof HTMLCanvasElement ) {
  1077. canvas = image;
  1078. } else {
  1079. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1080. _canvas.width = image.width;
  1081. _canvas.height = image.height;
  1082. const context = _canvas.getContext( '2d' );
  1083. if ( image instanceof ImageData ) {
  1084. context.putImageData( image, 0, 0 );
  1085. } else {
  1086. context.drawImage( image, 0, 0, image.width, image.height );
  1087. }
  1088. canvas = _canvas;
  1089. }
  1090. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1091. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1092. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1093. } else {
  1094. return canvas.toDataURL( 'image/png' );
  1095. }
  1096. }
  1097. static sRGBToLinear( image ) {
  1098. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1099. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1100. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1101. const canvas = createElementNS( 'canvas' );
  1102. canvas.width = image.width;
  1103. canvas.height = image.height;
  1104. const context = canvas.getContext( '2d' );
  1105. context.drawImage( image, 0, 0, image.width, image.height );
  1106. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1107. const data = imageData.data;
  1108. for ( let i = 0; i < data.length; i ++ ) {
  1109. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1110. }
  1111. context.putImageData( imageData, 0, 0 );
  1112. return canvas;
  1113. } else if ( image.data ) {
  1114. const data = image.data.slice( 0 );
  1115. for ( let i = 0; i < data.length; i ++ ) {
  1116. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1117. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1118. } else {
  1119. // assuming float
  1120. data[ i ] = SRGBToLinear( data[ i ] );
  1121. }
  1122. }
  1123. return {
  1124. data: data,
  1125. width: image.width,
  1126. height: image.height
  1127. };
  1128. } else {
  1129. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1130. return image;
  1131. }
  1132. }
  1133. }
  1134. let _sourceId = 0;
  1135. class Source {
  1136. constructor( data = null ) {
  1137. this.isSource = true;
  1138. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1139. this.uuid = generateUUID();
  1140. this.data = data;
  1141. this.dataReady = true;
  1142. this.version = 0;
  1143. }
  1144. set needsUpdate( value ) {
  1145. if ( value === true ) this.version ++;
  1146. }
  1147. toJSON( meta ) {
  1148. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1149. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1150. return meta.images[ this.uuid ];
  1151. }
  1152. const output = {
  1153. uuid: this.uuid,
  1154. url: ''
  1155. };
  1156. const data = this.data;
  1157. if ( data !== null ) {
  1158. let url;
  1159. if ( Array.isArray( data ) ) {
  1160. // cube texture
  1161. url = [];
  1162. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1163. if ( data[ i ].isDataTexture ) {
  1164. url.push( serializeImage( data[ i ].image ) );
  1165. } else {
  1166. url.push( serializeImage( data[ i ] ) );
  1167. }
  1168. }
  1169. } else {
  1170. // texture
  1171. url = serializeImage( data );
  1172. }
  1173. output.url = url;
  1174. }
  1175. if ( ! isRootObject ) {
  1176. meta.images[ this.uuid ] = output;
  1177. }
  1178. return output;
  1179. }
  1180. }
  1181. function serializeImage( image ) {
  1182. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1183. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1184. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1185. // default images
  1186. return ImageUtils.getDataURL( image );
  1187. } else {
  1188. if ( image.data ) {
  1189. // images of DataTexture
  1190. return {
  1191. data: Array.from( image.data ),
  1192. width: image.width,
  1193. height: image.height,
  1194. type: image.data.constructor.name
  1195. };
  1196. } else {
  1197. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1198. return {};
  1199. }
  1200. }
  1201. }
  1202. let _textureId = 0;
  1203. class Texture extends EventDispatcher {
  1204. 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 ) {
  1205. super();
  1206. this.isTexture = true;
  1207. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1208. this.uuid = generateUUID();
  1209. this.name = '';
  1210. this.source = new Source( image );
  1211. this.mipmaps = [];
  1212. this.mapping = mapping;
  1213. this.channel = 0;
  1214. this.wrapS = wrapS;
  1215. this.wrapT = wrapT;
  1216. this.magFilter = magFilter;
  1217. this.minFilter = minFilter;
  1218. this.anisotropy = anisotropy;
  1219. this.format = format;
  1220. this.internalFormat = null;
  1221. this.type = type;
  1222. this.offset = new Vector2( 0, 0 );
  1223. this.repeat = new Vector2( 1, 1 );
  1224. this.center = new Vector2( 0, 0 );
  1225. this.rotation = 0;
  1226. this.matrixAutoUpdate = true;
  1227. this.matrix = new Matrix3();
  1228. this.generateMipmaps = true;
  1229. this.premultiplyAlpha = false;
  1230. this.flipY = true;
  1231. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1232. this.colorSpace = colorSpace;
  1233. this.userData = {};
  1234. this.version = 0;
  1235. this.onUpdate = null;
  1236. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1237. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1238. }
  1239. get image() {
  1240. return this.source.data;
  1241. }
  1242. set image( value = null ) {
  1243. this.source.data = value;
  1244. }
  1245. updateMatrix() {
  1246. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1247. }
  1248. clone() {
  1249. return new this.constructor().copy( this );
  1250. }
  1251. copy( source ) {
  1252. this.name = source.name;
  1253. this.source = source.source;
  1254. this.mipmaps = source.mipmaps.slice( 0 );
  1255. this.mapping = source.mapping;
  1256. this.channel = source.channel;
  1257. this.wrapS = source.wrapS;
  1258. this.wrapT = source.wrapT;
  1259. this.magFilter = source.magFilter;
  1260. this.minFilter = source.minFilter;
  1261. this.anisotropy = source.anisotropy;
  1262. this.format = source.format;
  1263. this.internalFormat = source.internalFormat;
  1264. this.type = source.type;
  1265. this.offset.copy( source.offset );
  1266. this.repeat.copy( source.repeat );
  1267. this.center.copy( source.center );
  1268. this.rotation = source.rotation;
  1269. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1270. this.matrix.copy( source.matrix );
  1271. this.generateMipmaps = source.generateMipmaps;
  1272. this.premultiplyAlpha = source.premultiplyAlpha;
  1273. this.flipY = source.flipY;
  1274. this.unpackAlignment = source.unpackAlignment;
  1275. this.colorSpace = source.colorSpace;
  1276. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1277. this.needsUpdate = true;
  1278. return this;
  1279. }
  1280. toJSON( meta ) {
  1281. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1282. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1283. return meta.textures[ this.uuid ];
  1284. }
  1285. const output = {
  1286. metadata: {
  1287. version: 4.6,
  1288. type: 'Texture',
  1289. generator: 'Texture.toJSON'
  1290. },
  1291. uuid: this.uuid,
  1292. name: this.name,
  1293. image: this.source.toJSON( meta ).uuid,
  1294. mapping: this.mapping,
  1295. channel: this.channel,
  1296. repeat: [ this.repeat.x, this.repeat.y ],
  1297. offset: [ this.offset.x, this.offset.y ],
  1298. center: [ this.center.x, this.center.y ],
  1299. rotation: this.rotation,
  1300. wrap: [ this.wrapS, this.wrapT ],
  1301. format: this.format,
  1302. internalFormat: this.internalFormat,
  1303. type: this.type,
  1304. colorSpace: this.colorSpace,
  1305. minFilter: this.minFilter,
  1306. magFilter: this.magFilter,
  1307. anisotropy: this.anisotropy,
  1308. flipY: this.flipY,
  1309. generateMipmaps: this.generateMipmaps,
  1310. premultiplyAlpha: this.premultiplyAlpha,
  1311. unpackAlignment: this.unpackAlignment
  1312. };
  1313. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1314. if ( ! isRootObject ) {
  1315. meta.textures[ this.uuid ] = output;
  1316. }
  1317. return output;
  1318. }
  1319. dispose() {
  1320. this.dispatchEvent( { type: 'dispose' } );
  1321. }
  1322. transformUv( uv ) {
  1323. if ( this.mapping !== UVMapping ) return uv;
  1324. uv.applyMatrix3( this.matrix );
  1325. if ( uv.x < 0 || uv.x > 1 ) {
  1326. switch ( this.wrapS ) {
  1327. case RepeatWrapping:
  1328. uv.x = uv.x - Math.floor( uv.x );
  1329. break;
  1330. case ClampToEdgeWrapping:
  1331. uv.x = uv.x < 0 ? 0 : 1;
  1332. break;
  1333. case MirroredRepeatWrapping:
  1334. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1335. uv.x = Math.ceil( uv.x ) - uv.x;
  1336. } else {
  1337. uv.x = uv.x - Math.floor( uv.x );
  1338. }
  1339. break;
  1340. }
  1341. }
  1342. if ( uv.y < 0 || uv.y > 1 ) {
  1343. switch ( this.wrapT ) {
  1344. case RepeatWrapping:
  1345. uv.y = uv.y - Math.floor( uv.y );
  1346. break;
  1347. case ClampToEdgeWrapping:
  1348. uv.y = uv.y < 0 ? 0 : 1;
  1349. break;
  1350. case MirroredRepeatWrapping:
  1351. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1352. uv.y = Math.ceil( uv.y ) - uv.y;
  1353. } else {
  1354. uv.y = uv.y - Math.floor( uv.y );
  1355. }
  1356. break;
  1357. }
  1358. }
  1359. if ( this.flipY ) {
  1360. uv.y = 1 - uv.y;
  1361. }
  1362. return uv;
  1363. }
  1364. set needsUpdate( value ) {
  1365. if ( value === true ) {
  1366. this.version ++;
  1367. this.source.needsUpdate = true;
  1368. }
  1369. }
  1370. set needsPMREMUpdate( value ) {
  1371. if ( value === true ) {
  1372. this.pmremVersion ++;
  1373. }
  1374. }
  1375. }
  1376. Texture.DEFAULT_IMAGE = null;
  1377. Texture.DEFAULT_MAPPING = UVMapping;
  1378. Texture.DEFAULT_ANISOTROPY = 1;
  1379. class Vector4 {
  1380. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1381. Vector4.prototype.isVector4 = true;
  1382. this.x = x;
  1383. this.y = y;
  1384. this.z = z;
  1385. this.w = w;
  1386. }
  1387. get width() {
  1388. return this.z;
  1389. }
  1390. set width( value ) {
  1391. this.z = value;
  1392. }
  1393. get height() {
  1394. return this.w;
  1395. }
  1396. set height( value ) {
  1397. this.w = value;
  1398. }
  1399. set( x, y, z, w ) {
  1400. this.x = x;
  1401. this.y = y;
  1402. this.z = z;
  1403. this.w = w;
  1404. return this;
  1405. }
  1406. setScalar( scalar ) {
  1407. this.x = scalar;
  1408. this.y = scalar;
  1409. this.z = scalar;
  1410. this.w = scalar;
  1411. return this;
  1412. }
  1413. setX( x ) {
  1414. this.x = x;
  1415. return this;
  1416. }
  1417. setY( y ) {
  1418. this.y = y;
  1419. return this;
  1420. }
  1421. setZ( z ) {
  1422. this.z = z;
  1423. return this;
  1424. }
  1425. setW( w ) {
  1426. this.w = w;
  1427. return this;
  1428. }
  1429. setComponent( index, value ) {
  1430. switch ( index ) {
  1431. case 0: this.x = value; break;
  1432. case 1: this.y = value; break;
  1433. case 2: this.z = value; break;
  1434. case 3: this.w = value; break;
  1435. default: throw new Error( 'index is out of range: ' + index );
  1436. }
  1437. return this;
  1438. }
  1439. getComponent( index ) {
  1440. switch ( index ) {
  1441. case 0: return this.x;
  1442. case 1: return this.y;
  1443. case 2: return this.z;
  1444. case 3: return this.w;
  1445. default: throw new Error( 'index is out of range: ' + index );
  1446. }
  1447. }
  1448. clone() {
  1449. return new this.constructor( this.x, this.y, this.z, this.w );
  1450. }
  1451. copy( v ) {
  1452. this.x = v.x;
  1453. this.y = v.y;
  1454. this.z = v.z;
  1455. this.w = ( v.w !== undefined ) ? v.w : 1;
  1456. return this;
  1457. }
  1458. add( v ) {
  1459. this.x += v.x;
  1460. this.y += v.y;
  1461. this.z += v.z;
  1462. this.w += v.w;
  1463. return this;
  1464. }
  1465. addScalar( s ) {
  1466. this.x += s;
  1467. this.y += s;
  1468. this.z += s;
  1469. this.w += s;
  1470. return this;
  1471. }
  1472. addVectors( a, b ) {
  1473. this.x = a.x + b.x;
  1474. this.y = a.y + b.y;
  1475. this.z = a.z + b.z;
  1476. this.w = a.w + b.w;
  1477. return this;
  1478. }
  1479. addScaledVector( v, s ) {
  1480. this.x += v.x * s;
  1481. this.y += v.y * s;
  1482. this.z += v.z * s;
  1483. this.w += v.w * s;
  1484. return this;
  1485. }
  1486. sub( v ) {
  1487. this.x -= v.x;
  1488. this.y -= v.y;
  1489. this.z -= v.z;
  1490. this.w -= v.w;
  1491. return this;
  1492. }
  1493. subScalar( s ) {
  1494. this.x -= s;
  1495. this.y -= s;
  1496. this.z -= s;
  1497. this.w -= s;
  1498. return this;
  1499. }
  1500. subVectors( a, b ) {
  1501. this.x = a.x - b.x;
  1502. this.y = a.y - b.y;
  1503. this.z = a.z - b.z;
  1504. this.w = a.w - b.w;
  1505. return this;
  1506. }
  1507. multiply( v ) {
  1508. this.x *= v.x;
  1509. this.y *= v.y;
  1510. this.z *= v.z;
  1511. this.w *= v.w;
  1512. return this;
  1513. }
  1514. multiplyScalar( scalar ) {
  1515. this.x *= scalar;
  1516. this.y *= scalar;
  1517. this.z *= scalar;
  1518. this.w *= scalar;
  1519. return this;
  1520. }
  1521. applyMatrix4( m ) {
  1522. const x = this.x, y = this.y, z = this.z, w = this.w;
  1523. const e = m.elements;
  1524. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1525. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1526. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1527. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1528. return this;
  1529. }
  1530. divideScalar( scalar ) {
  1531. return this.multiplyScalar( 1 / scalar );
  1532. }
  1533. setAxisAngleFromQuaternion( q ) {
  1534. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1535. // q is assumed to be normalized
  1536. this.w = 2 * Math.acos( q.w );
  1537. const s = Math.sqrt( 1 - q.w * q.w );
  1538. if ( s < 0.0001 ) {
  1539. this.x = 1;
  1540. this.y = 0;
  1541. this.z = 0;
  1542. } else {
  1543. this.x = q.x / s;
  1544. this.y = q.y / s;
  1545. this.z = q.z / s;
  1546. }
  1547. return this;
  1548. }
  1549. setAxisAngleFromRotationMatrix( m ) {
  1550. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1551. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1552. let angle, x, y, z; // variables for result
  1553. const epsilon = 0.01, // margin to allow for rounding errors
  1554. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1555. te = m.elements,
  1556. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1557. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1558. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1559. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1560. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1561. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1562. // singularity found
  1563. // first check for identity matrix which must have +1 for all terms
  1564. // in leading diagonal and zero in other terms
  1565. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1566. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1567. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1568. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1569. // this singularity is identity matrix so angle = 0
  1570. this.set( 1, 0, 0, 0 );
  1571. return this; // zero angle, arbitrary axis
  1572. }
  1573. // otherwise this singularity is angle = 180
  1574. angle = Math.PI;
  1575. const xx = ( m11 + 1 ) / 2;
  1576. const yy = ( m22 + 1 ) / 2;
  1577. const zz = ( m33 + 1 ) / 2;
  1578. const xy = ( m12 + m21 ) / 4;
  1579. const xz = ( m13 + m31 ) / 4;
  1580. const yz = ( m23 + m32 ) / 4;
  1581. if ( ( xx > yy ) && ( xx > zz ) ) {
  1582. // m11 is the largest diagonal term
  1583. if ( xx < epsilon ) {
  1584. x = 0;
  1585. y = 0.707106781;
  1586. z = 0.707106781;
  1587. } else {
  1588. x = Math.sqrt( xx );
  1589. y = xy / x;
  1590. z = xz / x;
  1591. }
  1592. } else if ( yy > zz ) {
  1593. // m22 is the largest diagonal term
  1594. if ( yy < epsilon ) {
  1595. x = 0.707106781;
  1596. y = 0;
  1597. z = 0.707106781;
  1598. } else {
  1599. y = Math.sqrt( yy );
  1600. x = xy / y;
  1601. z = yz / y;
  1602. }
  1603. } else {
  1604. // m33 is the largest diagonal term so base result on this
  1605. if ( zz < epsilon ) {
  1606. x = 0.707106781;
  1607. y = 0.707106781;
  1608. z = 0;
  1609. } else {
  1610. z = Math.sqrt( zz );
  1611. x = xz / z;
  1612. y = yz / z;
  1613. }
  1614. }
  1615. this.set( x, y, z, angle );
  1616. return this; // return 180 deg rotation
  1617. }
  1618. // as we have reached here there are no singularities so we can handle normally
  1619. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1620. ( m13 - m31 ) * ( m13 - m31 ) +
  1621. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1622. if ( Math.abs( s ) < 0.001 ) s = 1;
  1623. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1624. // caught by singularity test above, but I've left it in just in case
  1625. this.x = ( m32 - m23 ) / s;
  1626. this.y = ( m13 - m31 ) / s;
  1627. this.z = ( m21 - m12 ) / s;
  1628. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1629. return this;
  1630. }
  1631. min( v ) {
  1632. this.x = Math.min( this.x, v.x );
  1633. this.y = Math.min( this.y, v.y );
  1634. this.z = Math.min( this.z, v.z );
  1635. this.w = Math.min( this.w, v.w );
  1636. return this;
  1637. }
  1638. max( v ) {
  1639. this.x = Math.max( this.x, v.x );
  1640. this.y = Math.max( this.y, v.y );
  1641. this.z = Math.max( this.z, v.z );
  1642. this.w = Math.max( this.w, v.w );
  1643. return this;
  1644. }
  1645. clamp( min, max ) {
  1646. // assumes min < max, componentwise
  1647. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1648. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1649. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1650. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1651. return this;
  1652. }
  1653. clampScalar( minVal, maxVal ) {
  1654. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1655. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1656. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1657. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1658. return this;
  1659. }
  1660. clampLength( min, max ) {
  1661. const length = this.length();
  1662. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1663. }
  1664. floor() {
  1665. this.x = Math.floor( this.x );
  1666. this.y = Math.floor( this.y );
  1667. this.z = Math.floor( this.z );
  1668. this.w = Math.floor( this.w );
  1669. return this;
  1670. }
  1671. ceil() {
  1672. this.x = Math.ceil( this.x );
  1673. this.y = Math.ceil( this.y );
  1674. this.z = Math.ceil( this.z );
  1675. this.w = Math.ceil( this.w );
  1676. return this;
  1677. }
  1678. round() {
  1679. this.x = Math.round( this.x );
  1680. this.y = Math.round( this.y );
  1681. this.z = Math.round( this.z );
  1682. this.w = Math.round( this.w );
  1683. return this;
  1684. }
  1685. roundToZero() {
  1686. this.x = Math.trunc( this.x );
  1687. this.y = Math.trunc( this.y );
  1688. this.z = Math.trunc( this.z );
  1689. this.w = Math.trunc( this.w );
  1690. return this;
  1691. }
  1692. negate() {
  1693. this.x = - this.x;
  1694. this.y = - this.y;
  1695. this.z = - this.z;
  1696. this.w = - this.w;
  1697. return this;
  1698. }
  1699. dot( v ) {
  1700. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1701. }
  1702. lengthSq() {
  1703. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1704. }
  1705. length() {
  1706. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1707. }
  1708. manhattanLength() {
  1709. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1710. }
  1711. normalize() {
  1712. return this.divideScalar( this.length() || 1 );
  1713. }
  1714. setLength( length ) {
  1715. return this.normalize().multiplyScalar( length );
  1716. }
  1717. lerp( v, alpha ) {
  1718. this.x += ( v.x - this.x ) * alpha;
  1719. this.y += ( v.y - this.y ) * alpha;
  1720. this.z += ( v.z - this.z ) * alpha;
  1721. this.w += ( v.w - this.w ) * alpha;
  1722. return this;
  1723. }
  1724. lerpVectors( v1, v2, alpha ) {
  1725. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1726. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1727. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1728. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1729. return this;
  1730. }
  1731. equals( v ) {
  1732. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1733. }
  1734. fromArray( array, offset = 0 ) {
  1735. this.x = array[ offset ];
  1736. this.y = array[ offset + 1 ];
  1737. this.z = array[ offset + 2 ];
  1738. this.w = array[ offset + 3 ];
  1739. return this;
  1740. }
  1741. toArray( array = [], offset = 0 ) {
  1742. array[ offset ] = this.x;
  1743. array[ offset + 1 ] = this.y;
  1744. array[ offset + 2 ] = this.z;
  1745. array[ offset + 3 ] = this.w;
  1746. return array;
  1747. }
  1748. fromBufferAttribute( attribute, index ) {
  1749. this.x = attribute.getX( index );
  1750. this.y = attribute.getY( index );
  1751. this.z = attribute.getZ( index );
  1752. this.w = attribute.getW( index );
  1753. return this;
  1754. }
  1755. random() {
  1756. this.x = Math.random();
  1757. this.y = Math.random();
  1758. this.z = Math.random();
  1759. this.w = Math.random();
  1760. return this;
  1761. }
  1762. *[ Symbol.iterator ]() {
  1763. yield this.x;
  1764. yield this.y;
  1765. yield this.z;
  1766. yield this.w;
  1767. }
  1768. }
  1769. /*
  1770. In options, we can specify:
  1771. * Texture parameters for an auto-generated target texture
  1772. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1773. */
  1774. class RenderTarget extends EventDispatcher {
  1775. constructor( width = 1, height = 1, options = {} ) {
  1776. super();
  1777. this.isRenderTarget = true;
  1778. this.width = width;
  1779. this.height = height;
  1780. this.depth = 1;
  1781. this.scissor = new Vector4( 0, 0, width, height );
  1782. this.scissorTest = false;
  1783. this.viewport = new Vector4( 0, 0, width, height );
  1784. const image = { width: width, height: height, depth: 1 };
  1785. options = Object.assign( {
  1786. generateMipmaps: false,
  1787. internalFormat: null,
  1788. minFilter: LinearFilter,
  1789. depthBuffer: true,
  1790. stencilBuffer: false,
  1791. depthTexture: null,
  1792. samples: 0,
  1793. count: 1
  1794. }, options );
  1795. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1796. texture.flipY = false;
  1797. texture.generateMipmaps = options.generateMipmaps;
  1798. texture.internalFormat = options.internalFormat;
  1799. this.textures = [];
  1800. const count = options.count;
  1801. for ( let i = 0; i < count; i ++ ) {
  1802. this.textures[ i ] = texture.clone();
  1803. this.textures[ i ].isRenderTargetTexture = true;
  1804. }
  1805. this.depthBuffer = options.depthBuffer;
  1806. this.stencilBuffer = options.stencilBuffer;
  1807. this.depthTexture = options.depthTexture;
  1808. this.samples = options.samples;
  1809. }
  1810. get texture() {
  1811. return this.textures[ 0 ];
  1812. }
  1813. set texture( value ) {
  1814. this.textures[ 0 ] = value;
  1815. }
  1816. setSize( width, height, depth = 1 ) {
  1817. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1818. this.width = width;
  1819. this.height = height;
  1820. this.depth = depth;
  1821. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1822. this.textures[ i ].image.width = width;
  1823. this.textures[ i ].image.height = height;
  1824. this.textures[ i ].image.depth = depth;
  1825. }
  1826. this.dispose();
  1827. }
  1828. this.viewport.set( 0, 0, width, height );
  1829. this.scissor.set( 0, 0, width, height );
  1830. }
  1831. clone() {
  1832. return new this.constructor().copy( this );
  1833. }
  1834. copy( source ) {
  1835. this.width = source.width;
  1836. this.height = source.height;
  1837. this.depth = source.depth;
  1838. this.scissor.copy( source.scissor );
  1839. this.scissorTest = source.scissorTest;
  1840. this.viewport.copy( source.viewport );
  1841. this.textures.length = 0;
  1842. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1843. this.textures[ i ] = source.textures[ i ].clone();
  1844. this.textures[ i ].isRenderTargetTexture = true;
  1845. }
  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 Quaternion {
  1917. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1918. this.isQuaternion = true;
  1919. this._x = x;
  1920. this._y = y;
  1921. this._z = z;
  1922. this._w = w;
  1923. }
  1924. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1925. // fuzz-free, array-based Quaternion SLERP operation
  1926. let x0 = src0[ srcOffset0 + 0 ],
  1927. y0 = src0[ srcOffset0 + 1 ],
  1928. z0 = src0[ srcOffset0 + 2 ],
  1929. w0 = src0[ srcOffset0 + 3 ];
  1930. const x1 = src1[ srcOffset1 + 0 ],
  1931. y1 = src1[ srcOffset1 + 1 ],
  1932. z1 = src1[ srcOffset1 + 2 ],
  1933. w1 = src1[ srcOffset1 + 3 ];
  1934. if ( t === 0 ) {
  1935. dst[ dstOffset + 0 ] = x0;
  1936. dst[ dstOffset + 1 ] = y0;
  1937. dst[ dstOffset + 2 ] = z0;
  1938. dst[ dstOffset + 3 ] = w0;
  1939. return;
  1940. }
  1941. if ( t === 1 ) {
  1942. dst[ dstOffset + 0 ] = x1;
  1943. dst[ dstOffset + 1 ] = y1;
  1944. dst[ dstOffset + 2 ] = z1;
  1945. dst[ dstOffset + 3 ] = w1;
  1946. return;
  1947. }
  1948. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1949. let s = 1 - t;
  1950. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1951. dir = ( cos >= 0 ? 1 : - 1 ),
  1952. sqrSin = 1 - cos * cos;
  1953. // Skip the Slerp for tiny steps to avoid numeric problems:
  1954. if ( sqrSin > Number.EPSILON ) {
  1955. const sin = Math.sqrt( sqrSin ),
  1956. len = Math.atan2( sin, cos * dir );
  1957. s = Math.sin( s * len ) / sin;
  1958. t = Math.sin( t * len ) / sin;
  1959. }
  1960. const tDir = t * dir;
  1961. x0 = x0 * s + x1 * tDir;
  1962. y0 = y0 * s + y1 * tDir;
  1963. z0 = z0 * s + z1 * tDir;
  1964. w0 = w0 * s + w1 * tDir;
  1965. // Normalize in case we just did a lerp:
  1966. if ( s === 1 - t ) {
  1967. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1968. x0 *= f;
  1969. y0 *= f;
  1970. z0 *= f;
  1971. w0 *= f;
  1972. }
  1973. }
  1974. dst[ dstOffset ] = x0;
  1975. dst[ dstOffset + 1 ] = y0;
  1976. dst[ dstOffset + 2 ] = z0;
  1977. dst[ dstOffset + 3 ] = w0;
  1978. }
  1979. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1980. const x0 = src0[ srcOffset0 ];
  1981. const y0 = src0[ srcOffset0 + 1 ];
  1982. const z0 = src0[ srcOffset0 + 2 ];
  1983. const w0 = src0[ srcOffset0 + 3 ];
  1984. const x1 = src1[ srcOffset1 ];
  1985. const y1 = src1[ srcOffset1 + 1 ];
  1986. const z1 = src1[ srcOffset1 + 2 ];
  1987. const w1 = src1[ srcOffset1 + 3 ];
  1988. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1989. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1990. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1991. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1992. return dst;
  1993. }
  1994. get x() {
  1995. return this._x;
  1996. }
  1997. set x( value ) {
  1998. this._x = value;
  1999. this._onChangeCallback();
  2000. }
  2001. get y() {
  2002. return this._y;
  2003. }
  2004. set y( value ) {
  2005. this._y = value;
  2006. this._onChangeCallback();
  2007. }
  2008. get z() {
  2009. return this._z;
  2010. }
  2011. set z( value ) {
  2012. this._z = value;
  2013. this._onChangeCallback();
  2014. }
  2015. get w() {
  2016. return this._w;
  2017. }
  2018. set w( value ) {
  2019. this._w = value;
  2020. this._onChangeCallback();
  2021. }
  2022. set( x, y, z, w ) {
  2023. this._x = x;
  2024. this._y = y;
  2025. this._z = z;
  2026. this._w = w;
  2027. this._onChangeCallback();
  2028. return this;
  2029. }
  2030. clone() {
  2031. return new this.constructor( this._x, this._y, this._z, this._w );
  2032. }
  2033. copy( quaternion ) {
  2034. this._x = quaternion.x;
  2035. this._y = quaternion.y;
  2036. this._z = quaternion.z;
  2037. this._w = quaternion.w;
  2038. this._onChangeCallback();
  2039. return this;
  2040. }
  2041. setFromEuler( euler, update = true ) {
  2042. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2043. // http://www.mathworks.com/matlabcentral/fileexchange/
  2044. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2045. // content/SpinCalc.m
  2046. const cos = Math.cos;
  2047. const sin = Math.sin;
  2048. const c1 = cos( x / 2 );
  2049. const c2 = cos( y / 2 );
  2050. const c3 = cos( z / 2 );
  2051. const s1 = sin( x / 2 );
  2052. const s2 = sin( y / 2 );
  2053. const s3 = sin( z / 2 );
  2054. switch ( order ) {
  2055. case 'XYZ':
  2056. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2057. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2058. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2059. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2060. break;
  2061. case 'YXZ':
  2062. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2063. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2064. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2065. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2066. break;
  2067. case 'ZXY':
  2068. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2069. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2070. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2071. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2072. break;
  2073. case 'ZYX':
  2074. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2075. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2076. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2077. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2078. break;
  2079. case 'YZX':
  2080. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2081. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2082. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2083. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2084. break;
  2085. case 'XZY':
  2086. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2087. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2088. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2089. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2090. break;
  2091. default:
  2092. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2093. }
  2094. if ( update === true ) this._onChangeCallback();
  2095. return this;
  2096. }
  2097. setFromAxisAngle( axis, angle ) {
  2098. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2099. // assumes axis is normalized
  2100. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2101. this._x = axis.x * s;
  2102. this._y = axis.y * s;
  2103. this._z = axis.z * s;
  2104. this._w = Math.cos( halfAngle );
  2105. this._onChangeCallback();
  2106. return this;
  2107. }
  2108. setFromRotationMatrix( m ) {
  2109. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2110. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2111. const te = m.elements,
  2112. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2113. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2114. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2115. trace = m11 + m22 + m33;
  2116. if ( trace > 0 ) {
  2117. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2118. this._w = 0.25 / s;
  2119. this._x = ( m32 - m23 ) * s;
  2120. this._y = ( m13 - m31 ) * s;
  2121. this._z = ( m21 - m12 ) * s;
  2122. } else if ( m11 > m22 && m11 > m33 ) {
  2123. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2124. this._w = ( m32 - m23 ) / s;
  2125. this._x = 0.25 * s;
  2126. this._y = ( m12 + m21 ) / s;
  2127. this._z = ( m13 + m31 ) / s;
  2128. } else if ( m22 > m33 ) {
  2129. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2130. this._w = ( m13 - m31 ) / s;
  2131. this._x = ( m12 + m21 ) / s;
  2132. this._y = 0.25 * s;
  2133. this._z = ( m23 + m32 ) / s;
  2134. } else {
  2135. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2136. this._w = ( m21 - m12 ) / s;
  2137. this._x = ( m13 + m31 ) / s;
  2138. this._y = ( m23 + m32 ) / s;
  2139. this._z = 0.25 * s;
  2140. }
  2141. this._onChangeCallback();
  2142. return this;
  2143. }
  2144. setFromUnitVectors( vFrom, vTo ) {
  2145. // assumes direction vectors vFrom and vTo are normalized
  2146. let r = vFrom.dot( vTo ) + 1;
  2147. if ( r < Number.EPSILON ) {
  2148. // vFrom and vTo point in opposite directions
  2149. r = 0;
  2150. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2151. this._x = - vFrom.y;
  2152. this._y = vFrom.x;
  2153. this._z = 0;
  2154. this._w = r;
  2155. } else {
  2156. this._x = 0;
  2157. this._y = - vFrom.z;
  2158. this._z = vFrom.y;
  2159. this._w = r;
  2160. }
  2161. } else {
  2162. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2163. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2164. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2165. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2166. this._w = r;
  2167. }
  2168. return this.normalize();
  2169. }
  2170. angleTo( q ) {
  2171. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2172. }
  2173. rotateTowards( q, step ) {
  2174. const angle = this.angleTo( q );
  2175. if ( angle === 0 ) return this;
  2176. const t = Math.min( 1, step / angle );
  2177. this.slerp( q, t );
  2178. return this;
  2179. }
  2180. identity() {
  2181. return this.set( 0, 0, 0, 1 );
  2182. }
  2183. invert() {
  2184. // quaternion is assumed to have unit length
  2185. return this.conjugate();
  2186. }
  2187. conjugate() {
  2188. this._x *= - 1;
  2189. this._y *= - 1;
  2190. this._z *= - 1;
  2191. this._onChangeCallback();
  2192. return this;
  2193. }
  2194. dot( v ) {
  2195. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2196. }
  2197. lengthSq() {
  2198. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2199. }
  2200. length() {
  2201. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2202. }
  2203. normalize() {
  2204. let l = this.length();
  2205. if ( l === 0 ) {
  2206. this._x = 0;
  2207. this._y = 0;
  2208. this._z = 0;
  2209. this._w = 1;
  2210. } else {
  2211. l = 1 / l;
  2212. this._x = this._x * l;
  2213. this._y = this._y * l;
  2214. this._z = this._z * l;
  2215. this._w = this._w * l;
  2216. }
  2217. this._onChangeCallback();
  2218. return this;
  2219. }
  2220. multiply( q ) {
  2221. return this.multiplyQuaternions( this, q );
  2222. }
  2223. premultiply( q ) {
  2224. return this.multiplyQuaternions( q, this );
  2225. }
  2226. multiplyQuaternions( a, b ) {
  2227. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2228. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2229. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2230. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2231. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2232. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2233. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2234. this._onChangeCallback();
  2235. return this;
  2236. }
  2237. slerp( qb, t ) {
  2238. if ( t === 0 ) return this;
  2239. if ( t === 1 ) return this.copy( qb );
  2240. const x = this._x, y = this._y, z = this._z, w = this._w;
  2241. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2242. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2243. if ( cosHalfTheta < 0 ) {
  2244. this._w = - qb._w;
  2245. this._x = - qb._x;
  2246. this._y = - qb._y;
  2247. this._z = - qb._z;
  2248. cosHalfTheta = - cosHalfTheta;
  2249. } else {
  2250. this.copy( qb );
  2251. }
  2252. if ( cosHalfTheta >= 1.0 ) {
  2253. this._w = w;
  2254. this._x = x;
  2255. this._y = y;
  2256. this._z = z;
  2257. return this;
  2258. }
  2259. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2260. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2261. const s = 1 - t;
  2262. this._w = s * w + t * this._w;
  2263. this._x = s * x + t * this._x;
  2264. this._y = s * y + t * this._y;
  2265. this._z = s * z + t * this._z;
  2266. this.normalize(); // normalize calls _onChangeCallback()
  2267. return this;
  2268. }
  2269. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2270. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2271. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2272. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2273. this._w = ( w * ratioA + this._w * ratioB );
  2274. this._x = ( x * ratioA + this._x * ratioB );
  2275. this._y = ( y * ratioA + this._y * ratioB );
  2276. this._z = ( z * ratioA + this._z * ratioB );
  2277. this._onChangeCallback();
  2278. return this;
  2279. }
  2280. slerpQuaternions( qa, qb, t ) {
  2281. return this.copy( qa ).slerp( qb, t );
  2282. }
  2283. random() {
  2284. // sets this quaternion to a uniform random unit quaternnion
  2285. // Ken Shoemake
  2286. // Uniform random rotations
  2287. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2288. const theta1 = 2 * Math.PI * Math.random();
  2289. const theta2 = 2 * Math.PI * Math.random();
  2290. const x0 = Math.random();
  2291. const r1 = Math.sqrt( 1 - x0 );
  2292. const r2 = Math.sqrt( x0 );
  2293. return this.set(
  2294. r1 * Math.sin( theta1 ),
  2295. r1 * Math.cos( theta1 ),
  2296. r2 * Math.sin( theta2 ),
  2297. r2 * Math.cos( theta2 ),
  2298. );
  2299. }
  2300. equals( quaternion ) {
  2301. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2302. }
  2303. fromArray( array, offset = 0 ) {
  2304. this._x = array[ offset ];
  2305. this._y = array[ offset + 1 ];
  2306. this._z = array[ offset + 2 ];
  2307. this._w = array[ offset + 3 ];
  2308. this._onChangeCallback();
  2309. return this;
  2310. }
  2311. toArray( array = [], offset = 0 ) {
  2312. array[ offset ] = this._x;
  2313. array[ offset + 1 ] = this._y;
  2314. array[ offset + 2 ] = this._z;
  2315. array[ offset + 3 ] = this._w;
  2316. return array;
  2317. }
  2318. fromBufferAttribute( attribute, index ) {
  2319. this._x = attribute.getX( index );
  2320. this._y = attribute.getY( index );
  2321. this._z = attribute.getZ( index );
  2322. this._w = attribute.getW( index );
  2323. this._onChangeCallback();
  2324. return this;
  2325. }
  2326. toJSON() {
  2327. return this.toArray();
  2328. }
  2329. _onChange( callback ) {
  2330. this._onChangeCallback = callback;
  2331. return this;
  2332. }
  2333. _onChangeCallback() {}
  2334. *[ Symbol.iterator ]() {
  2335. yield this._x;
  2336. yield this._y;
  2337. yield this._z;
  2338. yield this._w;
  2339. }
  2340. }
  2341. class Vector3 {
  2342. constructor( x = 0, y = 0, z = 0 ) {
  2343. Vector3.prototype.isVector3 = true;
  2344. this.x = x;
  2345. this.y = y;
  2346. this.z = z;
  2347. }
  2348. set( x, y, z ) {
  2349. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2350. this.x = x;
  2351. this.y = y;
  2352. this.z = z;
  2353. return this;
  2354. }
  2355. setScalar( scalar ) {
  2356. this.x = scalar;
  2357. this.y = scalar;
  2358. this.z = scalar;
  2359. return this;
  2360. }
  2361. setX( x ) {
  2362. this.x = x;
  2363. return this;
  2364. }
  2365. setY( y ) {
  2366. this.y = y;
  2367. return this;
  2368. }
  2369. setZ( z ) {
  2370. this.z = z;
  2371. return this;
  2372. }
  2373. setComponent( index, value ) {
  2374. switch ( index ) {
  2375. case 0: this.x = value; break;
  2376. case 1: this.y = value; break;
  2377. case 2: this.z = value; break;
  2378. default: throw new Error( 'index is out of range: ' + index );
  2379. }
  2380. return this;
  2381. }
  2382. getComponent( index ) {
  2383. switch ( index ) {
  2384. case 0: return this.x;
  2385. case 1: return this.y;
  2386. case 2: return this.z;
  2387. default: throw new Error( 'index is out of range: ' + index );
  2388. }
  2389. }
  2390. clone() {
  2391. return new this.constructor( this.x, this.y, this.z );
  2392. }
  2393. copy( v ) {
  2394. this.x = v.x;
  2395. this.y = v.y;
  2396. this.z = v.z;
  2397. return this;
  2398. }
  2399. add( v ) {
  2400. this.x += v.x;
  2401. this.y += v.y;
  2402. this.z += v.z;
  2403. return this;
  2404. }
  2405. addScalar( s ) {
  2406. this.x += s;
  2407. this.y += s;
  2408. this.z += s;
  2409. return this;
  2410. }
  2411. addVectors( a, b ) {
  2412. this.x = a.x + b.x;
  2413. this.y = a.y + b.y;
  2414. this.z = a.z + b.z;
  2415. return this;
  2416. }
  2417. addScaledVector( v, s ) {
  2418. this.x += v.x * s;
  2419. this.y += v.y * s;
  2420. this.z += v.z * s;
  2421. return this;
  2422. }
  2423. sub( v ) {
  2424. this.x -= v.x;
  2425. this.y -= v.y;
  2426. this.z -= v.z;
  2427. return this;
  2428. }
  2429. subScalar( s ) {
  2430. this.x -= s;
  2431. this.y -= s;
  2432. this.z -= s;
  2433. return this;
  2434. }
  2435. subVectors( a, b ) {
  2436. this.x = a.x - b.x;
  2437. this.y = a.y - b.y;
  2438. this.z = a.z - b.z;
  2439. return this;
  2440. }
  2441. multiply( v ) {
  2442. this.x *= v.x;
  2443. this.y *= v.y;
  2444. this.z *= v.z;
  2445. return this;
  2446. }
  2447. multiplyScalar( scalar ) {
  2448. this.x *= scalar;
  2449. this.y *= scalar;
  2450. this.z *= scalar;
  2451. return this;
  2452. }
  2453. multiplyVectors( a, b ) {
  2454. this.x = a.x * b.x;
  2455. this.y = a.y * b.y;
  2456. this.z = a.z * b.z;
  2457. return this;
  2458. }
  2459. applyEuler( euler ) {
  2460. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2461. }
  2462. applyAxisAngle( axis, angle ) {
  2463. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2464. }
  2465. applyMatrix3( m ) {
  2466. const x = this.x, y = this.y, z = this.z;
  2467. const e = m.elements;
  2468. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2469. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2470. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2471. return this;
  2472. }
  2473. applyNormalMatrix( m ) {
  2474. return this.applyMatrix3( m ).normalize();
  2475. }
  2476. applyMatrix4( m ) {
  2477. const x = this.x, y = this.y, z = this.z;
  2478. const e = m.elements;
  2479. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2480. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2481. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2482. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2483. return this;
  2484. }
  2485. applyQuaternion( q ) {
  2486. // quaternion q is assumed to have unit length
  2487. const vx = this.x, vy = this.y, vz = this.z;
  2488. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2489. // t = 2 * cross( q.xyz, v );
  2490. const tx = 2 * ( qy * vz - qz * vy );
  2491. const ty = 2 * ( qz * vx - qx * vz );
  2492. const tz = 2 * ( qx * vy - qy * vx );
  2493. // v + q.w * t + cross( q.xyz, t );
  2494. this.x = vx + qw * tx + qy * tz - qz * ty;
  2495. this.y = vy + qw * ty + qz * tx - qx * tz;
  2496. this.z = vz + qw * tz + qx * ty - qy * tx;
  2497. return this;
  2498. }
  2499. project( camera ) {
  2500. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2501. }
  2502. unproject( camera ) {
  2503. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2504. }
  2505. transformDirection( m ) {
  2506. // input: THREE.Matrix4 affine matrix
  2507. // vector interpreted as a direction
  2508. const x = this.x, y = this.y, z = this.z;
  2509. const e = m.elements;
  2510. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2511. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2512. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2513. return this.normalize();
  2514. }
  2515. divide( v ) {
  2516. this.x /= v.x;
  2517. this.y /= v.y;
  2518. this.z /= v.z;
  2519. return this;
  2520. }
  2521. divideScalar( scalar ) {
  2522. return this.multiplyScalar( 1 / scalar );
  2523. }
  2524. min( v ) {
  2525. this.x = Math.min( this.x, v.x );
  2526. this.y = Math.min( this.y, v.y );
  2527. this.z = Math.min( this.z, v.z );
  2528. return this;
  2529. }
  2530. max( v ) {
  2531. this.x = Math.max( this.x, v.x );
  2532. this.y = Math.max( this.y, v.y );
  2533. this.z = Math.max( this.z, v.z );
  2534. return this;
  2535. }
  2536. clamp( min, max ) {
  2537. // assumes min < max, componentwise
  2538. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2539. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2540. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2541. return this;
  2542. }
  2543. clampScalar( minVal, maxVal ) {
  2544. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2545. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2546. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2547. return this;
  2548. }
  2549. clampLength( min, max ) {
  2550. const length = this.length();
  2551. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2552. }
  2553. floor() {
  2554. this.x = Math.floor( this.x );
  2555. this.y = Math.floor( this.y );
  2556. this.z = Math.floor( this.z );
  2557. return this;
  2558. }
  2559. ceil() {
  2560. this.x = Math.ceil( this.x );
  2561. this.y = Math.ceil( this.y );
  2562. this.z = Math.ceil( this.z );
  2563. return this;
  2564. }
  2565. round() {
  2566. this.x = Math.round( this.x );
  2567. this.y = Math.round( this.y );
  2568. this.z = Math.round( this.z );
  2569. return this;
  2570. }
  2571. roundToZero() {
  2572. this.x = Math.trunc( this.x );
  2573. this.y = Math.trunc( this.y );
  2574. this.z = Math.trunc( this.z );
  2575. return this;
  2576. }
  2577. negate() {
  2578. this.x = - this.x;
  2579. this.y = - this.y;
  2580. this.z = - this.z;
  2581. return this;
  2582. }
  2583. dot( v ) {
  2584. return this.x * v.x + this.y * v.y + this.z * v.z;
  2585. }
  2586. // TODO lengthSquared?
  2587. lengthSq() {
  2588. return this.x * this.x + this.y * this.y + this.z * this.z;
  2589. }
  2590. length() {
  2591. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2592. }
  2593. manhattanLength() {
  2594. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2595. }
  2596. normalize() {
  2597. return this.divideScalar( this.length() || 1 );
  2598. }
  2599. setLength( length ) {
  2600. return this.normalize().multiplyScalar( length );
  2601. }
  2602. lerp( v, alpha ) {
  2603. this.x += ( v.x - this.x ) * alpha;
  2604. this.y += ( v.y - this.y ) * alpha;
  2605. this.z += ( v.z - this.z ) * alpha;
  2606. return this;
  2607. }
  2608. lerpVectors( v1, v2, alpha ) {
  2609. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2610. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2611. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2612. return this;
  2613. }
  2614. cross( v ) {
  2615. return this.crossVectors( this, v );
  2616. }
  2617. crossVectors( a, b ) {
  2618. const ax = a.x, ay = a.y, az = a.z;
  2619. const bx = b.x, by = b.y, bz = b.z;
  2620. this.x = ay * bz - az * by;
  2621. this.y = az * bx - ax * bz;
  2622. this.z = ax * by - ay * bx;
  2623. return this;
  2624. }
  2625. projectOnVector( v ) {
  2626. const denominator = v.lengthSq();
  2627. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2628. const scalar = v.dot( this ) / denominator;
  2629. return this.copy( v ).multiplyScalar( scalar );
  2630. }
  2631. projectOnPlane( planeNormal ) {
  2632. _vector$c.copy( this ).projectOnVector( planeNormal );
  2633. return this.sub( _vector$c );
  2634. }
  2635. reflect( normal ) {
  2636. // reflect incident vector off plane orthogonal to normal
  2637. // normal is assumed to have unit length
  2638. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2639. }
  2640. angleTo( v ) {
  2641. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2642. if ( denominator === 0 ) return Math.PI / 2;
  2643. const theta = this.dot( v ) / denominator;
  2644. // clamp, to handle numerical problems
  2645. return Math.acos( clamp( theta, - 1, 1 ) );
  2646. }
  2647. distanceTo( v ) {
  2648. return Math.sqrt( this.distanceToSquared( v ) );
  2649. }
  2650. distanceToSquared( v ) {
  2651. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2652. return dx * dx + dy * dy + dz * dz;
  2653. }
  2654. manhattanDistanceTo( v ) {
  2655. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2656. }
  2657. setFromSpherical( s ) {
  2658. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2659. }
  2660. setFromSphericalCoords( radius, phi, theta ) {
  2661. const sinPhiRadius = Math.sin( phi ) * radius;
  2662. this.x = sinPhiRadius * Math.sin( theta );
  2663. this.y = Math.cos( phi ) * radius;
  2664. this.z = sinPhiRadius * Math.cos( theta );
  2665. return this;
  2666. }
  2667. setFromCylindrical( c ) {
  2668. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2669. }
  2670. setFromCylindricalCoords( radius, theta, y ) {
  2671. this.x = radius * Math.sin( theta );
  2672. this.y = y;
  2673. this.z = radius * Math.cos( theta );
  2674. return this;
  2675. }
  2676. setFromMatrixPosition( m ) {
  2677. const e = m.elements;
  2678. this.x = e[ 12 ];
  2679. this.y = e[ 13 ];
  2680. this.z = e[ 14 ];
  2681. return this;
  2682. }
  2683. setFromMatrixScale( m ) {
  2684. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2685. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2686. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2687. this.x = sx;
  2688. this.y = sy;
  2689. this.z = sz;
  2690. return this;
  2691. }
  2692. setFromMatrixColumn( m, index ) {
  2693. return this.fromArray( m.elements, index * 4 );
  2694. }
  2695. setFromMatrix3Column( m, index ) {
  2696. return this.fromArray( m.elements, index * 3 );
  2697. }
  2698. setFromEuler( e ) {
  2699. this.x = e._x;
  2700. this.y = e._y;
  2701. this.z = e._z;
  2702. return this;
  2703. }
  2704. setFromColor( c ) {
  2705. this.x = c.r;
  2706. this.y = c.g;
  2707. this.z = c.b;
  2708. return this;
  2709. }
  2710. equals( v ) {
  2711. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2712. }
  2713. fromArray( array, offset = 0 ) {
  2714. this.x = array[ offset ];
  2715. this.y = array[ offset + 1 ];
  2716. this.z = array[ offset + 2 ];
  2717. return this;
  2718. }
  2719. toArray( array = [], offset = 0 ) {
  2720. array[ offset ] = this.x;
  2721. array[ offset + 1 ] = this.y;
  2722. array[ offset + 2 ] = this.z;
  2723. return array;
  2724. }
  2725. fromBufferAttribute( attribute, index ) {
  2726. this.x = attribute.getX( index );
  2727. this.y = attribute.getY( index );
  2728. this.z = attribute.getZ( index );
  2729. return this;
  2730. }
  2731. random() {
  2732. this.x = Math.random();
  2733. this.y = Math.random();
  2734. this.z = Math.random();
  2735. return this;
  2736. }
  2737. randomDirection() {
  2738. // https://mathworld.wolfram.com/SpherePointPicking.html
  2739. const theta = Math.random() * Math.PI * 2;
  2740. const u = Math.random() * 2 - 1;
  2741. const c = Math.sqrt( 1 - u * u );
  2742. this.x = c * Math.cos( theta );
  2743. this.y = u;
  2744. this.z = c * Math.sin( theta );
  2745. return this;
  2746. }
  2747. *[ Symbol.iterator ]() {
  2748. yield this.x;
  2749. yield this.y;
  2750. yield this.z;
  2751. }
  2752. }
  2753. const _vector$c = /*@__PURE__*/ new Vector3();
  2754. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2755. class Box3 {
  2756. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2757. this.isBox3 = true;
  2758. this.min = min;
  2759. this.max = max;
  2760. }
  2761. set( min, max ) {
  2762. this.min.copy( min );
  2763. this.max.copy( max );
  2764. return this;
  2765. }
  2766. setFromArray( array ) {
  2767. this.makeEmpty();
  2768. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2769. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2770. }
  2771. return this;
  2772. }
  2773. setFromBufferAttribute( attribute ) {
  2774. this.makeEmpty();
  2775. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2776. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2777. }
  2778. return this;
  2779. }
  2780. setFromPoints( points ) {
  2781. this.makeEmpty();
  2782. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2783. this.expandByPoint( points[ i ] );
  2784. }
  2785. return this;
  2786. }
  2787. setFromCenterAndSize( center, size ) {
  2788. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2789. this.min.copy( center ).sub( halfSize );
  2790. this.max.copy( center ).add( halfSize );
  2791. return this;
  2792. }
  2793. setFromObject( object, precise = false ) {
  2794. this.makeEmpty();
  2795. return this.expandByObject( object, precise );
  2796. }
  2797. clone() {
  2798. return new this.constructor().copy( this );
  2799. }
  2800. copy( box ) {
  2801. this.min.copy( box.min );
  2802. this.max.copy( box.max );
  2803. return this;
  2804. }
  2805. makeEmpty() {
  2806. this.min.x = this.min.y = this.min.z = + Infinity;
  2807. this.max.x = this.max.y = this.max.z = - Infinity;
  2808. return this;
  2809. }
  2810. isEmpty() {
  2811. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2812. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2813. }
  2814. getCenter( target ) {
  2815. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2816. }
  2817. getSize( target ) {
  2818. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2819. }
  2820. expandByPoint( point ) {
  2821. this.min.min( point );
  2822. this.max.max( point );
  2823. return this;
  2824. }
  2825. expandByVector( vector ) {
  2826. this.min.sub( vector );
  2827. this.max.add( vector );
  2828. return this;
  2829. }
  2830. expandByScalar( scalar ) {
  2831. this.min.addScalar( - scalar );
  2832. this.max.addScalar( scalar );
  2833. return this;
  2834. }
  2835. expandByObject( object, precise = false ) {
  2836. // Computes the world-axis-aligned bounding box of an object (including its children),
  2837. // accounting for both the object's, and children's, world transforms
  2838. object.updateWorldMatrix( false, false );
  2839. const geometry = object.geometry;
  2840. if ( geometry !== undefined ) {
  2841. const positionAttribute = geometry.getAttribute( 'position' );
  2842. // precise AABB computation based on vertex data requires at least a position attribute.
  2843. // instancing isn't supported so far and uses the normal (conservative) code path.
  2844. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2845. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2846. if ( object.isMesh === true ) {
  2847. object.getVertexPosition( i, _vector$b );
  2848. } else {
  2849. _vector$b.fromBufferAttribute( positionAttribute, i );
  2850. }
  2851. _vector$b.applyMatrix4( object.matrixWorld );
  2852. this.expandByPoint( _vector$b );
  2853. }
  2854. } else {
  2855. if ( object.boundingBox !== undefined ) {
  2856. // object-level bounding box
  2857. if ( object.boundingBox === null ) {
  2858. object.computeBoundingBox();
  2859. }
  2860. _box$4.copy( object.boundingBox );
  2861. } else {
  2862. // geometry-level bounding box
  2863. if ( geometry.boundingBox === null ) {
  2864. geometry.computeBoundingBox();
  2865. }
  2866. _box$4.copy( geometry.boundingBox );
  2867. }
  2868. _box$4.applyMatrix4( object.matrixWorld );
  2869. this.union( _box$4 );
  2870. }
  2871. }
  2872. const children = object.children;
  2873. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2874. this.expandByObject( children[ i ], precise );
  2875. }
  2876. return this;
  2877. }
  2878. containsPoint( point ) {
  2879. return point.x < this.min.x || point.x > this.max.x ||
  2880. point.y < this.min.y || point.y > this.max.y ||
  2881. point.z < this.min.z || point.z > this.max.z ? false : true;
  2882. }
  2883. containsBox( box ) {
  2884. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2885. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2886. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2887. }
  2888. getParameter( point, target ) {
  2889. // This can potentially have a divide by zero if the box
  2890. // has a size dimension of 0.
  2891. return target.set(
  2892. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2893. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2894. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2895. );
  2896. }
  2897. intersectsBox( box ) {
  2898. // using 6 splitting planes to rule out intersections.
  2899. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2900. box.max.y < this.min.y || box.min.y > this.max.y ||
  2901. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2902. }
  2903. intersectsSphere( sphere ) {
  2904. // Find the point on the AABB closest to the sphere center.
  2905. this.clampPoint( sphere.center, _vector$b );
  2906. // If that point is inside the sphere, the AABB and sphere intersect.
  2907. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2908. }
  2909. intersectsPlane( plane ) {
  2910. // We compute the minimum and maximum dot product values. If those values
  2911. // are on the same side (back or front) of the plane, then there is no intersection.
  2912. let min, max;
  2913. if ( plane.normal.x > 0 ) {
  2914. min = plane.normal.x * this.min.x;
  2915. max = plane.normal.x * this.max.x;
  2916. } else {
  2917. min = plane.normal.x * this.max.x;
  2918. max = plane.normal.x * this.min.x;
  2919. }
  2920. if ( plane.normal.y > 0 ) {
  2921. min += plane.normal.y * this.min.y;
  2922. max += plane.normal.y * this.max.y;
  2923. } else {
  2924. min += plane.normal.y * this.max.y;
  2925. max += plane.normal.y * this.min.y;
  2926. }
  2927. if ( plane.normal.z > 0 ) {
  2928. min += plane.normal.z * this.min.z;
  2929. max += plane.normal.z * this.max.z;
  2930. } else {
  2931. min += plane.normal.z * this.max.z;
  2932. max += plane.normal.z * this.min.z;
  2933. }
  2934. return ( min <= - plane.constant && max >= - plane.constant );
  2935. }
  2936. intersectsTriangle( triangle ) {
  2937. if ( this.isEmpty() ) {
  2938. return false;
  2939. }
  2940. // compute box center and extents
  2941. this.getCenter( _center );
  2942. _extents.subVectors( this.max, _center );
  2943. // translate triangle to aabb origin
  2944. _v0$2.subVectors( triangle.a, _center );
  2945. _v1$7.subVectors( triangle.b, _center );
  2946. _v2$4.subVectors( triangle.c, _center );
  2947. // compute edge vectors for triangle
  2948. _f0.subVectors( _v1$7, _v0$2 );
  2949. _f1.subVectors( _v2$4, _v1$7 );
  2950. _f2.subVectors( _v0$2, _v2$4 );
  2951. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2952. // 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
  2953. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2954. let axes = [
  2955. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2956. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2957. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2958. ];
  2959. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2960. return false;
  2961. }
  2962. // test 3 face normals from the aabb
  2963. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2964. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2965. return false;
  2966. }
  2967. // finally testing the face normal of the triangle
  2968. // use already existing triangle edge vectors here
  2969. _triangleNormal.crossVectors( _f0, _f1 );
  2970. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2971. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2972. }
  2973. clampPoint( point, target ) {
  2974. return target.copy( point ).clamp( this.min, this.max );
  2975. }
  2976. distanceToPoint( point ) {
  2977. return this.clampPoint( point, _vector$b ).distanceTo( point );
  2978. }
  2979. getBoundingSphere( target ) {
  2980. if ( this.isEmpty() ) {
  2981. target.makeEmpty();
  2982. } else {
  2983. this.getCenter( target.center );
  2984. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2985. }
  2986. return target;
  2987. }
  2988. intersect( box ) {
  2989. this.min.max( box.min );
  2990. this.max.min( box.max );
  2991. // 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.
  2992. if ( this.isEmpty() ) this.makeEmpty();
  2993. return this;
  2994. }
  2995. union( box ) {
  2996. this.min.min( box.min );
  2997. this.max.max( box.max );
  2998. return this;
  2999. }
  3000. applyMatrix4( matrix ) {
  3001. // transform of empty box is an empty box.
  3002. if ( this.isEmpty() ) return this;
  3003. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3004. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3005. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3006. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3007. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3008. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3009. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3010. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3011. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3012. this.setFromPoints( _points );
  3013. return this;
  3014. }
  3015. translate( offset ) {
  3016. this.min.add( offset );
  3017. this.max.add( offset );
  3018. return this;
  3019. }
  3020. equals( box ) {
  3021. return box.min.equals( this.min ) && box.max.equals( this.max );
  3022. }
  3023. }
  3024. const _points = [
  3025. /*@__PURE__*/ new Vector3(),
  3026. /*@__PURE__*/ new Vector3(),
  3027. /*@__PURE__*/ new Vector3(),
  3028. /*@__PURE__*/ new Vector3(),
  3029. /*@__PURE__*/ new Vector3(),
  3030. /*@__PURE__*/ new Vector3(),
  3031. /*@__PURE__*/ new Vector3(),
  3032. /*@__PURE__*/ new Vector3()
  3033. ];
  3034. const _vector$b = /*@__PURE__*/ new Vector3();
  3035. const _box$4 = /*@__PURE__*/ new Box3();
  3036. // triangle centered vertices
  3037. const _v0$2 = /*@__PURE__*/ new Vector3();
  3038. const _v1$7 = /*@__PURE__*/ new Vector3();
  3039. const _v2$4 = /*@__PURE__*/ new Vector3();
  3040. // triangle edge vectors
  3041. const _f0 = /*@__PURE__*/ new Vector3();
  3042. const _f1 = /*@__PURE__*/ new Vector3();
  3043. const _f2 = /*@__PURE__*/ new Vector3();
  3044. const _center = /*@__PURE__*/ new Vector3();
  3045. const _extents = /*@__PURE__*/ new Vector3();
  3046. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3047. const _testAxis = /*@__PURE__*/ new Vector3();
  3048. function satForAxes( axes, v0, v1, v2, extents ) {
  3049. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3050. _testAxis.fromArray( axes, i );
  3051. // project the aabb onto the separating axis
  3052. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3053. // project all 3 vertices of the triangle onto the separating axis
  3054. const p0 = v0.dot( _testAxis );
  3055. const p1 = v1.dot( _testAxis );
  3056. const p2 = v2.dot( _testAxis );
  3057. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3058. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3059. // points of the projected triangle are outside the projected half-length of the aabb
  3060. // the axis is separating and we can exit
  3061. return false;
  3062. }
  3063. }
  3064. return true;
  3065. }
  3066. const _box$3 = /*@__PURE__*/ new Box3();
  3067. const _v1$6 = /*@__PURE__*/ new Vector3();
  3068. const _v2$3 = /*@__PURE__*/ new Vector3();
  3069. class Sphere {
  3070. constructor( center = new Vector3(), radius = - 1 ) {
  3071. this.isSphere = true;
  3072. this.center = center;
  3073. this.radius = radius;
  3074. }
  3075. set( center, radius ) {
  3076. this.center.copy( center );
  3077. this.radius = radius;
  3078. return this;
  3079. }
  3080. setFromPoints( points, optionalCenter ) {
  3081. const center = this.center;
  3082. if ( optionalCenter !== undefined ) {
  3083. center.copy( optionalCenter );
  3084. } else {
  3085. _box$3.setFromPoints( points ).getCenter( center );
  3086. }
  3087. let maxRadiusSq = 0;
  3088. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3089. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3090. }
  3091. this.radius = Math.sqrt( maxRadiusSq );
  3092. return this;
  3093. }
  3094. copy( sphere ) {
  3095. this.center.copy( sphere.center );
  3096. this.radius = sphere.radius;
  3097. return this;
  3098. }
  3099. isEmpty() {
  3100. return ( this.radius < 0 );
  3101. }
  3102. makeEmpty() {
  3103. this.center.set( 0, 0, 0 );
  3104. this.radius = - 1;
  3105. return this;
  3106. }
  3107. containsPoint( point ) {
  3108. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3109. }
  3110. distanceToPoint( point ) {
  3111. return ( point.distanceTo( this.center ) - this.radius );
  3112. }
  3113. intersectsSphere( sphere ) {
  3114. const radiusSum = this.radius + sphere.radius;
  3115. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3116. }
  3117. intersectsBox( box ) {
  3118. return box.intersectsSphere( this );
  3119. }
  3120. intersectsPlane( plane ) {
  3121. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3122. }
  3123. clampPoint( point, target ) {
  3124. const deltaLengthSq = this.center.distanceToSquared( point );
  3125. target.copy( point );
  3126. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3127. target.sub( this.center ).normalize();
  3128. target.multiplyScalar( this.radius ).add( this.center );
  3129. }
  3130. return target;
  3131. }
  3132. getBoundingBox( target ) {
  3133. if ( this.isEmpty() ) {
  3134. // Empty sphere produces empty bounding box
  3135. target.makeEmpty();
  3136. return target;
  3137. }
  3138. target.set( this.center, this.center );
  3139. target.expandByScalar( this.radius );
  3140. return target;
  3141. }
  3142. applyMatrix4( matrix ) {
  3143. this.center.applyMatrix4( matrix );
  3144. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3145. return this;
  3146. }
  3147. translate( offset ) {
  3148. this.center.add( offset );
  3149. return this;
  3150. }
  3151. expandByPoint( point ) {
  3152. if ( this.isEmpty() ) {
  3153. this.center.copy( point );
  3154. this.radius = 0;
  3155. return this;
  3156. }
  3157. _v1$6.subVectors( point, this.center );
  3158. const lengthSq = _v1$6.lengthSq();
  3159. if ( lengthSq > ( this.radius * this.radius ) ) {
  3160. // calculate the minimal sphere
  3161. const length = Math.sqrt( lengthSq );
  3162. const delta = ( length - this.radius ) * 0.5;
  3163. this.center.addScaledVector( _v1$6, delta / length );
  3164. this.radius += delta;
  3165. }
  3166. return this;
  3167. }
  3168. union( sphere ) {
  3169. if ( sphere.isEmpty() ) {
  3170. return this;
  3171. }
  3172. if ( this.isEmpty() ) {
  3173. this.copy( sphere );
  3174. return this;
  3175. }
  3176. if ( this.center.equals( sphere.center ) === true ) {
  3177. this.radius = Math.max( this.radius, sphere.radius );
  3178. } else {
  3179. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3180. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3181. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3182. }
  3183. return this;
  3184. }
  3185. equals( sphere ) {
  3186. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3187. }
  3188. clone() {
  3189. return new this.constructor().copy( this );
  3190. }
  3191. }
  3192. const _vector$a = /*@__PURE__*/ new Vector3();
  3193. const _segCenter = /*@__PURE__*/ new Vector3();
  3194. const _segDir = /*@__PURE__*/ new Vector3();
  3195. const _diff = /*@__PURE__*/ new Vector3();
  3196. const _edge1 = /*@__PURE__*/ new Vector3();
  3197. const _edge2 = /*@__PURE__*/ new Vector3();
  3198. const _normal$1 = /*@__PURE__*/ new Vector3();
  3199. class Ray {
  3200. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3201. this.origin = origin;
  3202. this.direction = direction;
  3203. }
  3204. set( origin, direction ) {
  3205. this.origin.copy( origin );
  3206. this.direction.copy( direction );
  3207. return this;
  3208. }
  3209. copy( ray ) {
  3210. this.origin.copy( ray.origin );
  3211. this.direction.copy( ray.direction );
  3212. return this;
  3213. }
  3214. at( t, target ) {
  3215. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3216. }
  3217. lookAt( v ) {
  3218. this.direction.copy( v ).sub( this.origin ).normalize();
  3219. return this;
  3220. }
  3221. recast( t ) {
  3222. this.origin.copy( this.at( t, _vector$a ) );
  3223. return this;
  3224. }
  3225. closestPointToPoint( point, target ) {
  3226. target.subVectors( point, this.origin );
  3227. const directionDistance = target.dot( this.direction );
  3228. if ( directionDistance < 0 ) {
  3229. return target.copy( this.origin );
  3230. }
  3231. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3232. }
  3233. distanceToPoint( point ) {
  3234. return Math.sqrt( this.distanceSqToPoint( point ) );
  3235. }
  3236. distanceSqToPoint( point ) {
  3237. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3238. // point behind the ray
  3239. if ( directionDistance < 0 ) {
  3240. return this.origin.distanceToSquared( point );
  3241. }
  3242. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3243. return _vector$a.distanceToSquared( point );
  3244. }
  3245. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3246. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3247. // It returns the min distance between the ray and the segment
  3248. // defined by v0 and v1
  3249. // It can also set two optional targets :
  3250. // - The closest point on the ray
  3251. // - The closest point on the segment
  3252. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3253. _segDir.copy( v1 ).sub( v0 ).normalize();
  3254. _diff.copy( this.origin ).sub( _segCenter );
  3255. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3256. const a01 = - this.direction.dot( _segDir );
  3257. const b0 = _diff.dot( this.direction );
  3258. const b1 = - _diff.dot( _segDir );
  3259. const c = _diff.lengthSq();
  3260. const det = Math.abs( 1 - a01 * a01 );
  3261. let s0, s1, sqrDist, extDet;
  3262. if ( det > 0 ) {
  3263. // The ray and segment are not parallel.
  3264. s0 = a01 * b1 - b0;
  3265. s1 = a01 * b0 - b1;
  3266. extDet = segExtent * det;
  3267. if ( s0 >= 0 ) {
  3268. if ( s1 >= - extDet ) {
  3269. if ( s1 <= extDet ) {
  3270. // region 0
  3271. // Minimum at interior points of ray and segment.
  3272. const invDet = 1 / det;
  3273. s0 *= invDet;
  3274. s1 *= invDet;
  3275. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3276. } else {
  3277. // region 1
  3278. s1 = segExtent;
  3279. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3280. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3281. }
  3282. } else {
  3283. // region 5
  3284. s1 = - segExtent;
  3285. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3286. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3287. }
  3288. } else {
  3289. if ( s1 <= - extDet ) {
  3290. // region 4
  3291. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3292. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3293. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3294. } else if ( s1 <= extDet ) {
  3295. // region 3
  3296. s0 = 0;
  3297. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3298. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3299. } else {
  3300. // region 2
  3301. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3302. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3303. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3304. }
  3305. }
  3306. } else {
  3307. // Ray and segment are parallel.
  3308. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3309. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3310. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3311. }
  3312. if ( optionalPointOnRay ) {
  3313. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3314. }
  3315. if ( optionalPointOnSegment ) {
  3316. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3317. }
  3318. return sqrDist;
  3319. }
  3320. intersectSphere( sphere, target ) {
  3321. _vector$a.subVectors( sphere.center, this.origin );
  3322. const tca = _vector$a.dot( this.direction );
  3323. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3324. const radius2 = sphere.radius * sphere.radius;
  3325. if ( d2 > radius2 ) return null;
  3326. const thc = Math.sqrt( radius2 - d2 );
  3327. // t0 = first intersect point - entrance on front of sphere
  3328. const t0 = tca - thc;
  3329. // t1 = second intersect point - exit point on back of sphere
  3330. const t1 = tca + thc;
  3331. // test to see if t1 is behind the ray - if so, return null
  3332. if ( t1 < 0 ) return null;
  3333. // test to see if t0 is behind the ray:
  3334. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3335. // in order to always return an intersect point that is in front of the ray.
  3336. if ( t0 < 0 ) return this.at( t1, target );
  3337. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3338. return this.at( t0, target );
  3339. }
  3340. intersectsSphere( sphere ) {
  3341. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3342. }
  3343. distanceToPlane( plane ) {
  3344. const denominator = plane.normal.dot( this.direction );
  3345. if ( denominator === 0 ) {
  3346. // line is coplanar, return origin
  3347. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3348. return 0;
  3349. }
  3350. // Null is preferable to undefined since undefined means.... it is undefined
  3351. return null;
  3352. }
  3353. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3354. // Return if the ray never intersects the plane
  3355. return t >= 0 ? t : null;
  3356. }
  3357. intersectPlane( plane, target ) {
  3358. const t = this.distanceToPlane( plane );
  3359. if ( t === null ) {
  3360. return null;
  3361. }
  3362. return this.at( t, target );
  3363. }
  3364. intersectsPlane( plane ) {
  3365. // check if the ray lies on the plane first
  3366. const distToPoint = plane.distanceToPoint( this.origin );
  3367. if ( distToPoint === 0 ) {
  3368. return true;
  3369. }
  3370. const denominator = plane.normal.dot( this.direction );
  3371. if ( denominator * distToPoint < 0 ) {
  3372. return true;
  3373. }
  3374. // ray origin is behind the plane (and is pointing behind it)
  3375. return false;
  3376. }
  3377. intersectBox( box, target ) {
  3378. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3379. const invdirx = 1 / this.direction.x,
  3380. invdiry = 1 / this.direction.y,
  3381. invdirz = 1 / this.direction.z;
  3382. const origin = this.origin;
  3383. if ( invdirx >= 0 ) {
  3384. tmin = ( box.min.x - origin.x ) * invdirx;
  3385. tmax = ( box.max.x - origin.x ) * invdirx;
  3386. } else {
  3387. tmin = ( box.max.x - origin.x ) * invdirx;
  3388. tmax = ( box.min.x - origin.x ) * invdirx;
  3389. }
  3390. if ( invdiry >= 0 ) {
  3391. tymin = ( box.min.y - origin.y ) * invdiry;
  3392. tymax = ( box.max.y - origin.y ) * invdiry;
  3393. } else {
  3394. tymin = ( box.max.y - origin.y ) * invdiry;
  3395. tymax = ( box.min.y - origin.y ) * invdiry;
  3396. }
  3397. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3398. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3399. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3400. if ( invdirz >= 0 ) {
  3401. tzmin = ( box.min.z - origin.z ) * invdirz;
  3402. tzmax = ( box.max.z - origin.z ) * invdirz;
  3403. } else {
  3404. tzmin = ( box.max.z - origin.z ) * invdirz;
  3405. tzmax = ( box.min.z - origin.z ) * invdirz;
  3406. }
  3407. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3408. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3409. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3410. //return point closest to the ray (positive side)
  3411. if ( tmax < 0 ) return null;
  3412. return this.at( tmin >= 0 ? tmin : tmax, target );
  3413. }
  3414. intersectsBox( box ) {
  3415. return this.intersectBox( box, _vector$a ) !== null;
  3416. }
  3417. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3418. // Compute the offset origin, edges, and normal.
  3419. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3420. _edge1.subVectors( b, a );
  3421. _edge2.subVectors( c, a );
  3422. _normal$1.crossVectors( _edge1, _edge2 );
  3423. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3424. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3425. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3426. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3427. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3428. let DdN = this.direction.dot( _normal$1 );
  3429. let sign;
  3430. if ( DdN > 0 ) {
  3431. if ( backfaceCulling ) return null;
  3432. sign = 1;
  3433. } else if ( DdN < 0 ) {
  3434. sign = - 1;
  3435. DdN = - DdN;
  3436. } else {
  3437. return null;
  3438. }
  3439. _diff.subVectors( this.origin, a );
  3440. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3441. // b1 < 0, no intersection
  3442. if ( DdQxE2 < 0 ) {
  3443. return null;
  3444. }
  3445. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3446. // b2 < 0, no intersection
  3447. if ( DdE1xQ < 0 ) {
  3448. return null;
  3449. }
  3450. // b1+b2 > 1, no intersection
  3451. if ( DdQxE2 + DdE1xQ > DdN ) {
  3452. return null;
  3453. }
  3454. // Line intersects triangle, check if ray does.
  3455. const QdN = - sign * _diff.dot( _normal$1 );
  3456. // t < 0, no intersection
  3457. if ( QdN < 0 ) {
  3458. return null;
  3459. }
  3460. // Ray intersects triangle.
  3461. return this.at( QdN / DdN, target );
  3462. }
  3463. applyMatrix4( matrix4 ) {
  3464. this.origin.applyMatrix4( matrix4 );
  3465. this.direction.transformDirection( matrix4 );
  3466. return this;
  3467. }
  3468. equals( ray ) {
  3469. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3470. }
  3471. clone() {
  3472. return new this.constructor().copy( this );
  3473. }
  3474. }
  3475. class Matrix4 {
  3476. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3477. Matrix4.prototype.isMatrix4 = true;
  3478. this.elements = [
  3479. 1, 0, 0, 0,
  3480. 0, 1, 0, 0,
  3481. 0, 0, 1, 0,
  3482. 0, 0, 0, 1
  3483. ];
  3484. if ( n11 !== undefined ) {
  3485. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3486. }
  3487. }
  3488. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3489. const te = this.elements;
  3490. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3491. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3492. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3493. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3494. return this;
  3495. }
  3496. identity() {
  3497. this.set(
  3498. 1, 0, 0, 0,
  3499. 0, 1, 0, 0,
  3500. 0, 0, 1, 0,
  3501. 0, 0, 0, 1
  3502. );
  3503. return this;
  3504. }
  3505. clone() {
  3506. return new Matrix4().fromArray( this.elements );
  3507. }
  3508. copy( m ) {
  3509. const te = this.elements;
  3510. const me = m.elements;
  3511. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3512. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3513. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3514. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3515. return this;
  3516. }
  3517. copyPosition( m ) {
  3518. const te = this.elements, me = m.elements;
  3519. te[ 12 ] = me[ 12 ];
  3520. te[ 13 ] = me[ 13 ];
  3521. te[ 14 ] = me[ 14 ];
  3522. return this;
  3523. }
  3524. setFromMatrix3( m ) {
  3525. const me = m.elements;
  3526. this.set(
  3527. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3528. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3529. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3530. 0, 0, 0, 1
  3531. );
  3532. return this;
  3533. }
  3534. extractBasis( xAxis, yAxis, zAxis ) {
  3535. xAxis.setFromMatrixColumn( this, 0 );
  3536. yAxis.setFromMatrixColumn( this, 1 );
  3537. zAxis.setFromMatrixColumn( this, 2 );
  3538. return this;
  3539. }
  3540. makeBasis( xAxis, yAxis, zAxis ) {
  3541. this.set(
  3542. xAxis.x, yAxis.x, zAxis.x, 0,
  3543. xAxis.y, yAxis.y, zAxis.y, 0,
  3544. xAxis.z, yAxis.z, zAxis.z, 0,
  3545. 0, 0, 0, 1
  3546. );
  3547. return this;
  3548. }
  3549. extractRotation( m ) {
  3550. // this method does not support reflection matrices
  3551. const te = this.elements;
  3552. const me = m.elements;
  3553. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3554. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3555. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3556. te[ 0 ] = me[ 0 ] * scaleX;
  3557. te[ 1 ] = me[ 1 ] * scaleX;
  3558. te[ 2 ] = me[ 2 ] * scaleX;
  3559. te[ 3 ] = 0;
  3560. te[ 4 ] = me[ 4 ] * scaleY;
  3561. te[ 5 ] = me[ 5 ] * scaleY;
  3562. te[ 6 ] = me[ 6 ] * scaleY;
  3563. te[ 7 ] = 0;
  3564. te[ 8 ] = me[ 8 ] * scaleZ;
  3565. te[ 9 ] = me[ 9 ] * scaleZ;
  3566. te[ 10 ] = me[ 10 ] * scaleZ;
  3567. te[ 11 ] = 0;
  3568. te[ 12 ] = 0;
  3569. te[ 13 ] = 0;
  3570. te[ 14 ] = 0;
  3571. te[ 15 ] = 1;
  3572. return this;
  3573. }
  3574. makeRotationFromEuler( euler ) {
  3575. const te = this.elements;
  3576. const x = euler.x, y = euler.y, z = euler.z;
  3577. const a = Math.cos( x ), b = Math.sin( x );
  3578. const c = Math.cos( y ), d = Math.sin( y );
  3579. const e = Math.cos( z ), f = Math.sin( z );
  3580. if ( euler.order === 'XYZ' ) {
  3581. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3582. te[ 0 ] = c * e;
  3583. te[ 4 ] = - c * f;
  3584. te[ 8 ] = d;
  3585. te[ 1 ] = af + be * d;
  3586. te[ 5 ] = ae - bf * d;
  3587. te[ 9 ] = - b * c;
  3588. te[ 2 ] = bf - ae * d;
  3589. te[ 6 ] = be + af * d;
  3590. te[ 10 ] = a * c;
  3591. } else if ( euler.order === 'YXZ' ) {
  3592. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3593. te[ 0 ] = ce + df * b;
  3594. te[ 4 ] = de * b - cf;
  3595. te[ 8 ] = a * d;
  3596. te[ 1 ] = a * f;
  3597. te[ 5 ] = a * e;
  3598. te[ 9 ] = - b;
  3599. te[ 2 ] = cf * b - de;
  3600. te[ 6 ] = df + ce * b;
  3601. te[ 10 ] = a * c;
  3602. } else if ( euler.order === 'ZXY' ) {
  3603. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3604. te[ 0 ] = ce - df * b;
  3605. te[ 4 ] = - a * f;
  3606. te[ 8 ] = de + cf * b;
  3607. te[ 1 ] = cf + de * b;
  3608. te[ 5 ] = a * e;
  3609. te[ 9 ] = df - ce * b;
  3610. te[ 2 ] = - a * d;
  3611. te[ 6 ] = b;
  3612. te[ 10 ] = a * c;
  3613. } else if ( euler.order === 'ZYX' ) {
  3614. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3615. te[ 0 ] = c * e;
  3616. te[ 4 ] = be * d - af;
  3617. te[ 8 ] = ae * d + bf;
  3618. te[ 1 ] = c * f;
  3619. te[ 5 ] = bf * d + ae;
  3620. te[ 9 ] = af * d - be;
  3621. te[ 2 ] = - d;
  3622. te[ 6 ] = b * c;
  3623. te[ 10 ] = a * c;
  3624. } else if ( euler.order === 'YZX' ) {
  3625. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3626. te[ 0 ] = c * e;
  3627. te[ 4 ] = bd - ac * f;
  3628. te[ 8 ] = bc * f + ad;
  3629. te[ 1 ] = f;
  3630. te[ 5 ] = a * e;
  3631. te[ 9 ] = - b * e;
  3632. te[ 2 ] = - d * e;
  3633. te[ 6 ] = ad * f + bc;
  3634. te[ 10 ] = ac - bd * f;
  3635. } else if ( euler.order === 'XZY' ) {
  3636. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3637. te[ 0 ] = c * e;
  3638. te[ 4 ] = - f;
  3639. te[ 8 ] = d * e;
  3640. te[ 1 ] = ac * f + bd;
  3641. te[ 5 ] = a * e;
  3642. te[ 9 ] = ad * f - bc;
  3643. te[ 2 ] = bc * f - ad;
  3644. te[ 6 ] = b * e;
  3645. te[ 10 ] = bd * f + ac;
  3646. }
  3647. // bottom row
  3648. te[ 3 ] = 0;
  3649. te[ 7 ] = 0;
  3650. te[ 11 ] = 0;
  3651. // last column
  3652. te[ 12 ] = 0;
  3653. te[ 13 ] = 0;
  3654. te[ 14 ] = 0;
  3655. te[ 15 ] = 1;
  3656. return this;
  3657. }
  3658. makeRotationFromQuaternion( q ) {
  3659. return this.compose( _zero, q, _one );
  3660. }
  3661. lookAt( eye, target, up ) {
  3662. const te = this.elements;
  3663. _z.subVectors( eye, target );
  3664. if ( _z.lengthSq() === 0 ) {
  3665. // eye and target are in the same position
  3666. _z.z = 1;
  3667. }
  3668. _z.normalize();
  3669. _x.crossVectors( up, _z );
  3670. if ( _x.lengthSq() === 0 ) {
  3671. // up and z are parallel
  3672. if ( Math.abs( up.z ) === 1 ) {
  3673. _z.x += 0.0001;
  3674. } else {
  3675. _z.z += 0.0001;
  3676. }
  3677. _z.normalize();
  3678. _x.crossVectors( up, _z );
  3679. }
  3680. _x.normalize();
  3681. _y.crossVectors( _z, _x );
  3682. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3683. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3684. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3685. return this;
  3686. }
  3687. multiply( m ) {
  3688. return this.multiplyMatrices( this, m );
  3689. }
  3690. premultiply( m ) {
  3691. return this.multiplyMatrices( m, this );
  3692. }
  3693. multiplyMatrices( a, b ) {
  3694. const ae = a.elements;
  3695. const be = b.elements;
  3696. const te = this.elements;
  3697. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3698. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3699. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3700. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3701. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3702. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3703. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3704. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3705. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3706. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3707. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3708. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3709. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3710. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3711. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3712. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3713. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3714. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3715. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3716. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3717. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3718. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3719. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3720. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3721. return this;
  3722. }
  3723. multiplyScalar( s ) {
  3724. const te = this.elements;
  3725. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3726. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3727. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3728. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3729. return this;
  3730. }
  3731. determinant() {
  3732. const te = this.elements;
  3733. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3734. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3735. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3736. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3737. //TODO: make this more efficient
  3738. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3739. return (
  3740. n41 * (
  3741. + n14 * n23 * n32
  3742. - n13 * n24 * n32
  3743. - n14 * n22 * n33
  3744. + n12 * n24 * n33
  3745. + n13 * n22 * n34
  3746. - n12 * n23 * n34
  3747. ) +
  3748. n42 * (
  3749. + n11 * n23 * n34
  3750. - n11 * n24 * n33
  3751. + n14 * n21 * n33
  3752. - n13 * n21 * n34
  3753. + n13 * n24 * n31
  3754. - n14 * n23 * n31
  3755. ) +
  3756. n43 * (
  3757. + n11 * n24 * n32
  3758. - n11 * n22 * n34
  3759. - n14 * n21 * n32
  3760. + n12 * n21 * n34
  3761. + n14 * n22 * n31
  3762. - n12 * n24 * n31
  3763. ) +
  3764. n44 * (
  3765. - n13 * n22 * n31
  3766. - n11 * n23 * n32
  3767. + n11 * n22 * n33
  3768. + n13 * n21 * n32
  3769. - n12 * n21 * n33
  3770. + n12 * n23 * n31
  3771. )
  3772. );
  3773. }
  3774. transpose() {
  3775. const te = this.elements;
  3776. let tmp;
  3777. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3778. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3779. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3780. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3781. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3782. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3783. return this;
  3784. }
  3785. setPosition( x, y, z ) {
  3786. const te = this.elements;
  3787. if ( x.isVector3 ) {
  3788. te[ 12 ] = x.x;
  3789. te[ 13 ] = x.y;
  3790. te[ 14 ] = x.z;
  3791. } else {
  3792. te[ 12 ] = x;
  3793. te[ 13 ] = y;
  3794. te[ 14 ] = z;
  3795. }
  3796. return this;
  3797. }
  3798. invert() {
  3799. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3800. const te = this.elements,
  3801. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3802. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3803. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3804. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3805. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3806. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3807. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3808. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3809. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3810. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3811. const detInv = 1 / det;
  3812. te[ 0 ] = t11 * detInv;
  3813. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3814. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3815. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3816. te[ 4 ] = t12 * detInv;
  3817. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3818. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3819. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3820. te[ 8 ] = t13 * detInv;
  3821. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3822. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3823. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3824. te[ 12 ] = t14 * detInv;
  3825. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3826. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3827. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3828. return this;
  3829. }
  3830. scale( v ) {
  3831. const te = this.elements;
  3832. const x = v.x, y = v.y, z = v.z;
  3833. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3834. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3835. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3836. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3837. return this;
  3838. }
  3839. getMaxScaleOnAxis() {
  3840. const te = this.elements;
  3841. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3842. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3843. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3844. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3845. }
  3846. makeTranslation( x, y, z ) {
  3847. if ( x.isVector3 ) {
  3848. this.set(
  3849. 1, 0, 0, x.x,
  3850. 0, 1, 0, x.y,
  3851. 0, 0, 1, x.z,
  3852. 0, 0, 0, 1
  3853. );
  3854. } else {
  3855. this.set(
  3856. 1, 0, 0, x,
  3857. 0, 1, 0, y,
  3858. 0, 0, 1, z,
  3859. 0, 0, 0, 1
  3860. );
  3861. }
  3862. return this;
  3863. }
  3864. makeRotationX( theta ) {
  3865. const c = Math.cos( theta ), s = Math.sin( theta );
  3866. this.set(
  3867. 1, 0, 0, 0,
  3868. 0, c, - s, 0,
  3869. 0, s, c, 0,
  3870. 0, 0, 0, 1
  3871. );
  3872. return this;
  3873. }
  3874. makeRotationY( theta ) {
  3875. const c = Math.cos( theta ), s = Math.sin( theta );
  3876. this.set(
  3877. c, 0, s, 0,
  3878. 0, 1, 0, 0,
  3879. - s, 0, c, 0,
  3880. 0, 0, 0, 1
  3881. );
  3882. return this;
  3883. }
  3884. makeRotationZ( theta ) {
  3885. const c = Math.cos( theta ), s = Math.sin( theta );
  3886. this.set(
  3887. c, - s, 0, 0,
  3888. s, c, 0, 0,
  3889. 0, 0, 1, 0,
  3890. 0, 0, 0, 1
  3891. );
  3892. return this;
  3893. }
  3894. makeRotationAxis( axis, angle ) {
  3895. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3896. const c = Math.cos( angle );
  3897. const s = Math.sin( angle );
  3898. const t = 1 - c;
  3899. const x = axis.x, y = axis.y, z = axis.z;
  3900. const tx = t * x, ty = t * y;
  3901. this.set(
  3902. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3903. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3904. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3905. 0, 0, 0, 1
  3906. );
  3907. return this;
  3908. }
  3909. makeScale( x, y, z ) {
  3910. this.set(
  3911. x, 0, 0, 0,
  3912. 0, y, 0, 0,
  3913. 0, 0, z, 0,
  3914. 0, 0, 0, 1
  3915. );
  3916. return this;
  3917. }
  3918. makeShear( xy, xz, yx, yz, zx, zy ) {
  3919. this.set(
  3920. 1, yx, zx, 0,
  3921. xy, 1, zy, 0,
  3922. xz, yz, 1, 0,
  3923. 0, 0, 0, 1
  3924. );
  3925. return this;
  3926. }
  3927. compose( position, quaternion, scale ) {
  3928. const te = this.elements;
  3929. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3930. const x2 = x + x, y2 = y + y, z2 = z + z;
  3931. const xx = x * x2, xy = x * y2, xz = x * z2;
  3932. const yy = y * y2, yz = y * z2, zz = z * z2;
  3933. const wx = w * x2, wy = w * y2, wz = w * z2;
  3934. const sx = scale.x, sy = scale.y, sz = scale.z;
  3935. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3936. te[ 1 ] = ( xy + wz ) * sx;
  3937. te[ 2 ] = ( xz - wy ) * sx;
  3938. te[ 3 ] = 0;
  3939. te[ 4 ] = ( xy - wz ) * sy;
  3940. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3941. te[ 6 ] = ( yz + wx ) * sy;
  3942. te[ 7 ] = 0;
  3943. te[ 8 ] = ( xz + wy ) * sz;
  3944. te[ 9 ] = ( yz - wx ) * sz;
  3945. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3946. te[ 11 ] = 0;
  3947. te[ 12 ] = position.x;
  3948. te[ 13 ] = position.y;
  3949. te[ 14 ] = position.z;
  3950. te[ 15 ] = 1;
  3951. return this;
  3952. }
  3953. decompose( position, quaternion, scale ) {
  3954. const te = this.elements;
  3955. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3956. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3957. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3958. // if determine is negative, we need to invert one scale
  3959. const det = this.determinant();
  3960. if ( det < 0 ) sx = - sx;
  3961. position.x = te[ 12 ];
  3962. position.y = te[ 13 ];
  3963. position.z = te[ 14 ];
  3964. // scale the rotation part
  3965. _m1$4.copy( this );
  3966. const invSX = 1 / sx;
  3967. const invSY = 1 / sy;
  3968. const invSZ = 1 / sz;
  3969. _m1$4.elements[ 0 ] *= invSX;
  3970. _m1$4.elements[ 1 ] *= invSX;
  3971. _m1$4.elements[ 2 ] *= invSX;
  3972. _m1$4.elements[ 4 ] *= invSY;
  3973. _m1$4.elements[ 5 ] *= invSY;
  3974. _m1$4.elements[ 6 ] *= invSY;
  3975. _m1$4.elements[ 8 ] *= invSZ;
  3976. _m1$4.elements[ 9 ] *= invSZ;
  3977. _m1$4.elements[ 10 ] *= invSZ;
  3978. quaternion.setFromRotationMatrix( _m1$4 );
  3979. scale.x = sx;
  3980. scale.y = sy;
  3981. scale.z = sz;
  3982. return this;
  3983. }
  3984. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  3985. const te = this.elements;
  3986. const x = 2 * near / ( right - left );
  3987. const y = 2 * near / ( top - bottom );
  3988. const a = ( right + left ) / ( right - left );
  3989. const b = ( top + bottom ) / ( top - bottom );
  3990. let c, d;
  3991. if ( coordinateSystem === WebGLCoordinateSystem ) {
  3992. c = - ( far + near ) / ( far - near );
  3993. d = ( - 2 * far * near ) / ( far - near );
  3994. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  3995. c = - far / ( far - near );
  3996. d = ( - far * near ) / ( far - near );
  3997. } else {
  3998. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  3999. }
  4000. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4001. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4002. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4003. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4004. return this;
  4005. }
  4006. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4007. const te = this.elements;
  4008. const w = 1.0 / ( right - left );
  4009. const h = 1.0 / ( top - bottom );
  4010. const p = 1.0 / ( far - near );
  4011. const x = ( right + left ) * w;
  4012. const y = ( top + bottom ) * h;
  4013. let z, zInv;
  4014. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4015. z = ( far + near ) * p;
  4016. zInv = - 2 * p;
  4017. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4018. z = near * p;
  4019. zInv = - 1 * p;
  4020. } else {
  4021. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4022. }
  4023. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4024. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4025. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4026. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4027. return this;
  4028. }
  4029. equals( matrix ) {
  4030. const te = this.elements;
  4031. const me = matrix.elements;
  4032. for ( let i = 0; i < 16; i ++ ) {
  4033. if ( te[ i ] !== me[ i ] ) return false;
  4034. }
  4035. return true;
  4036. }
  4037. fromArray( array, offset = 0 ) {
  4038. for ( let i = 0; i < 16; i ++ ) {
  4039. this.elements[ i ] = array[ i + offset ];
  4040. }
  4041. return this;
  4042. }
  4043. toArray( array = [], offset = 0 ) {
  4044. const te = this.elements;
  4045. array[ offset ] = te[ 0 ];
  4046. array[ offset + 1 ] = te[ 1 ];
  4047. array[ offset + 2 ] = te[ 2 ];
  4048. array[ offset + 3 ] = te[ 3 ];
  4049. array[ offset + 4 ] = te[ 4 ];
  4050. array[ offset + 5 ] = te[ 5 ];
  4051. array[ offset + 6 ] = te[ 6 ];
  4052. array[ offset + 7 ] = te[ 7 ];
  4053. array[ offset + 8 ] = te[ 8 ];
  4054. array[ offset + 9 ] = te[ 9 ];
  4055. array[ offset + 10 ] = te[ 10 ];
  4056. array[ offset + 11 ] = te[ 11 ];
  4057. array[ offset + 12 ] = te[ 12 ];
  4058. array[ offset + 13 ] = te[ 13 ];
  4059. array[ offset + 14 ] = te[ 14 ];
  4060. array[ offset + 15 ] = te[ 15 ];
  4061. return array;
  4062. }
  4063. }
  4064. const _v1$5 = /*@__PURE__*/ new Vector3();
  4065. const _m1$4 = /*@__PURE__*/ new Matrix4();
  4066. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4067. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4068. const _x = /*@__PURE__*/ new Vector3();
  4069. const _y = /*@__PURE__*/ new Vector3();
  4070. const _z = /*@__PURE__*/ new Vector3();
  4071. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4072. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4073. class Euler {
  4074. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4075. this.isEuler = true;
  4076. this._x = x;
  4077. this._y = y;
  4078. this._z = z;
  4079. this._order = order;
  4080. }
  4081. get x() {
  4082. return this._x;
  4083. }
  4084. set x( value ) {
  4085. this._x = value;
  4086. this._onChangeCallback();
  4087. }
  4088. get y() {
  4089. return this._y;
  4090. }
  4091. set y( value ) {
  4092. this._y = value;
  4093. this._onChangeCallback();
  4094. }
  4095. get z() {
  4096. return this._z;
  4097. }
  4098. set z( value ) {
  4099. this._z = value;
  4100. this._onChangeCallback();
  4101. }
  4102. get order() {
  4103. return this._order;
  4104. }
  4105. set order( value ) {
  4106. this._order = value;
  4107. this._onChangeCallback();
  4108. }
  4109. set( x, y, z, order = this._order ) {
  4110. this._x = x;
  4111. this._y = y;
  4112. this._z = z;
  4113. this._order = order;
  4114. this._onChangeCallback();
  4115. return this;
  4116. }
  4117. clone() {
  4118. return new this.constructor( this._x, this._y, this._z, this._order );
  4119. }
  4120. copy( euler ) {
  4121. this._x = euler._x;
  4122. this._y = euler._y;
  4123. this._z = euler._z;
  4124. this._order = euler._order;
  4125. this._onChangeCallback();
  4126. return this;
  4127. }
  4128. setFromRotationMatrix( m, order = this._order, update = true ) {
  4129. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4130. const te = m.elements;
  4131. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4132. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4133. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4134. switch ( order ) {
  4135. case 'XYZ':
  4136. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4137. if ( Math.abs( m13 ) < 0.9999999 ) {
  4138. this._x = Math.atan2( - m23, m33 );
  4139. this._z = Math.atan2( - m12, m11 );
  4140. } else {
  4141. this._x = Math.atan2( m32, m22 );
  4142. this._z = 0;
  4143. }
  4144. break;
  4145. case 'YXZ':
  4146. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4147. if ( Math.abs( m23 ) < 0.9999999 ) {
  4148. this._y = Math.atan2( m13, m33 );
  4149. this._z = Math.atan2( m21, m22 );
  4150. } else {
  4151. this._y = Math.atan2( - m31, m11 );
  4152. this._z = 0;
  4153. }
  4154. break;
  4155. case 'ZXY':
  4156. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4157. if ( Math.abs( m32 ) < 0.9999999 ) {
  4158. this._y = Math.atan2( - m31, m33 );
  4159. this._z = Math.atan2( - m12, m22 );
  4160. } else {
  4161. this._y = 0;
  4162. this._z = Math.atan2( m21, m11 );
  4163. }
  4164. break;
  4165. case 'ZYX':
  4166. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4167. if ( Math.abs( m31 ) < 0.9999999 ) {
  4168. this._x = Math.atan2( m32, m33 );
  4169. this._z = Math.atan2( m21, m11 );
  4170. } else {
  4171. this._x = 0;
  4172. this._z = Math.atan2( - m12, m22 );
  4173. }
  4174. break;
  4175. case 'YZX':
  4176. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4177. if ( Math.abs( m21 ) < 0.9999999 ) {
  4178. this._x = Math.atan2( - m23, m22 );
  4179. this._y = Math.atan2( - m31, m11 );
  4180. } else {
  4181. this._x = 0;
  4182. this._y = Math.atan2( m13, m33 );
  4183. }
  4184. break;
  4185. case 'XZY':
  4186. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4187. if ( Math.abs( m12 ) < 0.9999999 ) {
  4188. this._x = Math.atan2( m32, m22 );
  4189. this._y = Math.atan2( m13, m11 );
  4190. } else {
  4191. this._x = Math.atan2( - m23, m33 );
  4192. this._y = 0;
  4193. }
  4194. break;
  4195. default:
  4196. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4197. }
  4198. this._order = order;
  4199. if ( update === true ) this._onChangeCallback();
  4200. return this;
  4201. }
  4202. setFromQuaternion( q, order, update ) {
  4203. _matrix$2.makeRotationFromQuaternion( q );
  4204. return this.setFromRotationMatrix( _matrix$2, order, update );
  4205. }
  4206. setFromVector3( v, order = this._order ) {
  4207. return this.set( v.x, v.y, v.z, order );
  4208. }
  4209. reorder( newOrder ) {
  4210. // WARNING: this discards revolution information -bhouston
  4211. _quaternion$3.setFromEuler( this );
  4212. return this.setFromQuaternion( _quaternion$3, newOrder );
  4213. }
  4214. equals( euler ) {
  4215. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4216. }
  4217. fromArray( array ) {
  4218. this._x = array[ 0 ];
  4219. this._y = array[ 1 ];
  4220. this._z = array[ 2 ];
  4221. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4222. this._onChangeCallback();
  4223. return this;
  4224. }
  4225. toArray( array = [], offset = 0 ) {
  4226. array[ offset ] = this._x;
  4227. array[ offset + 1 ] = this._y;
  4228. array[ offset + 2 ] = this._z;
  4229. array[ offset + 3 ] = this._order;
  4230. return array;
  4231. }
  4232. _onChange( callback ) {
  4233. this._onChangeCallback = callback;
  4234. return this;
  4235. }
  4236. _onChangeCallback() {}
  4237. *[ Symbol.iterator ]() {
  4238. yield this._x;
  4239. yield this._y;
  4240. yield this._z;
  4241. yield this._order;
  4242. }
  4243. }
  4244. Euler.DEFAULT_ORDER = 'XYZ';
  4245. class Layers {
  4246. constructor() {
  4247. this.mask = 1 | 0;
  4248. }
  4249. set( channel ) {
  4250. this.mask = ( 1 << channel | 0 ) >>> 0;
  4251. }
  4252. enable( channel ) {
  4253. this.mask |= 1 << channel | 0;
  4254. }
  4255. enableAll() {
  4256. this.mask = 0xffffffff | 0;
  4257. }
  4258. toggle( channel ) {
  4259. this.mask ^= 1 << channel | 0;
  4260. }
  4261. disable( channel ) {
  4262. this.mask &= ~ ( 1 << channel | 0 );
  4263. }
  4264. disableAll() {
  4265. this.mask = 0;
  4266. }
  4267. test( layers ) {
  4268. return ( this.mask & layers.mask ) !== 0;
  4269. }
  4270. isEnabled( channel ) {
  4271. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4272. }
  4273. }
  4274. let _object3DId = 0;
  4275. const _v1$4 = /*@__PURE__*/ new Vector3();
  4276. const _q1 = /*@__PURE__*/ new Quaternion();
  4277. const _m1$3 = /*@__PURE__*/ new Matrix4();
  4278. const _target = /*@__PURE__*/ new Vector3();
  4279. const _position$3 = /*@__PURE__*/ new Vector3();
  4280. const _scale$2 = /*@__PURE__*/ new Vector3();
  4281. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4282. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4283. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4284. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4285. const _addedEvent = { type: 'added' };
  4286. const _removedEvent = { type: 'removed' };
  4287. const _childaddedEvent = { type: 'childadded', child: null };
  4288. const _childremovedEvent = { type: 'childremoved', child: null };
  4289. class Object3D extends EventDispatcher {
  4290. constructor() {
  4291. super();
  4292. this.isObject3D = true;
  4293. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4294. this.uuid = generateUUID();
  4295. this.name = '';
  4296. this.type = 'Object3D';
  4297. this.parent = null;
  4298. this.children = [];
  4299. this.up = Object3D.DEFAULT_UP.clone();
  4300. const position = new Vector3();
  4301. const rotation = new Euler();
  4302. const quaternion = new Quaternion();
  4303. const scale = new Vector3( 1, 1, 1 );
  4304. function onRotationChange() {
  4305. quaternion.setFromEuler( rotation, false );
  4306. }
  4307. function onQuaternionChange() {
  4308. rotation.setFromQuaternion( quaternion, undefined, false );
  4309. }
  4310. rotation._onChange( onRotationChange );
  4311. quaternion._onChange( onQuaternionChange );
  4312. Object.defineProperties( this, {
  4313. position: {
  4314. configurable: true,
  4315. enumerable: true,
  4316. value: position
  4317. },
  4318. rotation: {
  4319. configurable: true,
  4320. enumerable: true,
  4321. value: rotation
  4322. },
  4323. quaternion: {
  4324. configurable: true,
  4325. enumerable: true,
  4326. value: quaternion
  4327. },
  4328. scale: {
  4329. configurable: true,
  4330. enumerable: true,
  4331. value: scale
  4332. },
  4333. modelViewMatrix: {
  4334. value: new Matrix4()
  4335. },
  4336. normalMatrix: {
  4337. value: new Matrix3()
  4338. }
  4339. } );
  4340. this.matrix = new Matrix4();
  4341. this.matrixWorld = new Matrix4();
  4342. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4343. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4344. this.matrixWorldNeedsUpdate = false;
  4345. this.layers = new Layers();
  4346. this.visible = true;
  4347. this.castShadow = false;
  4348. this.receiveShadow = false;
  4349. this.frustumCulled = true;
  4350. this.renderOrder = 0;
  4351. this.animations = [];
  4352. this.userData = {};
  4353. }
  4354. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4355. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4356. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4357. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4358. applyMatrix4( matrix ) {
  4359. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4360. this.matrix.premultiply( matrix );
  4361. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4362. }
  4363. applyQuaternion( q ) {
  4364. this.quaternion.premultiply( q );
  4365. return this;
  4366. }
  4367. setRotationFromAxisAngle( axis, angle ) {
  4368. // assumes axis is normalized
  4369. this.quaternion.setFromAxisAngle( axis, angle );
  4370. }
  4371. setRotationFromEuler( euler ) {
  4372. this.quaternion.setFromEuler( euler, true );
  4373. }
  4374. setRotationFromMatrix( m ) {
  4375. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4376. this.quaternion.setFromRotationMatrix( m );
  4377. }
  4378. setRotationFromQuaternion( q ) {
  4379. // assumes q is normalized
  4380. this.quaternion.copy( q );
  4381. }
  4382. rotateOnAxis( axis, angle ) {
  4383. // rotate object on axis in object space
  4384. // axis is assumed to be normalized
  4385. _q1.setFromAxisAngle( axis, angle );
  4386. this.quaternion.multiply( _q1 );
  4387. return this;
  4388. }
  4389. rotateOnWorldAxis( axis, angle ) {
  4390. // rotate object on axis in world space
  4391. // axis is assumed to be normalized
  4392. // method assumes no rotated parent
  4393. _q1.setFromAxisAngle( axis, angle );
  4394. this.quaternion.premultiply( _q1 );
  4395. return this;
  4396. }
  4397. rotateX( angle ) {
  4398. return this.rotateOnAxis( _xAxis, angle );
  4399. }
  4400. rotateY( angle ) {
  4401. return this.rotateOnAxis( _yAxis, angle );
  4402. }
  4403. rotateZ( angle ) {
  4404. return this.rotateOnAxis( _zAxis, angle );
  4405. }
  4406. translateOnAxis( axis, distance ) {
  4407. // translate object by distance along axis in object space
  4408. // axis is assumed to be normalized
  4409. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4410. this.position.add( _v1$4.multiplyScalar( distance ) );
  4411. return this;
  4412. }
  4413. translateX( distance ) {
  4414. return this.translateOnAxis( _xAxis, distance );
  4415. }
  4416. translateY( distance ) {
  4417. return this.translateOnAxis( _yAxis, distance );
  4418. }
  4419. translateZ( distance ) {
  4420. return this.translateOnAxis( _zAxis, distance );
  4421. }
  4422. localToWorld( vector ) {
  4423. this.updateWorldMatrix( true, false );
  4424. return vector.applyMatrix4( this.matrixWorld );
  4425. }
  4426. worldToLocal( vector ) {
  4427. this.updateWorldMatrix( true, false );
  4428. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  4429. }
  4430. lookAt( x, y, z ) {
  4431. // This method does not support objects having non-uniformly-scaled parent(s)
  4432. if ( x.isVector3 ) {
  4433. _target.copy( x );
  4434. } else {
  4435. _target.set( x, y, z );
  4436. }
  4437. const parent = this.parent;
  4438. this.updateWorldMatrix( true, false );
  4439. _position$3.setFromMatrixPosition( this.matrixWorld );
  4440. if ( this.isCamera || this.isLight ) {
  4441. _m1$3.lookAt( _position$3, _target, this.up );
  4442. } else {
  4443. _m1$3.lookAt( _target, _position$3, this.up );
  4444. }
  4445. this.quaternion.setFromRotationMatrix( _m1$3 );
  4446. if ( parent ) {
  4447. _m1$3.extractRotation( parent.matrixWorld );
  4448. _q1.setFromRotationMatrix( _m1$3 );
  4449. this.quaternion.premultiply( _q1.invert() );
  4450. }
  4451. }
  4452. add( object ) {
  4453. if ( arguments.length > 1 ) {
  4454. for ( let i = 0; i < arguments.length; i ++ ) {
  4455. this.add( arguments[ i ] );
  4456. }
  4457. return this;
  4458. }
  4459. if ( object === this ) {
  4460. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4461. return this;
  4462. }
  4463. if ( object && object.isObject3D ) {
  4464. object.removeFromParent();
  4465. object.parent = this;
  4466. this.children.push( object );
  4467. object.dispatchEvent( _addedEvent );
  4468. _childaddedEvent.child = object;
  4469. this.dispatchEvent( _childaddedEvent );
  4470. _childaddedEvent.child = null;
  4471. } else {
  4472. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4473. }
  4474. return this;
  4475. }
  4476. remove( object ) {
  4477. if ( arguments.length > 1 ) {
  4478. for ( let i = 0; i < arguments.length; i ++ ) {
  4479. this.remove( arguments[ i ] );
  4480. }
  4481. return this;
  4482. }
  4483. const index = this.children.indexOf( object );
  4484. if ( index !== - 1 ) {
  4485. object.parent = null;
  4486. this.children.splice( index, 1 );
  4487. object.dispatchEvent( _removedEvent );
  4488. _childremovedEvent.child = object;
  4489. this.dispatchEvent( _childremovedEvent );
  4490. _childremovedEvent.child = null;
  4491. }
  4492. return this;
  4493. }
  4494. removeFromParent() {
  4495. const parent = this.parent;
  4496. if ( parent !== null ) {
  4497. parent.remove( this );
  4498. }
  4499. return this;
  4500. }
  4501. clear() {
  4502. return this.remove( ... this.children );
  4503. }
  4504. attach( object ) {
  4505. // adds object as a child of this, while maintaining the object's world transform
  4506. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4507. this.updateWorldMatrix( true, false );
  4508. _m1$3.copy( this.matrixWorld ).invert();
  4509. if ( object.parent !== null ) {
  4510. object.parent.updateWorldMatrix( true, false );
  4511. _m1$3.multiply( object.parent.matrixWorld );
  4512. }
  4513. object.applyMatrix4( _m1$3 );
  4514. object.removeFromParent();
  4515. object.parent = this;
  4516. this.children.push( object );
  4517. object.updateWorldMatrix( false, true );
  4518. object.dispatchEvent( _addedEvent );
  4519. _childaddedEvent.child = object;
  4520. this.dispatchEvent( _childaddedEvent );
  4521. _childaddedEvent.child = null;
  4522. return this;
  4523. }
  4524. getObjectById( id ) {
  4525. return this.getObjectByProperty( 'id', id );
  4526. }
  4527. getObjectByName( name ) {
  4528. return this.getObjectByProperty( 'name', name );
  4529. }
  4530. getObjectByProperty( name, value ) {
  4531. if ( this[ name ] === value ) return this;
  4532. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4533. const child = this.children[ i ];
  4534. const object = child.getObjectByProperty( name, value );
  4535. if ( object !== undefined ) {
  4536. return object;
  4537. }
  4538. }
  4539. return undefined;
  4540. }
  4541. getObjectsByProperty( name, value, result = [] ) {
  4542. if ( this[ name ] === value ) result.push( this );
  4543. const children = this.children;
  4544. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4545. children[ i ].getObjectsByProperty( name, value, result );
  4546. }
  4547. return result;
  4548. }
  4549. getWorldPosition( target ) {
  4550. this.updateWorldMatrix( true, false );
  4551. return target.setFromMatrixPosition( this.matrixWorld );
  4552. }
  4553. getWorldQuaternion( target ) {
  4554. this.updateWorldMatrix( true, false );
  4555. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4556. return target;
  4557. }
  4558. getWorldScale( target ) {
  4559. this.updateWorldMatrix( true, false );
  4560. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4561. return target;
  4562. }
  4563. getWorldDirection( target ) {
  4564. this.updateWorldMatrix( true, false );
  4565. const e = this.matrixWorld.elements;
  4566. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4567. }
  4568. raycast( /* raycaster, intersects */ ) {}
  4569. traverse( callback ) {
  4570. callback( this );
  4571. const children = this.children;
  4572. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4573. children[ i ].traverse( callback );
  4574. }
  4575. }
  4576. traverseVisible( callback ) {
  4577. if ( this.visible === false ) return;
  4578. callback( this );
  4579. const children = this.children;
  4580. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4581. children[ i ].traverseVisible( callback );
  4582. }
  4583. }
  4584. traverseAncestors( callback ) {
  4585. const parent = this.parent;
  4586. if ( parent !== null ) {
  4587. callback( parent );
  4588. parent.traverseAncestors( callback );
  4589. }
  4590. }
  4591. updateMatrix() {
  4592. this.matrix.compose( this.position, this.quaternion, this.scale );
  4593. this.matrixWorldNeedsUpdate = true;
  4594. }
  4595. updateMatrixWorld( force ) {
  4596. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4597. if ( this.matrixWorldNeedsUpdate || force ) {
  4598. if ( this.parent === null ) {
  4599. this.matrixWorld.copy( this.matrix );
  4600. } else {
  4601. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4602. }
  4603. this.matrixWorldNeedsUpdate = false;
  4604. force = true;
  4605. }
  4606. // update children
  4607. const children = this.children;
  4608. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4609. const child = children[ i ];
  4610. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4611. child.updateMatrixWorld( force );
  4612. }
  4613. }
  4614. }
  4615. updateWorldMatrix( updateParents, updateChildren ) {
  4616. const parent = this.parent;
  4617. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4618. parent.updateWorldMatrix( true, false );
  4619. }
  4620. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4621. if ( this.parent === null ) {
  4622. this.matrixWorld.copy( this.matrix );
  4623. } else {
  4624. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4625. }
  4626. // update children
  4627. if ( updateChildren === true ) {
  4628. const children = this.children;
  4629. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4630. const child = children[ i ];
  4631. if ( child.matrixWorldAutoUpdate === true ) {
  4632. child.updateWorldMatrix( false, true );
  4633. }
  4634. }
  4635. }
  4636. }
  4637. toJSON( meta ) {
  4638. // meta is a string when called from JSON.stringify
  4639. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4640. const output = {};
  4641. // meta is a hash used to collect geometries, materials.
  4642. // not providing it implies that this is the root object
  4643. // being serialized.
  4644. if ( isRootObject ) {
  4645. // initialize meta obj
  4646. meta = {
  4647. geometries: {},
  4648. materials: {},
  4649. textures: {},
  4650. images: {},
  4651. shapes: {},
  4652. skeletons: {},
  4653. animations: {},
  4654. nodes: {}
  4655. };
  4656. output.metadata = {
  4657. version: 4.6,
  4658. type: 'Object',
  4659. generator: 'Object3D.toJSON'
  4660. };
  4661. }
  4662. // standard Object3D serialization
  4663. const object = {};
  4664. object.uuid = this.uuid;
  4665. object.type = this.type;
  4666. if ( this.name !== '' ) object.name = this.name;
  4667. if ( this.castShadow === true ) object.castShadow = true;
  4668. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4669. if ( this.visible === false ) object.visible = false;
  4670. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4671. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4672. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4673. object.layers = this.layers.mask;
  4674. object.matrix = this.matrix.toArray();
  4675. object.up = this.up.toArray();
  4676. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4677. // object specific properties
  4678. if ( this.isInstancedMesh ) {
  4679. object.type = 'InstancedMesh';
  4680. object.count = this.count;
  4681. object.instanceMatrix = this.instanceMatrix.toJSON();
  4682. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4683. }
  4684. if ( this.isBatchedMesh ) {
  4685. object.type = 'BatchedMesh';
  4686. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4687. object.sortObjects = this.sortObjects;
  4688. object.drawRanges = this._drawRanges;
  4689. object.reservedRanges = this._reservedRanges;
  4690. object.visibility = this._visibility;
  4691. object.active = this._active;
  4692. object.bounds = this._bounds.map( bound => ( {
  4693. boxInitialized: bound.boxInitialized,
  4694. boxMin: bound.box.min.toArray(),
  4695. boxMax: bound.box.max.toArray(),
  4696. sphereInitialized: bound.sphereInitialized,
  4697. sphereRadius: bound.sphere.radius,
  4698. sphereCenter: bound.sphere.center.toArray()
  4699. } ) );
  4700. object.maxGeometryCount = this._maxGeometryCount;
  4701. object.maxVertexCount = this._maxVertexCount;
  4702. object.maxIndexCount = this._maxIndexCount;
  4703. object.geometryInitialized = this._geometryInitialized;
  4704. object.geometryCount = this._geometryCount;
  4705. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4706. if ( this.boundingSphere !== null ) {
  4707. object.boundingSphere = {
  4708. center: object.boundingSphere.center.toArray(),
  4709. radius: object.boundingSphere.radius
  4710. };
  4711. }
  4712. if ( this.boundingBox !== null ) {
  4713. object.boundingBox = {
  4714. min: object.boundingBox.min.toArray(),
  4715. max: object.boundingBox.max.toArray()
  4716. };
  4717. }
  4718. }
  4719. //
  4720. function serialize( library, element ) {
  4721. if ( library[ element.uuid ] === undefined ) {
  4722. library[ element.uuid ] = element.toJSON( meta );
  4723. }
  4724. return element.uuid;
  4725. }
  4726. if ( this.isScene ) {
  4727. if ( this.background ) {
  4728. if ( this.background.isColor ) {
  4729. object.background = this.background.toJSON();
  4730. } else if ( this.background.isTexture ) {
  4731. object.background = this.background.toJSON( meta ).uuid;
  4732. }
  4733. }
  4734. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4735. object.environment = this.environment.toJSON( meta ).uuid;
  4736. }
  4737. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4738. object.geometry = serialize( meta.geometries, this.geometry );
  4739. const parameters = this.geometry.parameters;
  4740. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4741. const shapes = parameters.shapes;
  4742. if ( Array.isArray( shapes ) ) {
  4743. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4744. const shape = shapes[ i ];
  4745. serialize( meta.shapes, shape );
  4746. }
  4747. } else {
  4748. serialize( meta.shapes, shapes );
  4749. }
  4750. }
  4751. }
  4752. if ( this.isSkinnedMesh ) {
  4753. object.bindMode = this.bindMode;
  4754. object.bindMatrix = this.bindMatrix.toArray();
  4755. if ( this.skeleton !== undefined ) {
  4756. serialize( meta.skeletons, this.skeleton );
  4757. object.skeleton = this.skeleton.uuid;
  4758. }
  4759. }
  4760. if ( this.material !== undefined ) {
  4761. if ( Array.isArray( this.material ) ) {
  4762. const uuids = [];
  4763. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4764. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4765. }
  4766. object.material = uuids;
  4767. } else {
  4768. object.material = serialize( meta.materials, this.material );
  4769. }
  4770. }
  4771. //
  4772. if ( this.children.length > 0 ) {
  4773. object.children = [];
  4774. for ( let i = 0; i < this.children.length; i ++ ) {
  4775. object.children.push( this.children[ i ].toJSON( meta ).object );
  4776. }
  4777. }
  4778. //
  4779. if ( this.animations.length > 0 ) {
  4780. object.animations = [];
  4781. for ( let i = 0; i < this.animations.length; i ++ ) {
  4782. const animation = this.animations[ i ];
  4783. object.animations.push( serialize( meta.animations, animation ) );
  4784. }
  4785. }
  4786. if ( isRootObject ) {
  4787. const geometries = extractFromCache( meta.geometries );
  4788. const materials = extractFromCache( meta.materials );
  4789. const textures = extractFromCache( meta.textures );
  4790. const images = extractFromCache( meta.images );
  4791. const shapes = extractFromCache( meta.shapes );
  4792. const skeletons = extractFromCache( meta.skeletons );
  4793. const animations = extractFromCache( meta.animations );
  4794. const nodes = extractFromCache( meta.nodes );
  4795. if ( geometries.length > 0 ) output.geometries = geometries;
  4796. if ( materials.length > 0 ) output.materials = materials;
  4797. if ( textures.length > 0 ) output.textures = textures;
  4798. if ( images.length > 0 ) output.images = images;
  4799. if ( shapes.length > 0 ) output.shapes = shapes;
  4800. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4801. if ( animations.length > 0 ) output.animations = animations;
  4802. if ( nodes.length > 0 ) output.nodes = nodes;
  4803. }
  4804. output.object = object;
  4805. return output;
  4806. // extract data from the cache hash
  4807. // remove metadata on each item
  4808. // and return as array
  4809. function extractFromCache( cache ) {
  4810. const values = [];
  4811. for ( const key in cache ) {
  4812. const data = cache[ key ];
  4813. delete data.metadata;
  4814. values.push( data );
  4815. }
  4816. return values;
  4817. }
  4818. }
  4819. clone( recursive ) {
  4820. return new this.constructor().copy( this, recursive );
  4821. }
  4822. copy( source, recursive = true ) {
  4823. this.name = source.name;
  4824. this.up.copy( source.up );
  4825. this.position.copy( source.position );
  4826. this.rotation.order = source.rotation.order;
  4827. this.quaternion.copy( source.quaternion );
  4828. this.scale.copy( source.scale );
  4829. this.matrix.copy( source.matrix );
  4830. this.matrixWorld.copy( source.matrixWorld );
  4831. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4832. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4833. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4834. this.layers.mask = source.layers.mask;
  4835. this.visible = source.visible;
  4836. this.castShadow = source.castShadow;
  4837. this.receiveShadow = source.receiveShadow;
  4838. this.frustumCulled = source.frustumCulled;
  4839. this.renderOrder = source.renderOrder;
  4840. this.animations = source.animations.slice();
  4841. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4842. if ( recursive === true ) {
  4843. for ( let i = 0; i < source.children.length; i ++ ) {
  4844. const child = source.children[ i ];
  4845. this.add( child.clone() );
  4846. }
  4847. }
  4848. return this;
  4849. }
  4850. }
  4851. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4852. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4853. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4854. const _v0$1 = /*@__PURE__*/ new Vector3();
  4855. const _v1$3 = /*@__PURE__*/ new Vector3();
  4856. const _v2$2 = /*@__PURE__*/ new Vector3();
  4857. const _v3$2 = /*@__PURE__*/ new Vector3();
  4858. const _vab = /*@__PURE__*/ new Vector3();
  4859. const _vac = /*@__PURE__*/ new Vector3();
  4860. const _vbc = /*@__PURE__*/ new Vector3();
  4861. const _vap = /*@__PURE__*/ new Vector3();
  4862. const _vbp = /*@__PURE__*/ new Vector3();
  4863. const _vcp = /*@__PURE__*/ new Vector3();
  4864. class Triangle {
  4865. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4866. this.a = a;
  4867. this.b = b;
  4868. this.c = c;
  4869. }
  4870. static getNormal( a, b, c, target ) {
  4871. target.subVectors( c, b );
  4872. _v0$1.subVectors( a, b );
  4873. target.cross( _v0$1 );
  4874. const targetLengthSq = target.lengthSq();
  4875. if ( targetLengthSq > 0 ) {
  4876. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4877. }
  4878. return target.set( 0, 0, 0 );
  4879. }
  4880. // static/instance method to calculate barycentric coordinates
  4881. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4882. static getBarycoord( point, a, b, c, target ) {
  4883. _v0$1.subVectors( c, a );
  4884. _v1$3.subVectors( b, a );
  4885. _v2$2.subVectors( point, a );
  4886. const dot00 = _v0$1.dot( _v0$1 );
  4887. const dot01 = _v0$1.dot( _v1$3 );
  4888. const dot02 = _v0$1.dot( _v2$2 );
  4889. const dot11 = _v1$3.dot( _v1$3 );
  4890. const dot12 = _v1$3.dot( _v2$2 );
  4891. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4892. // collinear or singular triangle
  4893. if ( denom === 0 ) {
  4894. target.set( 0, 0, 0 );
  4895. return null;
  4896. }
  4897. const invDenom = 1 / denom;
  4898. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4899. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4900. // barycentric coordinates must always sum to 1
  4901. return target.set( 1 - u - v, v, u );
  4902. }
  4903. static containsPoint( point, a, b, c ) {
  4904. // if the triangle is degenerate then we can't contain a point
  4905. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4906. return false;
  4907. }
  4908. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4909. }
  4910. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4911. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4912. target.x = 0;
  4913. target.y = 0;
  4914. if ( 'z' in target ) target.z = 0;
  4915. if ( 'w' in target ) target.w = 0;
  4916. return null;
  4917. }
  4918. target.setScalar( 0 );
  4919. target.addScaledVector( v1, _v3$2.x );
  4920. target.addScaledVector( v2, _v3$2.y );
  4921. target.addScaledVector( v3, _v3$2.z );
  4922. return target;
  4923. }
  4924. static isFrontFacing( a, b, c, direction ) {
  4925. _v0$1.subVectors( c, b );
  4926. _v1$3.subVectors( a, b );
  4927. // strictly front facing
  4928. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4929. }
  4930. set( a, b, c ) {
  4931. this.a.copy( a );
  4932. this.b.copy( b );
  4933. this.c.copy( c );
  4934. return this;
  4935. }
  4936. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4937. this.a.copy( points[ i0 ] );
  4938. this.b.copy( points[ i1 ] );
  4939. this.c.copy( points[ i2 ] );
  4940. return this;
  4941. }
  4942. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4943. this.a.fromBufferAttribute( attribute, i0 );
  4944. this.b.fromBufferAttribute( attribute, i1 );
  4945. this.c.fromBufferAttribute( attribute, i2 );
  4946. return this;
  4947. }
  4948. clone() {
  4949. return new this.constructor().copy( this );
  4950. }
  4951. copy( triangle ) {
  4952. this.a.copy( triangle.a );
  4953. this.b.copy( triangle.b );
  4954. this.c.copy( triangle.c );
  4955. return this;
  4956. }
  4957. getArea() {
  4958. _v0$1.subVectors( this.c, this.b );
  4959. _v1$3.subVectors( this.a, this.b );
  4960. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4961. }
  4962. getMidpoint( target ) {
  4963. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4964. }
  4965. getNormal( target ) {
  4966. return Triangle.getNormal( this.a, this.b, this.c, target );
  4967. }
  4968. getPlane( target ) {
  4969. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4970. }
  4971. getBarycoord( point, target ) {
  4972. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4973. }
  4974. getInterpolation( point, v1, v2, v3, target ) {
  4975. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4976. }
  4977. containsPoint( point ) {
  4978. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4979. }
  4980. isFrontFacing( direction ) {
  4981. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4982. }
  4983. intersectsBox( box ) {
  4984. return box.intersectsTriangle( this );
  4985. }
  4986. closestPointToPoint( p, target ) {
  4987. const a = this.a, b = this.b, c = this.c;
  4988. let v, w;
  4989. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4990. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4991. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4992. // basically, we're distinguishing which of the voronoi regions of the triangle
  4993. // the point lies in with the minimum amount of redundant computation.
  4994. _vab.subVectors( b, a );
  4995. _vac.subVectors( c, a );
  4996. _vap.subVectors( p, a );
  4997. const d1 = _vab.dot( _vap );
  4998. const d2 = _vac.dot( _vap );
  4999. if ( d1 <= 0 && d2 <= 0 ) {
  5000. // vertex region of A; barycentric coords (1, 0, 0)
  5001. return target.copy( a );
  5002. }
  5003. _vbp.subVectors( p, b );
  5004. const d3 = _vab.dot( _vbp );
  5005. const d4 = _vac.dot( _vbp );
  5006. if ( d3 >= 0 && d4 <= d3 ) {
  5007. // vertex region of B; barycentric coords (0, 1, 0)
  5008. return target.copy( b );
  5009. }
  5010. const vc = d1 * d4 - d3 * d2;
  5011. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5012. v = d1 / ( d1 - d3 );
  5013. // edge region of AB; barycentric coords (1-v, v, 0)
  5014. return target.copy( a ).addScaledVector( _vab, v );
  5015. }
  5016. _vcp.subVectors( p, c );
  5017. const d5 = _vab.dot( _vcp );
  5018. const d6 = _vac.dot( _vcp );
  5019. if ( d6 >= 0 && d5 <= d6 ) {
  5020. // vertex region of C; barycentric coords (0, 0, 1)
  5021. return target.copy( c );
  5022. }
  5023. const vb = d5 * d2 - d1 * d6;
  5024. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5025. w = d2 / ( d2 - d6 );
  5026. // edge region of AC; barycentric coords (1-w, 0, w)
  5027. return target.copy( a ).addScaledVector( _vac, w );
  5028. }
  5029. const va = d3 * d6 - d5 * d4;
  5030. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5031. _vbc.subVectors( c, b );
  5032. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5033. // edge region of BC; barycentric coords (0, 1-w, w)
  5034. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5035. }
  5036. // face region
  5037. const denom = 1 / ( va + vb + vc );
  5038. // u = va * denom
  5039. v = vb * denom;
  5040. w = vc * denom;
  5041. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5042. }
  5043. equals( triangle ) {
  5044. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5045. }
  5046. }
  5047. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5048. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5049. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5050. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5051. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5052. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5053. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5054. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5055. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5056. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5057. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5058. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5059. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5060. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5061. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5062. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5063. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5064. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5065. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5066. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5067. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5068. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5069. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5070. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5071. const _hslA = { h: 0, s: 0, l: 0 };
  5072. const _hslB = { h: 0, s: 0, l: 0 };
  5073. function hue2rgb( p, q, t ) {
  5074. if ( t < 0 ) t += 1;
  5075. if ( t > 1 ) t -= 1;
  5076. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5077. if ( t < 1 / 2 ) return q;
  5078. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5079. return p;
  5080. }
  5081. class Color {
  5082. constructor( r, g, b ) {
  5083. this.isColor = true;
  5084. this.r = 1;
  5085. this.g = 1;
  5086. this.b = 1;
  5087. return this.set( r, g, b );
  5088. }
  5089. set( r, g, b ) {
  5090. if ( g === undefined && b === undefined ) {
  5091. // r is THREE.Color, hex or string
  5092. const value = r;
  5093. if ( value && value.isColor ) {
  5094. this.copy( value );
  5095. } else if ( typeof value === 'number' ) {
  5096. this.setHex( value );
  5097. } else if ( typeof value === 'string' ) {
  5098. this.setStyle( value );
  5099. }
  5100. } else {
  5101. this.setRGB( r, g, b );
  5102. }
  5103. return this;
  5104. }
  5105. setScalar( scalar ) {
  5106. this.r = scalar;
  5107. this.g = scalar;
  5108. this.b = scalar;
  5109. return this;
  5110. }
  5111. setHex( hex, colorSpace = SRGBColorSpace ) {
  5112. hex = Math.floor( hex );
  5113. this.r = ( hex >> 16 & 255 ) / 255;
  5114. this.g = ( hex >> 8 & 255 ) / 255;
  5115. this.b = ( hex & 255 ) / 255;
  5116. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5117. return this;
  5118. }
  5119. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5120. this.r = r;
  5121. this.g = g;
  5122. this.b = b;
  5123. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5124. return this;
  5125. }
  5126. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5127. // h,s,l ranges are in 0.0 - 1.0
  5128. h = euclideanModulo( h, 1 );
  5129. s = clamp( s, 0, 1 );
  5130. l = clamp( l, 0, 1 );
  5131. if ( s === 0 ) {
  5132. this.r = this.g = this.b = l;
  5133. } else {
  5134. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5135. const q = ( 2 * l ) - p;
  5136. this.r = hue2rgb( q, p, h + 1 / 3 );
  5137. this.g = hue2rgb( q, p, h );
  5138. this.b = hue2rgb( q, p, h - 1 / 3 );
  5139. }
  5140. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5141. return this;
  5142. }
  5143. setStyle( style, colorSpace = SRGBColorSpace ) {
  5144. function handleAlpha( string ) {
  5145. if ( string === undefined ) return;
  5146. if ( parseFloat( string ) < 1 ) {
  5147. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5148. }
  5149. }
  5150. let m;
  5151. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5152. // rgb / hsl
  5153. let color;
  5154. const name = m[ 1 ];
  5155. const components = m[ 2 ];
  5156. switch ( name ) {
  5157. case 'rgb':
  5158. case 'rgba':
  5159. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5160. // rgb(255,0,0) rgba(255,0,0,0.5)
  5161. handleAlpha( color[ 4 ] );
  5162. return this.setRGB(
  5163. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5164. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5165. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5166. colorSpace
  5167. );
  5168. }
  5169. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5170. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5171. handleAlpha( color[ 4 ] );
  5172. return this.setRGB(
  5173. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5174. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5175. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5176. colorSpace
  5177. );
  5178. }
  5179. break;
  5180. case 'hsl':
  5181. case 'hsla':
  5182. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5183. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5184. handleAlpha( color[ 4 ] );
  5185. return this.setHSL(
  5186. parseFloat( color[ 1 ] ) / 360,
  5187. parseFloat( color[ 2 ] ) / 100,
  5188. parseFloat( color[ 3 ] ) / 100,
  5189. colorSpace
  5190. );
  5191. }
  5192. break;
  5193. default:
  5194. console.warn( 'THREE.Color: Unknown color model ' + style );
  5195. }
  5196. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5197. // hex color
  5198. const hex = m[ 1 ];
  5199. const size = hex.length;
  5200. if ( size === 3 ) {
  5201. // #ff0
  5202. return this.setRGB(
  5203. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5204. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5205. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5206. colorSpace
  5207. );
  5208. } else if ( size === 6 ) {
  5209. // #ff0000
  5210. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5211. } else {
  5212. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5213. }
  5214. } else if ( style && style.length > 0 ) {
  5215. return this.setColorName( style, colorSpace );
  5216. }
  5217. return this;
  5218. }
  5219. setColorName( style, colorSpace = SRGBColorSpace ) {
  5220. // color keywords
  5221. const hex = _colorKeywords[ style.toLowerCase() ];
  5222. if ( hex !== undefined ) {
  5223. // red
  5224. this.setHex( hex, colorSpace );
  5225. } else {
  5226. // unknown color
  5227. console.warn( 'THREE.Color: Unknown color ' + style );
  5228. }
  5229. return this;
  5230. }
  5231. clone() {
  5232. return new this.constructor( this.r, this.g, this.b );
  5233. }
  5234. copy( color ) {
  5235. this.r = color.r;
  5236. this.g = color.g;
  5237. this.b = color.b;
  5238. return this;
  5239. }
  5240. copySRGBToLinear( color ) {
  5241. this.r = SRGBToLinear( color.r );
  5242. this.g = SRGBToLinear( color.g );
  5243. this.b = SRGBToLinear( color.b );
  5244. return this;
  5245. }
  5246. copyLinearToSRGB( color ) {
  5247. this.r = LinearToSRGB( color.r );
  5248. this.g = LinearToSRGB( color.g );
  5249. this.b = LinearToSRGB( color.b );
  5250. return this;
  5251. }
  5252. convertSRGBToLinear() {
  5253. this.copySRGBToLinear( this );
  5254. return this;
  5255. }
  5256. convertLinearToSRGB() {
  5257. this.copyLinearToSRGB( this );
  5258. return this;
  5259. }
  5260. getHex( colorSpace = SRGBColorSpace ) {
  5261. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5262. 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 ) );
  5263. }
  5264. getHexString( colorSpace = SRGBColorSpace ) {
  5265. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5266. }
  5267. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5268. // h,s,l ranges are in 0.0 - 1.0
  5269. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5270. const r = _color.r, g = _color.g, b = _color.b;
  5271. const max = Math.max( r, g, b );
  5272. const min = Math.min( r, g, b );
  5273. let hue, saturation;
  5274. const lightness = ( min + max ) / 2.0;
  5275. if ( min === max ) {
  5276. hue = 0;
  5277. saturation = 0;
  5278. } else {
  5279. const delta = max - min;
  5280. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5281. switch ( max ) {
  5282. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5283. case g: hue = ( b - r ) / delta + 2; break;
  5284. case b: hue = ( r - g ) / delta + 4; break;
  5285. }
  5286. hue /= 6;
  5287. }
  5288. target.h = hue;
  5289. target.s = saturation;
  5290. target.l = lightness;
  5291. return target;
  5292. }
  5293. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5294. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5295. target.r = _color.r;
  5296. target.g = _color.g;
  5297. target.b = _color.b;
  5298. return target;
  5299. }
  5300. getStyle( colorSpace = SRGBColorSpace ) {
  5301. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5302. const r = _color.r, g = _color.g, b = _color.b;
  5303. if ( colorSpace !== SRGBColorSpace ) {
  5304. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5305. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5306. }
  5307. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5308. }
  5309. offsetHSL( h, s, l ) {
  5310. this.getHSL( _hslA );
  5311. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5312. }
  5313. add( color ) {
  5314. this.r += color.r;
  5315. this.g += color.g;
  5316. this.b += color.b;
  5317. return this;
  5318. }
  5319. addColors( color1, color2 ) {
  5320. this.r = color1.r + color2.r;
  5321. this.g = color1.g + color2.g;
  5322. this.b = color1.b + color2.b;
  5323. return this;
  5324. }
  5325. addScalar( s ) {
  5326. this.r += s;
  5327. this.g += s;
  5328. this.b += s;
  5329. return this;
  5330. }
  5331. sub( color ) {
  5332. this.r = Math.max( 0, this.r - color.r );
  5333. this.g = Math.max( 0, this.g - color.g );
  5334. this.b = Math.max( 0, this.b - color.b );
  5335. return this;
  5336. }
  5337. multiply( color ) {
  5338. this.r *= color.r;
  5339. this.g *= color.g;
  5340. this.b *= color.b;
  5341. return this;
  5342. }
  5343. multiplyScalar( s ) {
  5344. this.r *= s;
  5345. this.g *= s;
  5346. this.b *= s;
  5347. return this;
  5348. }
  5349. lerp( color, alpha ) {
  5350. this.r += ( color.r - this.r ) * alpha;
  5351. this.g += ( color.g - this.g ) * alpha;
  5352. this.b += ( color.b - this.b ) * alpha;
  5353. return this;
  5354. }
  5355. lerpColors( color1, color2, alpha ) {
  5356. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5357. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5358. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5359. return this;
  5360. }
  5361. lerpHSL( color, alpha ) {
  5362. this.getHSL( _hslA );
  5363. color.getHSL( _hslB );
  5364. const h = lerp( _hslA.h, _hslB.h, alpha );
  5365. const s = lerp( _hslA.s, _hslB.s, alpha );
  5366. const l = lerp( _hslA.l, _hslB.l, alpha );
  5367. this.setHSL( h, s, l );
  5368. return this;
  5369. }
  5370. setFromVector3( v ) {
  5371. this.r = v.x;
  5372. this.g = v.y;
  5373. this.b = v.z;
  5374. return this;
  5375. }
  5376. applyMatrix3( m ) {
  5377. const r = this.r, g = this.g, b = this.b;
  5378. const e = m.elements;
  5379. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5380. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5381. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5382. return this;
  5383. }
  5384. equals( c ) {
  5385. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5386. }
  5387. fromArray( array, offset = 0 ) {
  5388. this.r = array[ offset ];
  5389. this.g = array[ offset + 1 ];
  5390. this.b = array[ offset + 2 ];
  5391. return this;
  5392. }
  5393. toArray( array = [], offset = 0 ) {
  5394. array[ offset ] = this.r;
  5395. array[ offset + 1 ] = this.g;
  5396. array[ offset + 2 ] = this.b;
  5397. return array;
  5398. }
  5399. fromBufferAttribute( attribute, index ) {
  5400. this.r = attribute.getX( index );
  5401. this.g = attribute.getY( index );
  5402. this.b = attribute.getZ( index );
  5403. return this;
  5404. }
  5405. toJSON() {
  5406. return this.getHex();
  5407. }
  5408. *[ Symbol.iterator ]() {
  5409. yield this.r;
  5410. yield this.g;
  5411. yield this.b;
  5412. }
  5413. }
  5414. const _color = /*@__PURE__*/ new Color();
  5415. Color.NAMES = _colorKeywords;
  5416. let _materialId = 0;
  5417. class Material extends EventDispatcher {
  5418. constructor() {
  5419. super();
  5420. this.isMaterial = true;
  5421. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5422. this.uuid = generateUUID();
  5423. this.name = '';
  5424. this.type = 'Material';
  5425. this.blending = NormalBlending;
  5426. this.side = FrontSide;
  5427. this.vertexColors = false;
  5428. this.opacity = 1;
  5429. this.transparent = false;
  5430. this.alphaHash = false;
  5431. this.blendSrc = SrcAlphaFactor;
  5432. this.blendDst = OneMinusSrcAlphaFactor;
  5433. this.blendEquation = AddEquation;
  5434. this.blendSrcAlpha = null;
  5435. this.blendDstAlpha = null;
  5436. this.blendEquationAlpha = null;
  5437. this.blendColor = new Color( 0, 0, 0 );
  5438. this.blendAlpha = 0;
  5439. this.depthFunc = LessEqualDepth;
  5440. this.depthTest = true;
  5441. this.depthWrite = true;
  5442. this.stencilWriteMask = 0xff;
  5443. this.stencilFunc = AlwaysStencilFunc;
  5444. this.stencilRef = 0;
  5445. this.stencilFuncMask = 0xff;
  5446. this.stencilFail = KeepStencilOp;
  5447. this.stencilZFail = KeepStencilOp;
  5448. this.stencilZPass = KeepStencilOp;
  5449. this.stencilWrite = false;
  5450. this.clippingPlanes = null;
  5451. this.clipIntersection = false;
  5452. this.clipShadows = false;
  5453. this.shadowSide = null;
  5454. this.colorWrite = true;
  5455. this.precision = null; // override the renderer's default precision for this material
  5456. this.polygonOffset = false;
  5457. this.polygonOffsetFactor = 0;
  5458. this.polygonOffsetUnits = 0;
  5459. this.dithering = false;
  5460. this.alphaToCoverage = false;
  5461. this.premultipliedAlpha = false;
  5462. this.forceSinglePass = false;
  5463. this.visible = true;
  5464. this.toneMapped = true;
  5465. this.userData = {};
  5466. this.version = 0;
  5467. this._alphaTest = 0;
  5468. }
  5469. get alphaTest() {
  5470. return this._alphaTest;
  5471. }
  5472. set alphaTest( value ) {
  5473. if ( this._alphaTest > 0 !== value > 0 ) {
  5474. this.version ++;
  5475. }
  5476. this._alphaTest = value;
  5477. }
  5478. onBuild( /* shaderobject, renderer */ ) {}
  5479. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5480. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5481. customProgramCacheKey() {
  5482. return this.onBeforeCompile.toString();
  5483. }
  5484. setValues( values ) {
  5485. if ( values === undefined ) return;
  5486. for ( const key in values ) {
  5487. const newValue = values[ key ];
  5488. if ( newValue === undefined ) {
  5489. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5490. continue;
  5491. }
  5492. const currentValue = this[ key ];
  5493. if ( currentValue === undefined ) {
  5494. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5495. continue;
  5496. }
  5497. if ( currentValue && currentValue.isColor ) {
  5498. currentValue.set( newValue );
  5499. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5500. currentValue.copy( newValue );
  5501. } else {
  5502. this[ key ] = newValue;
  5503. }
  5504. }
  5505. }
  5506. toJSON( meta ) {
  5507. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5508. if ( isRootObject ) {
  5509. meta = {
  5510. textures: {},
  5511. images: {}
  5512. };
  5513. }
  5514. const data = {
  5515. metadata: {
  5516. version: 4.6,
  5517. type: 'Material',
  5518. generator: 'Material.toJSON'
  5519. }
  5520. };
  5521. // standard Material serialization
  5522. data.uuid = this.uuid;
  5523. data.type = this.type;
  5524. if ( this.name !== '' ) data.name = this.name;
  5525. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5526. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5527. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5528. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5529. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5530. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5531. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5532. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5533. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5534. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5535. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5536. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5537. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5538. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5539. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5540. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5541. }
  5542. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5543. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5544. }
  5545. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5546. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5547. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5548. }
  5549. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5550. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5551. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5552. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5553. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5554. }
  5555. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5556. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5557. }
  5558. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5559. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5560. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5561. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5562. }
  5563. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5564. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5565. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5566. if ( this.lightMap && this.lightMap.isTexture ) {
  5567. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5568. data.lightMapIntensity = this.lightMapIntensity;
  5569. }
  5570. if ( this.aoMap && this.aoMap.isTexture ) {
  5571. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5572. data.aoMapIntensity = this.aoMapIntensity;
  5573. }
  5574. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5575. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5576. data.bumpScale = this.bumpScale;
  5577. }
  5578. if ( this.normalMap && this.normalMap.isTexture ) {
  5579. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5580. data.normalMapType = this.normalMapType;
  5581. data.normalScale = this.normalScale.toArray();
  5582. }
  5583. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5584. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5585. data.displacementScale = this.displacementScale;
  5586. data.displacementBias = this.displacementBias;
  5587. }
  5588. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5589. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5590. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5591. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5592. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5593. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5594. if ( this.envMap && this.envMap.isTexture ) {
  5595. data.envMap = this.envMap.toJSON( meta ).uuid;
  5596. if ( this.combine !== undefined ) data.combine = this.combine;
  5597. }
  5598. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5599. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5600. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5601. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5602. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5603. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5604. }
  5605. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5606. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5607. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5608. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5609. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5610. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5611. if ( this.size !== undefined ) data.size = this.size;
  5612. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5613. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5614. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5615. if ( this.side !== FrontSide ) data.side = this.side;
  5616. if ( this.vertexColors === true ) data.vertexColors = true;
  5617. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5618. if ( this.transparent === true ) data.transparent = true;
  5619. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5620. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5621. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5622. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5623. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5624. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5625. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5626. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5627. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5628. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5629. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5630. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5631. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5632. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5633. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5634. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5635. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5636. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5637. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5638. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5639. // rotation (SpriteMaterial)
  5640. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5641. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5642. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5643. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5644. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5645. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5646. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5647. if ( this.scale !== undefined ) data.scale = this.scale;
  5648. if ( this.dithering === true ) data.dithering = true;
  5649. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5650. if ( this.alphaHash === true ) data.alphaHash = true;
  5651. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5652. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5653. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5654. if ( this.wireframe === true ) data.wireframe = true;
  5655. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5656. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5657. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5658. if ( this.flatShading === true ) data.flatShading = true;
  5659. if ( this.visible === false ) data.visible = false;
  5660. if ( this.toneMapped === false ) data.toneMapped = false;
  5661. if ( this.fog === false ) data.fog = false;
  5662. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5663. // TODO: Copied from Object3D.toJSON
  5664. function extractFromCache( cache ) {
  5665. const values = [];
  5666. for ( const key in cache ) {
  5667. const data = cache[ key ];
  5668. delete data.metadata;
  5669. values.push( data );
  5670. }
  5671. return values;
  5672. }
  5673. if ( isRootObject ) {
  5674. const textures = extractFromCache( meta.textures );
  5675. const images = extractFromCache( meta.images );
  5676. if ( textures.length > 0 ) data.textures = textures;
  5677. if ( images.length > 0 ) data.images = images;
  5678. }
  5679. return data;
  5680. }
  5681. clone() {
  5682. return new this.constructor().copy( this );
  5683. }
  5684. copy( source ) {
  5685. this.name = source.name;
  5686. this.blending = source.blending;
  5687. this.side = source.side;
  5688. this.vertexColors = source.vertexColors;
  5689. this.opacity = source.opacity;
  5690. this.transparent = source.transparent;
  5691. this.blendSrc = source.blendSrc;
  5692. this.blendDst = source.blendDst;
  5693. this.blendEquation = source.blendEquation;
  5694. this.blendSrcAlpha = source.blendSrcAlpha;
  5695. this.blendDstAlpha = source.blendDstAlpha;
  5696. this.blendEquationAlpha = source.blendEquationAlpha;
  5697. this.blendColor.copy( source.blendColor );
  5698. this.blendAlpha = source.blendAlpha;
  5699. this.depthFunc = source.depthFunc;
  5700. this.depthTest = source.depthTest;
  5701. this.depthWrite = source.depthWrite;
  5702. this.stencilWriteMask = source.stencilWriteMask;
  5703. this.stencilFunc = source.stencilFunc;
  5704. this.stencilRef = source.stencilRef;
  5705. this.stencilFuncMask = source.stencilFuncMask;
  5706. this.stencilFail = source.stencilFail;
  5707. this.stencilZFail = source.stencilZFail;
  5708. this.stencilZPass = source.stencilZPass;
  5709. this.stencilWrite = source.stencilWrite;
  5710. const srcPlanes = source.clippingPlanes;
  5711. let dstPlanes = null;
  5712. if ( srcPlanes !== null ) {
  5713. const n = srcPlanes.length;
  5714. dstPlanes = new Array( n );
  5715. for ( let i = 0; i !== n; ++ i ) {
  5716. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5717. }
  5718. }
  5719. this.clippingPlanes = dstPlanes;
  5720. this.clipIntersection = source.clipIntersection;
  5721. this.clipShadows = source.clipShadows;
  5722. this.shadowSide = source.shadowSide;
  5723. this.colorWrite = source.colorWrite;
  5724. this.precision = source.precision;
  5725. this.polygonOffset = source.polygonOffset;
  5726. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5727. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5728. this.dithering = source.dithering;
  5729. this.alphaTest = source.alphaTest;
  5730. this.alphaHash = source.alphaHash;
  5731. this.alphaToCoverage = source.alphaToCoverage;
  5732. this.premultipliedAlpha = source.premultipliedAlpha;
  5733. this.forceSinglePass = source.forceSinglePass;
  5734. this.visible = source.visible;
  5735. this.toneMapped = source.toneMapped;
  5736. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5737. return this;
  5738. }
  5739. dispose() {
  5740. this.dispatchEvent( { type: 'dispose' } );
  5741. }
  5742. set needsUpdate( value ) {
  5743. if ( value === true ) this.version ++;
  5744. }
  5745. }
  5746. class MeshBasicMaterial extends Material {
  5747. constructor( parameters ) {
  5748. super();
  5749. this.isMeshBasicMaterial = true;
  5750. this.type = 'MeshBasicMaterial';
  5751. this.color = new Color( 0xffffff ); // emissive
  5752. this.map = null;
  5753. this.lightMap = null;
  5754. this.lightMapIntensity = 1.0;
  5755. this.aoMap = null;
  5756. this.aoMapIntensity = 1.0;
  5757. this.specularMap = null;
  5758. this.alphaMap = null;
  5759. this.envMap = null;
  5760. this.envMapRotation = new Euler();
  5761. this.combine = MultiplyOperation;
  5762. this.reflectivity = 1;
  5763. this.refractionRatio = 0.98;
  5764. this.wireframe = false;
  5765. this.wireframeLinewidth = 1;
  5766. this.wireframeLinecap = 'round';
  5767. this.wireframeLinejoin = 'round';
  5768. this.fog = true;
  5769. this.setValues( parameters );
  5770. }
  5771. copy( source ) {
  5772. super.copy( source );
  5773. this.color.copy( source.color );
  5774. this.map = source.map;
  5775. this.lightMap = source.lightMap;
  5776. this.lightMapIntensity = source.lightMapIntensity;
  5777. this.aoMap = source.aoMap;
  5778. this.aoMapIntensity = source.aoMapIntensity;
  5779. this.specularMap = source.specularMap;
  5780. this.alphaMap = source.alphaMap;
  5781. this.envMap = source.envMap;
  5782. this.envMapRotation.copy( source.envMapRotation );
  5783. this.combine = source.combine;
  5784. this.reflectivity = source.reflectivity;
  5785. this.refractionRatio = source.refractionRatio;
  5786. this.wireframe = source.wireframe;
  5787. this.wireframeLinewidth = source.wireframeLinewidth;
  5788. this.wireframeLinecap = source.wireframeLinecap;
  5789. this.wireframeLinejoin = source.wireframeLinejoin;
  5790. this.fog = source.fog;
  5791. return this;
  5792. }
  5793. }
  5794. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5795. const _tables = /*@__PURE__*/ _generateTables();
  5796. function _generateTables() {
  5797. // float32 to float16 helpers
  5798. const buffer = new ArrayBuffer( 4 );
  5799. const floatView = new Float32Array( buffer );
  5800. const uint32View = new Uint32Array( buffer );
  5801. const baseTable = new Uint32Array( 512 );
  5802. const shiftTable = new Uint32Array( 512 );
  5803. for ( let i = 0; i < 256; ++ i ) {
  5804. const e = i - 127;
  5805. // very small number (0, -0)
  5806. if ( e < - 27 ) {
  5807. baseTable[ i ] = 0x0000;
  5808. baseTable[ i | 0x100 ] = 0x8000;
  5809. shiftTable[ i ] = 24;
  5810. shiftTable[ i | 0x100 ] = 24;
  5811. // small number (denorm)
  5812. } else if ( e < - 14 ) {
  5813. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5814. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5815. shiftTable[ i ] = - e - 1;
  5816. shiftTable[ i | 0x100 ] = - e - 1;
  5817. // normal number
  5818. } else if ( e <= 15 ) {
  5819. baseTable[ i ] = ( e + 15 ) << 10;
  5820. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5821. shiftTable[ i ] = 13;
  5822. shiftTable[ i | 0x100 ] = 13;
  5823. // large number (Infinity, -Infinity)
  5824. } else if ( e < 128 ) {
  5825. baseTable[ i ] = 0x7c00;
  5826. baseTable[ i | 0x100 ] = 0xfc00;
  5827. shiftTable[ i ] = 24;
  5828. shiftTable[ i | 0x100 ] = 24;
  5829. // stay (NaN, Infinity, -Infinity)
  5830. } else {
  5831. baseTable[ i ] = 0x7c00;
  5832. baseTable[ i | 0x100 ] = 0xfc00;
  5833. shiftTable[ i ] = 13;
  5834. shiftTable[ i | 0x100 ] = 13;
  5835. }
  5836. }
  5837. // float16 to float32 helpers
  5838. const mantissaTable = new Uint32Array( 2048 );
  5839. const exponentTable = new Uint32Array( 64 );
  5840. const offsetTable = new Uint32Array( 64 );
  5841. for ( let i = 1; i < 1024; ++ i ) {
  5842. let m = i << 13; // zero pad mantissa bits
  5843. let e = 0; // zero exponent
  5844. // normalized
  5845. while ( ( m & 0x00800000 ) === 0 ) {
  5846. m <<= 1;
  5847. e -= 0x00800000; // decrement exponent
  5848. }
  5849. m &= ~ 0x00800000; // clear leading 1 bit
  5850. e += 0x38800000; // adjust bias
  5851. mantissaTable[ i ] = m | e;
  5852. }
  5853. for ( let i = 1024; i < 2048; ++ i ) {
  5854. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5855. }
  5856. for ( let i = 1; i < 31; ++ i ) {
  5857. exponentTable[ i ] = i << 23;
  5858. }
  5859. exponentTable[ 31 ] = 0x47800000;
  5860. exponentTable[ 32 ] = 0x80000000;
  5861. for ( let i = 33; i < 63; ++ i ) {
  5862. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5863. }
  5864. exponentTable[ 63 ] = 0xc7800000;
  5865. for ( let i = 1; i < 64; ++ i ) {
  5866. if ( i !== 32 ) {
  5867. offsetTable[ i ] = 1024;
  5868. }
  5869. }
  5870. return {
  5871. floatView: floatView,
  5872. uint32View: uint32View,
  5873. baseTable: baseTable,
  5874. shiftTable: shiftTable,
  5875. mantissaTable: mantissaTable,
  5876. exponentTable: exponentTable,
  5877. offsetTable: offsetTable
  5878. };
  5879. }
  5880. // float32 to float16
  5881. function toHalfFloat( val ) {
  5882. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5883. val = clamp( val, - 65504, 65504 );
  5884. _tables.floatView[ 0 ] = val;
  5885. const f = _tables.uint32View[ 0 ];
  5886. const e = ( f >> 23 ) & 0x1ff;
  5887. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5888. }
  5889. // float16 to float32
  5890. function fromHalfFloat( val ) {
  5891. const m = val >> 10;
  5892. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5893. return _tables.floatView[ 0 ];
  5894. }
  5895. const DataUtils = {
  5896. toHalfFloat: toHalfFloat,
  5897. fromHalfFloat: fromHalfFloat,
  5898. };
  5899. const _vector$9 = /*@__PURE__*/ new Vector3();
  5900. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5901. class BufferAttribute {
  5902. constructor( array, itemSize, normalized = false ) {
  5903. if ( Array.isArray( array ) ) {
  5904. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5905. }
  5906. this.isBufferAttribute = true;
  5907. this.name = '';
  5908. this.array = array;
  5909. this.itemSize = itemSize;
  5910. this.count = array !== undefined ? array.length / itemSize : 0;
  5911. this.normalized = normalized;
  5912. this.usage = StaticDrawUsage;
  5913. this._updateRange = { offset: 0, count: - 1 };
  5914. this.updateRanges = [];
  5915. this.gpuType = FloatType;
  5916. this.version = 0;
  5917. }
  5918. onUploadCallback() {}
  5919. set needsUpdate( value ) {
  5920. if ( value === true ) this.version ++;
  5921. }
  5922. get updateRange() {
  5923. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5924. return this._updateRange;
  5925. }
  5926. setUsage( value ) {
  5927. this.usage = value;
  5928. return this;
  5929. }
  5930. addUpdateRange( start, count ) {
  5931. this.updateRanges.push( { start, count } );
  5932. }
  5933. clearUpdateRanges() {
  5934. this.updateRanges.length = 0;
  5935. }
  5936. copy( source ) {
  5937. this.name = source.name;
  5938. this.array = new source.array.constructor( source.array );
  5939. this.itemSize = source.itemSize;
  5940. this.count = source.count;
  5941. this.normalized = source.normalized;
  5942. this.usage = source.usage;
  5943. this.gpuType = source.gpuType;
  5944. return this;
  5945. }
  5946. copyAt( index1, attribute, index2 ) {
  5947. index1 *= this.itemSize;
  5948. index2 *= attribute.itemSize;
  5949. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5950. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5951. }
  5952. return this;
  5953. }
  5954. copyArray( array ) {
  5955. this.array.set( array );
  5956. return this;
  5957. }
  5958. applyMatrix3( m ) {
  5959. if ( this.itemSize === 2 ) {
  5960. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5961. _vector2$1.fromBufferAttribute( this, i );
  5962. _vector2$1.applyMatrix3( m );
  5963. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5964. }
  5965. } else if ( this.itemSize === 3 ) {
  5966. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5967. _vector$9.fromBufferAttribute( this, i );
  5968. _vector$9.applyMatrix3( m );
  5969. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5970. }
  5971. }
  5972. return this;
  5973. }
  5974. applyMatrix4( m ) {
  5975. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5976. _vector$9.fromBufferAttribute( this, i );
  5977. _vector$9.applyMatrix4( m );
  5978. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5979. }
  5980. return this;
  5981. }
  5982. applyNormalMatrix( m ) {
  5983. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5984. _vector$9.fromBufferAttribute( this, i );
  5985. _vector$9.applyNormalMatrix( m );
  5986. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5987. }
  5988. return this;
  5989. }
  5990. transformDirection( m ) {
  5991. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5992. _vector$9.fromBufferAttribute( this, i );
  5993. _vector$9.transformDirection( m );
  5994. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5995. }
  5996. return this;
  5997. }
  5998. set( value, offset = 0 ) {
  5999. // Matching BufferAttribute constructor, do not normalize the array.
  6000. this.array.set( value, offset );
  6001. return this;
  6002. }
  6003. getComponent( index, component ) {
  6004. let value = this.array[ index * this.itemSize + component ];
  6005. if ( this.normalized ) value = denormalize( value, this.array );
  6006. return value;
  6007. }
  6008. setComponent( index, component, value ) {
  6009. if ( this.normalized ) value = normalize( value, this.array );
  6010. this.array[ index * this.itemSize + component ] = value;
  6011. return this;
  6012. }
  6013. getX( index ) {
  6014. let x = this.array[ index * this.itemSize ];
  6015. if ( this.normalized ) x = denormalize( x, this.array );
  6016. return x;
  6017. }
  6018. setX( index, x ) {
  6019. if ( this.normalized ) x = normalize( x, this.array );
  6020. this.array[ index * this.itemSize ] = x;
  6021. return this;
  6022. }
  6023. getY( index ) {
  6024. let y = this.array[ index * this.itemSize + 1 ];
  6025. if ( this.normalized ) y = denormalize( y, this.array );
  6026. return y;
  6027. }
  6028. setY( index, y ) {
  6029. if ( this.normalized ) y = normalize( y, this.array );
  6030. this.array[ index * this.itemSize + 1 ] = y;
  6031. return this;
  6032. }
  6033. getZ( index ) {
  6034. let z = this.array[ index * this.itemSize + 2 ];
  6035. if ( this.normalized ) z = denormalize( z, this.array );
  6036. return z;
  6037. }
  6038. setZ( index, z ) {
  6039. if ( this.normalized ) z = normalize( z, this.array );
  6040. this.array[ index * this.itemSize + 2 ] = z;
  6041. return this;
  6042. }
  6043. getW( index ) {
  6044. let w = this.array[ index * this.itemSize + 3 ];
  6045. if ( this.normalized ) w = denormalize( w, this.array );
  6046. return w;
  6047. }
  6048. setW( index, w ) {
  6049. if ( this.normalized ) w = normalize( w, this.array );
  6050. this.array[ index * this.itemSize + 3 ] = w;
  6051. return this;
  6052. }
  6053. setXY( index, x, y ) {
  6054. index *= this.itemSize;
  6055. if ( this.normalized ) {
  6056. x = normalize( x, this.array );
  6057. y = normalize( y, this.array );
  6058. }
  6059. this.array[ index + 0 ] = x;
  6060. this.array[ index + 1 ] = y;
  6061. return this;
  6062. }
  6063. setXYZ( index, x, y, z ) {
  6064. index *= this.itemSize;
  6065. if ( this.normalized ) {
  6066. x = normalize( x, this.array );
  6067. y = normalize( y, this.array );
  6068. z = normalize( z, this.array );
  6069. }
  6070. this.array[ index + 0 ] = x;
  6071. this.array[ index + 1 ] = y;
  6072. this.array[ index + 2 ] = z;
  6073. return this;
  6074. }
  6075. setXYZW( index, x, y, z, w ) {
  6076. index *= this.itemSize;
  6077. if ( this.normalized ) {
  6078. x = normalize( x, this.array );
  6079. y = normalize( y, this.array );
  6080. z = normalize( z, this.array );
  6081. w = normalize( w, this.array );
  6082. }
  6083. this.array[ index + 0 ] = x;
  6084. this.array[ index + 1 ] = y;
  6085. this.array[ index + 2 ] = z;
  6086. this.array[ index + 3 ] = w;
  6087. return this;
  6088. }
  6089. onUpload( callback ) {
  6090. this.onUploadCallback = callback;
  6091. return this;
  6092. }
  6093. clone() {
  6094. return new this.constructor( this.array, this.itemSize ).copy( this );
  6095. }
  6096. toJSON() {
  6097. const data = {
  6098. itemSize: this.itemSize,
  6099. type: this.array.constructor.name,
  6100. array: Array.from( this.array ),
  6101. normalized: this.normalized
  6102. };
  6103. if ( this.name !== '' ) data.name = this.name;
  6104. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6105. return data;
  6106. }
  6107. }
  6108. //
  6109. class Int8BufferAttribute extends BufferAttribute {
  6110. constructor( array, itemSize, normalized ) {
  6111. super( new Int8Array( array ), itemSize, normalized );
  6112. }
  6113. }
  6114. class Uint8BufferAttribute extends BufferAttribute {
  6115. constructor( array, itemSize, normalized ) {
  6116. super( new Uint8Array( array ), itemSize, normalized );
  6117. }
  6118. }
  6119. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6120. constructor( array, itemSize, normalized ) {
  6121. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6122. }
  6123. }
  6124. class Int16BufferAttribute extends BufferAttribute {
  6125. constructor( array, itemSize, normalized ) {
  6126. super( new Int16Array( array ), itemSize, normalized );
  6127. }
  6128. }
  6129. class Uint16BufferAttribute extends BufferAttribute {
  6130. constructor( array, itemSize, normalized ) {
  6131. super( new Uint16Array( array ), itemSize, normalized );
  6132. }
  6133. }
  6134. class Int32BufferAttribute extends BufferAttribute {
  6135. constructor( array, itemSize, normalized ) {
  6136. super( new Int32Array( array ), itemSize, normalized );
  6137. }
  6138. }
  6139. class Uint32BufferAttribute extends BufferAttribute {
  6140. constructor( array, itemSize, normalized ) {
  6141. super( new Uint32Array( array ), itemSize, normalized );
  6142. }
  6143. }
  6144. class Float16BufferAttribute extends BufferAttribute {
  6145. constructor( array, itemSize, normalized ) {
  6146. super( new Uint16Array( array ), itemSize, normalized );
  6147. this.isFloat16BufferAttribute = true;
  6148. }
  6149. getX( index ) {
  6150. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6151. if ( this.normalized ) x = denormalize( x, this.array );
  6152. return x;
  6153. }
  6154. setX( index, x ) {
  6155. if ( this.normalized ) x = normalize( x, this.array );
  6156. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6157. return this;
  6158. }
  6159. getY( index ) {
  6160. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6161. if ( this.normalized ) y = denormalize( y, this.array );
  6162. return y;
  6163. }
  6164. setY( index, y ) {
  6165. if ( this.normalized ) y = normalize( y, this.array );
  6166. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6167. return this;
  6168. }
  6169. getZ( index ) {
  6170. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6171. if ( this.normalized ) z = denormalize( z, this.array );
  6172. return z;
  6173. }
  6174. setZ( index, z ) {
  6175. if ( this.normalized ) z = normalize( z, this.array );
  6176. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6177. return this;
  6178. }
  6179. getW( index ) {
  6180. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6181. if ( this.normalized ) w = denormalize( w, this.array );
  6182. return w;
  6183. }
  6184. setW( index, w ) {
  6185. if ( this.normalized ) w = normalize( w, this.array );
  6186. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6187. return this;
  6188. }
  6189. setXY( index, x, y ) {
  6190. index *= this.itemSize;
  6191. if ( this.normalized ) {
  6192. x = normalize( x, this.array );
  6193. y = normalize( y, this.array );
  6194. }
  6195. this.array[ index + 0 ] = toHalfFloat( x );
  6196. this.array[ index + 1 ] = toHalfFloat( y );
  6197. return this;
  6198. }
  6199. setXYZ( index, x, y, z ) {
  6200. index *= this.itemSize;
  6201. if ( this.normalized ) {
  6202. x = normalize( x, this.array );
  6203. y = normalize( y, this.array );
  6204. z = normalize( z, this.array );
  6205. }
  6206. this.array[ index + 0 ] = toHalfFloat( x );
  6207. this.array[ index + 1 ] = toHalfFloat( y );
  6208. this.array[ index + 2 ] = toHalfFloat( z );
  6209. return this;
  6210. }
  6211. setXYZW( index, x, y, z, w ) {
  6212. index *= this.itemSize;
  6213. if ( this.normalized ) {
  6214. x = normalize( x, this.array );
  6215. y = normalize( y, this.array );
  6216. z = normalize( z, this.array );
  6217. w = normalize( w, this.array );
  6218. }
  6219. this.array[ index + 0 ] = toHalfFloat( x );
  6220. this.array[ index + 1 ] = toHalfFloat( y );
  6221. this.array[ index + 2 ] = toHalfFloat( z );
  6222. this.array[ index + 3 ] = toHalfFloat( w );
  6223. return this;
  6224. }
  6225. }
  6226. class Float32BufferAttribute extends BufferAttribute {
  6227. constructor( array, itemSize, normalized ) {
  6228. super( new Float32Array( array ), itemSize, normalized );
  6229. }
  6230. }
  6231. let _id$2 = 0;
  6232. const _m1$2 = /*@__PURE__*/ new Matrix4();
  6233. const _obj = /*@__PURE__*/ new Object3D();
  6234. const _offset = /*@__PURE__*/ new Vector3();
  6235. const _box$2 = /*@__PURE__*/ new Box3();
  6236. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6237. const _vector$8 = /*@__PURE__*/ new Vector3();
  6238. class BufferGeometry extends EventDispatcher {
  6239. constructor() {
  6240. super();
  6241. this.isBufferGeometry = true;
  6242. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6243. this.uuid = generateUUID();
  6244. this.name = '';
  6245. this.type = 'BufferGeometry';
  6246. this.index = null;
  6247. this.attributes = {};
  6248. this.morphAttributes = {};
  6249. this.morphTargetsRelative = false;
  6250. this.groups = [];
  6251. this.boundingBox = null;
  6252. this.boundingSphere = null;
  6253. this.drawRange = { start: 0, count: Infinity };
  6254. this.userData = {};
  6255. }
  6256. getIndex() {
  6257. return this.index;
  6258. }
  6259. setIndex( index ) {
  6260. if ( Array.isArray( index ) ) {
  6261. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6262. } else {
  6263. this.index = index;
  6264. }
  6265. return this;
  6266. }
  6267. getAttribute( name ) {
  6268. return this.attributes[ name ];
  6269. }
  6270. setAttribute( name, attribute ) {
  6271. this.attributes[ name ] = attribute;
  6272. return this;
  6273. }
  6274. deleteAttribute( name ) {
  6275. delete this.attributes[ name ];
  6276. return this;
  6277. }
  6278. hasAttribute( name ) {
  6279. return this.attributes[ name ] !== undefined;
  6280. }
  6281. addGroup( start, count, materialIndex = 0 ) {
  6282. this.groups.push( {
  6283. start: start,
  6284. count: count,
  6285. materialIndex: materialIndex
  6286. } );
  6287. }
  6288. clearGroups() {
  6289. this.groups = [];
  6290. }
  6291. setDrawRange( start, count ) {
  6292. this.drawRange.start = start;
  6293. this.drawRange.count = count;
  6294. }
  6295. applyMatrix4( matrix ) {
  6296. const position = this.attributes.position;
  6297. if ( position !== undefined ) {
  6298. position.applyMatrix4( matrix );
  6299. position.needsUpdate = true;
  6300. }
  6301. const normal = this.attributes.normal;
  6302. if ( normal !== undefined ) {
  6303. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6304. normal.applyNormalMatrix( normalMatrix );
  6305. normal.needsUpdate = true;
  6306. }
  6307. const tangent = this.attributes.tangent;
  6308. if ( tangent !== undefined ) {
  6309. tangent.transformDirection( matrix );
  6310. tangent.needsUpdate = true;
  6311. }
  6312. if ( this.boundingBox !== null ) {
  6313. this.computeBoundingBox();
  6314. }
  6315. if ( this.boundingSphere !== null ) {
  6316. this.computeBoundingSphere();
  6317. }
  6318. return this;
  6319. }
  6320. applyQuaternion( q ) {
  6321. _m1$2.makeRotationFromQuaternion( q );
  6322. this.applyMatrix4( _m1$2 );
  6323. return this;
  6324. }
  6325. rotateX( angle ) {
  6326. // rotate geometry around world x-axis
  6327. _m1$2.makeRotationX( angle );
  6328. this.applyMatrix4( _m1$2 );
  6329. return this;
  6330. }
  6331. rotateY( angle ) {
  6332. // rotate geometry around world y-axis
  6333. _m1$2.makeRotationY( angle );
  6334. this.applyMatrix4( _m1$2 );
  6335. return this;
  6336. }
  6337. rotateZ( angle ) {
  6338. // rotate geometry around world z-axis
  6339. _m1$2.makeRotationZ( angle );
  6340. this.applyMatrix4( _m1$2 );
  6341. return this;
  6342. }
  6343. translate( x, y, z ) {
  6344. // translate geometry
  6345. _m1$2.makeTranslation( x, y, z );
  6346. this.applyMatrix4( _m1$2 );
  6347. return this;
  6348. }
  6349. scale( x, y, z ) {
  6350. // scale geometry
  6351. _m1$2.makeScale( x, y, z );
  6352. this.applyMatrix4( _m1$2 );
  6353. return this;
  6354. }
  6355. lookAt( vector ) {
  6356. _obj.lookAt( vector );
  6357. _obj.updateMatrix();
  6358. this.applyMatrix4( _obj.matrix );
  6359. return this;
  6360. }
  6361. center() {
  6362. this.computeBoundingBox();
  6363. this.boundingBox.getCenter( _offset ).negate();
  6364. this.translate( _offset.x, _offset.y, _offset.z );
  6365. return this;
  6366. }
  6367. setFromPoints( points ) {
  6368. const position = [];
  6369. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6370. const point = points[ i ];
  6371. position.push( point.x, point.y, point.z || 0 );
  6372. }
  6373. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6374. return this;
  6375. }
  6376. computeBoundingBox() {
  6377. if ( this.boundingBox === null ) {
  6378. this.boundingBox = new Box3();
  6379. }
  6380. const position = this.attributes.position;
  6381. const morphAttributesPosition = this.morphAttributes.position;
  6382. if ( position && position.isGLBufferAttribute ) {
  6383. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6384. this.boundingBox.set(
  6385. new Vector3( - Infinity, - Infinity, - Infinity ),
  6386. new Vector3( + Infinity, + Infinity, + Infinity )
  6387. );
  6388. return;
  6389. }
  6390. if ( position !== undefined ) {
  6391. this.boundingBox.setFromBufferAttribute( position );
  6392. // process morph attributes if present
  6393. if ( morphAttributesPosition ) {
  6394. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6395. const morphAttribute = morphAttributesPosition[ i ];
  6396. _box$2.setFromBufferAttribute( morphAttribute );
  6397. if ( this.morphTargetsRelative ) {
  6398. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6399. this.boundingBox.expandByPoint( _vector$8 );
  6400. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6401. this.boundingBox.expandByPoint( _vector$8 );
  6402. } else {
  6403. this.boundingBox.expandByPoint( _box$2.min );
  6404. this.boundingBox.expandByPoint( _box$2.max );
  6405. }
  6406. }
  6407. }
  6408. } else {
  6409. this.boundingBox.makeEmpty();
  6410. }
  6411. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6412. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6413. }
  6414. }
  6415. computeBoundingSphere() {
  6416. if ( this.boundingSphere === null ) {
  6417. this.boundingSphere = new Sphere();
  6418. }
  6419. const position = this.attributes.position;
  6420. const morphAttributesPosition = this.morphAttributes.position;
  6421. if ( position && position.isGLBufferAttribute ) {
  6422. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6423. this.boundingSphere.set( new Vector3(), Infinity );
  6424. return;
  6425. }
  6426. if ( position ) {
  6427. // first, find the center of the bounding sphere
  6428. const center = this.boundingSphere.center;
  6429. _box$2.setFromBufferAttribute( position );
  6430. // process morph attributes if present
  6431. if ( morphAttributesPosition ) {
  6432. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6433. const morphAttribute = morphAttributesPosition[ i ];
  6434. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6435. if ( this.morphTargetsRelative ) {
  6436. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6437. _box$2.expandByPoint( _vector$8 );
  6438. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6439. _box$2.expandByPoint( _vector$8 );
  6440. } else {
  6441. _box$2.expandByPoint( _boxMorphTargets.min );
  6442. _box$2.expandByPoint( _boxMorphTargets.max );
  6443. }
  6444. }
  6445. }
  6446. _box$2.getCenter( center );
  6447. // second, try to find a boundingSphere with a radius smaller than the
  6448. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6449. let maxRadiusSq = 0;
  6450. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6451. _vector$8.fromBufferAttribute( position, i );
  6452. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6453. }
  6454. // process morph attributes if present
  6455. if ( morphAttributesPosition ) {
  6456. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6457. const morphAttribute = morphAttributesPosition[ i ];
  6458. const morphTargetsRelative = this.morphTargetsRelative;
  6459. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6460. _vector$8.fromBufferAttribute( morphAttribute, j );
  6461. if ( morphTargetsRelative ) {
  6462. _offset.fromBufferAttribute( position, j );
  6463. _vector$8.add( _offset );
  6464. }
  6465. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6466. }
  6467. }
  6468. }
  6469. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6470. if ( isNaN( this.boundingSphere.radius ) ) {
  6471. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6472. }
  6473. }
  6474. }
  6475. computeTangents() {
  6476. const index = this.index;
  6477. const attributes = this.attributes;
  6478. // based on http://www.terathon.com/code/tangent.html
  6479. // (per vertex tangents)
  6480. if ( index === null ||
  6481. attributes.position === undefined ||
  6482. attributes.normal === undefined ||
  6483. attributes.uv === undefined ) {
  6484. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6485. return;
  6486. }
  6487. const positionAttribute = attributes.position;
  6488. const normalAttribute = attributes.normal;
  6489. const uvAttribute = attributes.uv;
  6490. if ( this.hasAttribute( 'tangent' ) === false ) {
  6491. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6492. }
  6493. const tangentAttribute = this.getAttribute( 'tangent' );
  6494. const tan1 = [], tan2 = [];
  6495. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6496. tan1[ i ] = new Vector3();
  6497. tan2[ i ] = new Vector3();
  6498. }
  6499. const vA = new Vector3(),
  6500. vB = new Vector3(),
  6501. vC = new Vector3(),
  6502. uvA = new Vector2(),
  6503. uvB = new Vector2(),
  6504. uvC = new Vector2(),
  6505. sdir = new Vector3(),
  6506. tdir = new Vector3();
  6507. function handleTriangle( a, b, c ) {
  6508. vA.fromBufferAttribute( positionAttribute, a );
  6509. vB.fromBufferAttribute( positionAttribute, b );
  6510. vC.fromBufferAttribute( positionAttribute, c );
  6511. uvA.fromBufferAttribute( uvAttribute, a );
  6512. uvB.fromBufferAttribute( uvAttribute, b );
  6513. uvC.fromBufferAttribute( uvAttribute, c );
  6514. vB.sub( vA );
  6515. vC.sub( vA );
  6516. uvB.sub( uvA );
  6517. uvC.sub( uvA );
  6518. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6519. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6520. if ( ! isFinite( r ) ) return;
  6521. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6522. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6523. tan1[ a ].add( sdir );
  6524. tan1[ b ].add( sdir );
  6525. tan1[ c ].add( sdir );
  6526. tan2[ a ].add( tdir );
  6527. tan2[ b ].add( tdir );
  6528. tan2[ c ].add( tdir );
  6529. }
  6530. let groups = this.groups;
  6531. if ( groups.length === 0 ) {
  6532. groups = [ {
  6533. start: 0,
  6534. count: index.count
  6535. } ];
  6536. }
  6537. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6538. const group = groups[ i ];
  6539. const start = group.start;
  6540. const count = group.count;
  6541. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6542. handleTriangle(
  6543. index.getX( j + 0 ),
  6544. index.getX( j + 1 ),
  6545. index.getX( j + 2 )
  6546. );
  6547. }
  6548. }
  6549. const tmp = new Vector3(), tmp2 = new Vector3();
  6550. const n = new Vector3(), n2 = new Vector3();
  6551. function handleVertex( v ) {
  6552. n.fromBufferAttribute( normalAttribute, v );
  6553. n2.copy( n );
  6554. const t = tan1[ v ];
  6555. // Gram-Schmidt orthogonalize
  6556. tmp.copy( t );
  6557. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6558. // Calculate handedness
  6559. tmp2.crossVectors( n2, t );
  6560. const test = tmp2.dot( tan2[ v ] );
  6561. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6562. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6563. }
  6564. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6565. const group = groups[ i ];
  6566. const start = group.start;
  6567. const count = group.count;
  6568. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6569. handleVertex( index.getX( j + 0 ) );
  6570. handleVertex( index.getX( j + 1 ) );
  6571. handleVertex( index.getX( j + 2 ) );
  6572. }
  6573. }
  6574. }
  6575. computeVertexNormals() {
  6576. const index = this.index;
  6577. const positionAttribute = this.getAttribute( 'position' );
  6578. if ( positionAttribute !== undefined ) {
  6579. let normalAttribute = this.getAttribute( 'normal' );
  6580. if ( normalAttribute === undefined ) {
  6581. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6582. this.setAttribute( 'normal', normalAttribute );
  6583. } else {
  6584. // reset existing normals to zero
  6585. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6586. normalAttribute.setXYZ( i, 0, 0, 0 );
  6587. }
  6588. }
  6589. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6590. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6591. const cb = new Vector3(), ab = new Vector3();
  6592. // indexed elements
  6593. if ( index ) {
  6594. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6595. const vA = index.getX( i + 0 );
  6596. const vB = index.getX( i + 1 );
  6597. const vC = index.getX( i + 2 );
  6598. pA.fromBufferAttribute( positionAttribute, vA );
  6599. pB.fromBufferAttribute( positionAttribute, vB );
  6600. pC.fromBufferAttribute( positionAttribute, vC );
  6601. cb.subVectors( pC, pB );
  6602. ab.subVectors( pA, pB );
  6603. cb.cross( ab );
  6604. nA.fromBufferAttribute( normalAttribute, vA );
  6605. nB.fromBufferAttribute( normalAttribute, vB );
  6606. nC.fromBufferAttribute( normalAttribute, vC );
  6607. nA.add( cb );
  6608. nB.add( cb );
  6609. nC.add( cb );
  6610. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6611. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6612. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6613. }
  6614. } else {
  6615. // non-indexed elements (unconnected triangle soup)
  6616. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6617. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6618. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6619. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6620. cb.subVectors( pC, pB );
  6621. ab.subVectors( pA, pB );
  6622. cb.cross( ab );
  6623. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6624. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6625. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6626. }
  6627. }
  6628. this.normalizeNormals();
  6629. normalAttribute.needsUpdate = true;
  6630. }
  6631. }
  6632. normalizeNormals() {
  6633. const normals = this.attributes.normal;
  6634. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6635. _vector$8.fromBufferAttribute( normals, i );
  6636. _vector$8.normalize();
  6637. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6638. }
  6639. }
  6640. toNonIndexed() {
  6641. function convertBufferAttribute( attribute, indices ) {
  6642. const array = attribute.array;
  6643. const itemSize = attribute.itemSize;
  6644. const normalized = attribute.normalized;
  6645. const array2 = new array.constructor( indices.length * itemSize );
  6646. let index = 0, index2 = 0;
  6647. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6648. if ( attribute.isInterleavedBufferAttribute ) {
  6649. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6650. } else {
  6651. index = indices[ i ] * itemSize;
  6652. }
  6653. for ( let j = 0; j < itemSize; j ++ ) {
  6654. array2[ index2 ++ ] = array[ index ++ ];
  6655. }
  6656. }
  6657. return new BufferAttribute( array2, itemSize, normalized );
  6658. }
  6659. //
  6660. if ( this.index === null ) {
  6661. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6662. return this;
  6663. }
  6664. const geometry2 = new BufferGeometry();
  6665. const indices = this.index.array;
  6666. const attributes = this.attributes;
  6667. // attributes
  6668. for ( const name in attributes ) {
  6669. const attribute = attributes[ name ];
  6670. const newAttribute = convertBufferAttribute( attribute, indices );
  6671. geometry2.setAttribute( name, newAttribute );
  6672. }
  6673. // morph attributes
  6674. const morphAttributes = this.morphAttributes;
  6675. for ( const name in morphAttributes ) {
  6676. const morphArray = [];
  6677. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6678. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6679. const attribute = morphAttribute[ i ];
  6680. const newAttribute = convertBufferAttribute( attribute, indices );
  6681. morphArray.push( newAttribute );
  6682. }
  6683. geometry2.morphAttributes[ name ] = morphArray;
  6684. }
  6685. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6686. // groups
  6687. const groups = this.groups;
  6688. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6689. const group = groups[ i ];
  6690. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6691. }
  6692. return geometry2;
  6693. }
  6694. toJSON() {
  6695. const data = {
  6696. metadata: {
  6697. version: 4.6,
  6698. type: 'BufferGeometry',
  6699. generator: 'BufferGeometry.toJSON'
  6700. }
  6701. };
  6702. // standard BufferGeometry serialization
  6703. data.uuid = this.uuid;
  6704. data.type = this.type;
  6705. if ( this.name !== '' ) data.name = this.name;
  6706. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6707. if ( this.parameters !== undefined ) {
  6708. const parameters = this.parameters;
  6709. for ( const key in parameters ) {
  6710. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6711. }
  6712. return data;
  6713. }
  6714. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6715. data.data = { attributes: {} };
  6716. const index = this.index;
  6717. if ( index !== null ) {
  6718. data.data.index = {
  6719. type: index.array.constructor.name,
  6720. array: Array.prototype.slice.call( index.array )
  6721. };
  6722. }
  6723. const attributes = this.attributes;
  6724. for ( const key in attributes ) {
  6725. const attribute = attributes[ key ];
  6726. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6727. }
  6728. const morphAttributes = {};
  6729. let hasMorphAttributes = false;
  6730. for ( const key in this.morphAttributes ) {
  6731. const attributeArray = this.morphAttributes[ key ];
  6732. const array = [];
  6733. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6734. const attribute = attributeArray[ i ];
  6735. array.push( attribute.toJSON( data.data ) );
  6736. }
  6737. if ( array.length > 0 ) {
  6738. morphAttributes[ key ] = array;
  6739. hasMorphAttributes = true;
  6740. }
  6741. }
  6742. if ( hasMorphAttributes ) {
  6743. data.data.morphAttributes = morphAttributes;
  6744. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6745. }
  6746. const groups = this.groups;
  6747. if ( groups.length > 0 ) {
  6748. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6749. }
  6750. const boundingSphere = this.boundingSphere;
  6751. if ( boundingSphere !== null ) {
  6752. data.data.boundingSphere = {
  6753. center: boundingSphere.center.toArray(),
  6754. radius: boundingSphere.radius
  6755. };
  6756. }
  6757. return data;
  6758. }
  6759. clone() {
  6760. return new this.constructor().copy( this );
  6761. }
  6762. copy( source ) {
  6763. // reset
  6764. this.index = null;
  6765. this.attributes = {};
  6766. this.morphAttributes = {};
  6767. this.groups = [];
  6768. this.boundingBox = null;
  6769. this.boundingSphere = null;
  6770. // used for storing cloned, shared data
  6771. const data = {};
  6772. // name
  6773. this.name = source.name;
  6774. // index
  6775. const index = source.index;
  6776. if ( index !== null ) {
  6777. this.setIndex( index.clone( data ) );
  6778. }
  6779. // attributes
  6780. const attributes = source.attributes;
  6781. for ( const name in attributes ) {
  6782. const attribute = attributes[ name ];
  6783. this.setAttribute( name, attribute.clone( data ) );
  6784. }
  6785. // morph attributes
  6786. const morphAttributes = source.morphAttributes;
  6787. for ( const name in morphAttributes ) {
  6788. const array = [];
  6789. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6790. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6791. array.push( morphAttribute[ i ].clone( data ) );
  6792. }
  6793. this.morphAttributes[ name ] = array;
  6794. }
  6795. this.morphTargetsRelative = source.morphTargetsRelative;
  6796. // groups
  6797. const groups = source.groups;
  6798. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6799. const group = groups[ i ];
  6800. this.addGroup( group.start, group.count, group.materialIndex );
  6801. }
  6802. // bounding box
  6803. const boundingBox = source.boundingBox;
  6804. if ( boundingBox !== null ) {
  6805. this.boundingBox = boundingBox.clone();
  6806. }
  6807. // bounding sphere
  6808. const boundingSphere = source.boundingSphere;
  6809. if ( boundingSphere !== null ) {
  6810. this.boundingSphere = boundingSphere.clone();
  6811. }
  6812. // draw range
  6813. this.drawRange.start = source.drawRange.start;
  6814. this.drawRange.count = source.drawRange.count;
  6815. // user data
  6816. this.userData = source.userData;
  6817. return this;
  6818. }
  6819. dispose() {
  6820. this.dispatchEvent( { type: 'dispose' } );
  6821. }
  6822. }
  6823. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6824. const _ray$3 = /*@__PURE__*/ new Ray();
  6825. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6826. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6827. const _vA$1 = /*@__PURE__*/ new Vector3();
  6828. const _vB$1 = /*@__PURE__*/ new Vector3();
  6829. const _vC$1 = /*@__PURE__*/ new Vector3();
  6830. const _tempA = /*@__PURE__*/ new Vector3();
  6831. const _morphA = /*@__PURE__*/ new Vector3();
  6832. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6833. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6834. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6835. const _normalA = /*@__PURE__*/ new Vector3();
  6836. const _normalB = /*@__PURE__*/ new Vector3();
  6837. const _normalC = /*@__PURE__*/ new Vector3();
  6838. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6839. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6840. class Mesh extends Object3D {
  6841. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6842. super();
  6843. this.isMesh = true;
  6844. this.type = 'Mesh';
  6845. this.geometry = geometry;
  6846. this.material = material;
  6847. this.updateMorphTargets();
  6848. }
  6849. copy( source, recursive ) {
  6850. super.copy( source, recursive );
  6851. if ( source.morphTargetInfluences !== undefined ) {
  6852. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6853. }
  6854. if ( source.morphTargetDictionary !== undefined ) {
  6855. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6856. }
  6857. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6858. this.geometry = source.geometry;
  6859. return this;
  6860. }
  6861. updateMorphTargets() {
  6862. const geometry = this.geometry;
  6863. const morphAttributes = geometry.morphAttributes;
  6864. const keys = Object.keys( morphAttributes );
  6865. if ( keys.length > 0 ) {
  6866. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6867. if ( morphAttribute !== undefined ) {
  6868. this.morphTargetInfluences = [];
  6869. this.morphTargetDictionary = {};
  6870. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6871. const name = morphAttribute[ m ].name || String( m );
  6872. this.morphTargetInfluences.push( 0 );
  6873. this.morphTargetDictionary[ name ] = m;
  6874. }
  6875. }
  6876. }
  6877. }
  6878. getVertexPosition( index, target ) {
  6879. const geometry = this.geometry;
  6880. const position = geometry.attributes.position;
  6881. const morphPosition = geometry.morphAttributes.position;
  6882. const morphTargetsRelative = geometry.morphTargetsRelative;
  6883. target.fromBufferAttribute( position, index );
  6884. const morphInfluences = this.morphTargetInfluences;
  6885. if ( morphPosition && morphInfluences ) {
  6886. _morphA.set( 0, 0, 0 );
  6887. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6888. const influence = morphInfluences[ i ];
  6889. const morphAttribute = morphPosition[ i ];
  6890. if ( influence === 0 ) continue;
  6891. _tempA.fromBufferAttribute( morphAttribute, index );
  6892. if ( morphTargetsRelative ) {
  6893. _morphA.addScaledVector( _tempA, influence );
  6894. } else {
  6895. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6896. }
  6897. }
  6898. target.add( _morphA );
  6899. }
  6900. return target;
  6901. }
  6902. raycast( raycaster, intersects ) {
  6903. const geometry = this.geometry;
  6904. const material = this.material;
  6905. const matrixWorld = this.matrixWorld;
  6906. if ( material === undefined ) return;
  6907. // test with bounding sphere in world space
  6908. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6909. _sphere$6.copy( geometry.boundingSphere );
  6910. _sphere$6.applyMatrix4( matrixWorld );
  6911. // check distance from ray origin to bounding sphere
  6912. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6913. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6914. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6915. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6916. }
  6917. // convert ray to local space of mesh
  6918. _inverseMatrix$3.copy( matrixWorld ).invert();
  6919. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6920. // test with bounding box in local space
  6921. if ( geometry.boundingBox !== null ) {
  6922. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6923. }
  6924. // test for intersections with geometry
  6925. this._computeIntersections( raycaster, intersects, _ray$3 );
  6926. }
  6927. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6928. let intersection;
  6929. const geometry = this.geometry;
  6930. const material = this.material;
  6931. const index = geometry.index;
  6932. const position = geometry.attributes.position;
  6933. const uv = geometry.attributes.uv;
  6934. const uv1 = geometry.attributes.uv1;
  6935. const normal = geometry.attributes.normal;
  6936. const groups = geometry.groups;
  6937. const drawRange = geometry.drawRange;
  6938. if ( index !== null ) {
  6939. // indexed buffer geometry
  6940. if ( Array.isArray( material ) ) {
  6941. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6942. const group = groups[ i ];
  6943. const groupMaterial = material[ group.materialIndex ];
  6944. const start = Math.max( group.start, drawRange.start );
  6945. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6946. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6947. const a = index.getX( j );
  6948. const b = index.getX( j + 1 );
  6949. const c = index.getX( j + 2 );
  6950. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6951. if ( intersection ) {
  6952. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6953. intersection.face.materialIndex = group.materialIndex;
  6954. intersects.push( intersection );
  6955. }
  6956. }
  6957. }
  6958. } else {
  6959. const start = Math.max( 0, drawRange.start );
  6960. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6961. for ( let i = start, il = end; i < il; i += 3 ) {
  6962. const a = index.getX( i );
  6963. const b = index.getX( i + 1 );
  6964. const c = index.getX( i + 2 );
  6965. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6966. if ( intersection ) {
  6967. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6968. intersects.push( intersection );
  6969. }
  6970. }
  6971. }
  6972. } else if ( position !== undefined ) {
  6973. // non-indexed buffer geometry
  6974. if ( Array.isArray( material ) ) {
  6975. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6976. const group = groups[ i ];
  6977. const groupMaterial = material[ group.materialIndex ];
  6978. const start = Math.max( group.start, drawRange.start );
  6979. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6980. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6981. const a = j;
  6982. const b = j + 1;
  6983. const c = j + 2;
  6984. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6985. if ( intersection ) {
  6986. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6987. intersection.face.materialIndex = group.materialIndex;
  6988. intersects.push( intersection );
  6989. }
  6990. }
  6991. }
  6992. } else {
  6993. const start = Math.max( 0, drawRange.start );
  6994. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6995. for ( let i = start, il = end; i < il; i += 3 ) {
  6996. const a = i;
  6997. const b = i + 1;
  6998. const c = i + 2;
  6999. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7000. if ( intersection ) {
  7001. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7002. intersects.push( intersection );
  7003. }
  7004. }
  7005. }
  7006. }
  7007. }
  7008. }
  7009. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7010. let intersect;
  7011. if ( material.side === BackSide ) {
  7012. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7013. } else {
  7014. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7015. }
  7016. if ( intersect === null ) return null;
  7017. _intersectionPointWorld.copy( point );
  7018. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7019. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7020. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7021. return {
  7022. distance: distance,
  7023. point: _intersectionPointWorld.clone(),
  7024. object: object
  7025. };
  7026. }
  7027. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7028. object.getVertexPosition( a, _vA$1 );
  7029. object.getVertexPosition( b, _vB$1 );
  7030. object.getVertexPosition( c, _vC$1 );
  7031. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7032. if ( intersection ) {
  7033. if ( uv ) {
  7034. _uvA$1.fromBufferAttribute( uv, a );
  7035. _uvB$1.fromBufferAttribute( uv, b );
  7036. _uvC$1.fromBufferAttribute( uv, c );
  7037. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7038. }
  7039. if ( uv1 ) {
  7040. _uvA$1.fromBufferAttribute( uv1, a );
  7041. _uvB$1.fromBufferAttribute( uv1, b );
  7042. _uvC$1.fromBufferAttribute( uv1, c );
  7043. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7044. }
  7045. if ( normal ) {
  7046. _normalA.fromBufferAttribute( normal, a );
  7047. _normalB.fromBufferAttribute( normal, b );
  7048. _normalC.fromBufferAttribute( normal, c );
  7049. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7050. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7051. intersection.normal.multiplyScalar( - 1 );
  7052. }
  7053. }
  7054. const face = {
  7055. a: a,
  7056. b: b,
  7057. c: c,
  7058. normal: new Vector3(),
  7059. materialIndex: 0
  7060. };
  7061. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7062. intersection.face = face;
  7063. }
  7064. return intersection;
  7065. }
  7066. class BoxGeometry extends BufferGeometry {
  7067. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7068. super();
  7069. this.type = 'BoxGeometry';
  7070. this.parameters = {
  7071. width: width,
  7072. height: height,
  7073. depth: depth,
  7074. widthSegments: widthSegments,
  7075. heightSegments: heightSegments,
  7076. depthSegments: depthSegments
  7077. };
  7078. const scope = this;
  7079. // segments
  7080. widthSegments = Math.floor( widthSegments );
  7081. heightSegments = Math.floor( heightSegments );
  7082. depthSegments = Math.floor( depthSegments );
  7083. // buffers
  7084. const indices = [];
  7085. const vertices = [];
  7086. const normals = [];
  7087. const uvs = [];
  7088. // helper variables
  7089. let numberOfVertices = 0;
  7090. let groupStart = 0;
  7091. // build each side of the box geometry
  7092. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7093. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7094. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7095. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7096. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7097. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7098. // build geometry
  7099. this.setIndex( indices );
  7100. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7101. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7102. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7103. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7104. const segmentWidth = width / gridX;
  7105. const segmentHeight = height / gridY;
  7106. const widthHalf = width / 2;
  7107. const heightHalf = height / 2;
  7108. const depthHalf = depth / 2;
  7109. const gridX1 = gridX + 1;
  7110. const gridY1 = gridY + 1;
  7111. let vertexCounter = 0;
  7112. let groupCount = 0;
  7113. const vector = new Vector3();
  7114. // generate vertices, normals and uvs
  7115. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7116. const y = iy * segmentHeight - heightHalf;
  7117. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7118. const x = ix * segmentWidth - widthHalf;
  7119. // set values to correct vector component
  7120. vector[ u ] = x * udir;
  7121. vector[ v ] = y * vdir;
  7122. vector[ w ] = depthHalf;
  7123. // now apply vector to vertex buffer
  7124. vertices.push( vector.x, vector.y, vector.z );
  7125. // set values to correct vector component
  7126. vector[ u ] = 0;
  7127. vector[ v ] = 0;
  7128. vector[ w ] = depth > 0 ? 1 : - 1;
  7129. // now apply vector to normal buffer
  7130. normals.push( vector.x, vector.y, vector.z );
  7131. // uvs
  7132. uvs.push( ix / gridX );
  7133. uvs.push( 1 - ( iy / gridY ) );
  7134. // counters
  7135. vertexCounter += 1;
  7136. }
  7137. }
  7138. // indices
  7139. // 1. you need three indices to draw a single face
  7140. // 2. a single segment consists of two faces
  7141. // 3. so we need to generate six (2*3) indices per segment
  7142. for ( let iy = 0; iy < gridY; iy ++ ) {
  7143. for ( let ix = 0; ix < gridX; ix ++ ) {
  7144. const a = numberOfVertices + ix + gridX1 * iy;
  7145. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7146. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7147. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7148. // faces
  7149. indices.push( a, b, d );
  7150. indices.push( b, c, d );
  7151. // increase counter
  7152. groupCount += 6;
  7153. }
  7154. }
  7155. // add a group to the geometry. this will ensure multi material support
  7156. scope.addGroup( groupStart, groupCount, materialIndex );
  7157. // calculate new start value for groups
  7158. groupStart += groupCount;
  7159. // update total number of vertices
  7160. numberOfVertices += vertexCounter;
  7161. }
  7162. }
  7163. copy( source ) {
  7164. super.copy( source );
  7165. this.parameters = Object.assign( {}, source.parameters );
  7166. return this;
  7167. }
  7168. static fromJSON( data ) {
  7169. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7170. }
  7171. }
  7172. /**
  7173. * Uniform Utilities
  7174. */
  7175. function cloneUniforms( src ) {
  7176. const dst = {};
  7177. for ( const u in src ) {
  7178. dst[ u ] = {};
  7179. for ( const p in src[ u ] ) {
  7180. const property = src[ u ][ p ];
  7181. if ( property && ( property.isColor ||
  7182. property.isMatrix3 || property.isMatrix4 ||
  7183. property.isVector2 || property.isVector3 || property.isVector4 ||
  7184. property.isTexture || property.isQuaternion ) ) {
  7185. if ( property.isRenderTargetTexture ) {
  7186. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7187. dst[ u ][ p ] = null;
  7188. } else {
  7189. dst[ u ][ p ] = property.clone();
  7190. }
  7191. } else if ( Array.isArray( property ) ) {
  7192. dst[ u ][ p ] = property.slice();
  7193. } else {
  7194. dst[ u ][ p ] = property;
  7195. }
  7196. }
  7197. }
  7198. return dst;
  7199. }
  7200. function mergeUniforms( uniforms ) {
  7201. const merged = {};
  7202. for ( let u = 0; u < uniforms.length; u ++ ) {
  7203. const tmp = cloneUniforms( uniforms[ u ] );
  7204. for ( const p in tmp ) {
  7205. merged[ p ] = tmp[ p ];
  7206. }
  7207. }
  7208. return merged;
  7209. }
  7210. function cloneUniformsGroups( src ) {
  7211. const dst = [];
  7212. for ( let u = 0; u < src.length; u ++ ) {
  7213. dst.push( src[ u ].clone() );
  7214. }
  7215. return dst;
  7216. }
  7217. function getUnlitUniformColorSpace( renderer ) {
  7218. const currentRenderTarget = renderer.getRenderTarget();
  7219. if ( currentRenderTarget === null ) {
  7220. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7221. return renderer.outputColorSpace;
  7222. }
  7223. // https://github.com/mrdoob/three.js/issues/27868
  7224. if ( currentRenderTarget.isXRRenderTarget === true ) {
  7225. return currentRenderTarget.texture.colorSpace;
  7226. }
  7227. return ColorManagement.workingColorSpace;
  7228. }
  7229. // Legacy
  7230. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7231. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7232. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7233. class ShaderMaterial extends Material {
  7234. constructor( parameters ) {
  7235. super();
  7236. this.isShaderMaterial = true;
  7237. this.type = 'ShaderMaterial';
  7238. this.defines = {};
  7239. this.uniforms = {};
  7240. this.uniformsGroups = [];
  7241. this.vertexShader = default_vertex;
  7242. this.fragmentShader = default_fragment;
  7243. this.linewidth = 1;
  7244. this.wireframe = false;
  7245. this.wireframeLinewidth = 1;
  7246. this.fog = false; // set to use scene fog
  7247. this.lights = false; // set to use scene lights
  7248. this.clipping = false; // set to use user-defined clipping planes
  7249. this.forceSinglePass = true;
  7250. this.extensions = {
  7251. clipCullDistance: false, // set to use vertex shader clipping
  7252. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7253. };
  7254. // When rendered geometry doesn't include these attributes but the material does,
  7255. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7256. this.defaultAttributeValues = {
  7257. 'color': [ 1, 1, 1 ],
  7258. 'uv': [ 0, 0 ],
  7259. 'uv1': [ 0, 0 ]
  7260. };
  7261. this.index0AttributeName = undefined;
  7262. this.uniformsNeedUpdate = false;
  7263. this.glslVersion = null;
  7264. if ( parameters !== undefined ) {
  7265. this.setValues( parameters );
  7266. }
  7267. }
  7268. copy( source ) {
  7269. super.copy( source );
  7270. this.fragmentShader = source.fragmentShader;
  7271. this.vertexShader = source.vertexShader;
  7272. this.uniforms = cloneUniforms( source.uniforms );
  7273. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7274. this.defines = Object.assign( {}, source.defines );
  7275. this.wireframe = source.wireframe;
  7276. this.wireframeLinewidth = source.wireframeLinewidth;
  7277. this.fog = source.fog;
  7278. this.lights = source.lights;
  7279. this.clipping = source.clipping;
  7280. this.extensions = Object.assign( {}, source.extensions );
  7281. this.glslVersion = source.glslVersion;
  7282. return this;
  7283. }
  7284. toJSON( meta ) {
  7285. const data = super.toJSON( meta );
  7286. data.glslVersion = this.glslVersion;
  7287. data.uniforms = {};
  7288. for ( const name in this.uniforms ) {
  7289. const uniform = this.uniforms[ name ];
  7290. const value = uniform.value;
  7291. if ( value && value.isTexture ) {
  7292. data.uniforms[ name ] = {
  7293. type: 't',
  7294. value: value.toJSON( meta ).uuid
  7295. };
  7296. } else if ( value && value.isColor ) {
  7297. data.uniforms[ name ] = {
  7298. type: 'c',
  7299. value: value.getHex()
  7300. };
  7301. } else if ( value && value.isVector2 ) {
  7302. data.uniforms[ name ] = {
  7303. type: 'v2',
  7304. value: value.toArray()
  7305. };
  7306. } else if ( value && value.isVector3 ) {
  7307. data.uniforms[ name ] = {
  7308. type: 'v3',
  7309. value: value.toArray()
  7310. };
  7311. } else if ( value && value.isVector4 ) {
  7312. data.uniforms[ name ] = {
  7313. type: 'v4',
  7314. value: value.toArray()
  7315. };
  7316. } else if ( value && value.isMatrix3 ) {
  7317. data.uniforms[ name ] = {
  7318. type: 'm3',
  7319. value: value.toArray()
  7320. };
  7321. } else if ( value && value.isMatrix4 ) {
  7322. data.uniforms[ name ] = {
  7323. type: 'm4',
  7324. value: value.toArray()
  7325. };
  7326. } else {
  7327. data.uniforms[ name ] = {
  7328. value: value
  7329. };
  7330. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7331. }
  7332. }
  7333. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7334. data.vertexShader = this.vertexShader;
  7335. data.fragmentShader = this.fragmentShader;
  7336. data.lights = this.lights;
  7337. data.clipping = this.clipping;
  7338. const extensions = {};
  7339. for ( const key in this.extensions ) {
  7340. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7341. }
  7342. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7343. return data;
  7344. }
  7345. }
  7346. class Camera extends Object3D {
  7347. constructor() {
  7348. super();
  7349. this.isCamera = true;
  7350. this.type = 'Camera';
  7351. this.matrixWorldInverse = new Matrix4();
  7352. this.projectionMatrix = new Matrix4();
  7353. this.projectionMatrixInverse = new Matrix4();
  7354. this.coordinateSystem = WebGLCoordinateSystem;
  7355. }
  7356. copy( source, recursive ) {
  7357. super.copy( source, recursive );
  7358. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7359. this.projectionMatrix.copy( source.projectionMatrix );
  7360. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7361. this.coordinateSystem = source.coordinateSystem;
  7362. return this;
  7363. }
  7364. getWorldDirection( target ) {
  7365. return super.getWorldDirection( target ).negate();
  7366. }
  7367. updateMatrixWorld( force ) {
  7368. super.updateMatrixWorld( force );
  7369. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7370. }
  7371. updateWorldMatrix( updateParents, updateChildren ) {
  7372. super.updateWorldMatrix( updateParents, updateChildren );
  7373. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7374. }
  7375. clone() {
  7376. return new this.constructor().copy( this );
  7377. }
  7378. }
  7379. const _v3$1 = /*@__PURE__*/ new Vector3();
  7380. const _minTarget = /*@__PURE__*/ new Vector2();
  7381. const _maxTarget = /*@__PURE__*/ new Vector2();
  7382. class PerspectiveCamera extends Camera {
  7383. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7384. super();
  7385. this.isPerspectiveCamera = true;
  7386. this.type = 'PerspectiveCamera';
  7387. this.fov = fov;
  7388. this.zoom = 1;
  7389. this.near = near;
  7390. this.far = far;
  7391. this.focus = 10;
  7392. this.aspect = aspect;
  7393. this.view = null;
  7394. this.filmGauge = 35; // width of the film (default in millimeters)
  7395. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7396. this.updateProjectionMatrix();
  7397. }
  7398. copy( source, recursive ) {
  7399. super.copy( source, recursive );
  7400. this.fov = source.fov;
  7401. this.zoom = source.zoom;
  7402. this.near = source.near;
  7403. this.far = source.far;
  7404. this.focus = source.focus;
  7405. this.aspect = source.aspect;
  7406. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7407. this.filmGauge = source.filmGauge;
  7408. this.filmOffset = source.filmOffset;
  7409. return this;
  7410. }
  7411. /**
  7412. * Sets the FOV by focal length in respect to the current .filmGauge.
  7413. *
  7414. * The default film gauge is 35, so that the focal length can be specified for
  7415. * a 35mm (full frame) camera.
  7416. *
  7417. * Values for focal length and film gauge must have the same unit.
  7418. */
  7419. setFocalLength( focalLength ) {
  7420. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7421. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7422. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7423. this.updateProjectionMatrix();
  7424. }
  7425. /**
  7426. * Calculates the focal length from the current .fov and .filmGauge.
  7427. */
  7428. getFocalLength() {
  7429. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7430. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7431. }
  7432. getEffectiveFOV() {
  7433. return RAD2DEG * 2 * Math.atan(
  7434. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7435. }
  7436. getFilmWidth() {
  7437. // film not completely covered in portrait format (aspect < 1)
  7438. return this.filmGauge * Math.min( this.aspect, 1 );
  7439. }
  7440. getFilmHeight() {
  7441. // film not completely covered in landscape format (aspect > 1)
  7442. return this.filmGauge / Math.max( this.aspect, 1 );
  7443. }
  7444. /**
  7445. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7446. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7447. */
  7448. getViewBounds( distance, minTarget, maxTarget ) {
  7449. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7450. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7451. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7452. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7453. }
  7454. /**
  7455. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7456. * Copies the result into the target Vector2, where x is width and y is height.
  7457. */
  7458. getViewSize( distance, target ) {
  7459. this.getViewBounds( distance, _minTarget, _maxTarget );
  7460. return target.subVectors( _maxTarget, _minTarget );
  7461. }
  7462. /**
  7463. * Sets an offset in a larger frustum. This is useful for multi-window or
  7464. * multi-monitor/multi-machine setups.
  7465. *
  7466. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7467. * the monitors are in grid like this
  7468. *
  7469. * +---+---+---+
  7470. * | A | B | C |
  7471. * +---+---+---+
  7472. * | D | E | F |
  7473. * +---+---+---+
  7474. *
  7475. * then for each monitor you would call it like this
  7476. *
  7477. * const w = 1920;
  7478. * const h = 1080;
  7479. * const fullWidth = w * 3;
  7480. * const fullHeight = h * 2;
  7481. *
  7482. * --A--
  7483. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7484. * --B--
  7485. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7486. * --C--
  7487. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7488. * --D--
  7489. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7490. * --E--
  7491. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7492. * --F--
  7493. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7494. *
  7495. * Note there is no reason monitors have to be the same size or in a grid.
  7496. */
  7497. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7498. this.aspect = fullWidth / fullHeight;
  7499. if ( this.view === null ) {
  7500. this.view = {
  7501. enabled: true,
  7502. fullWidth: 1,
  7503. fullHeight: 1,
  7504. offsetX: 0,
  7505. offsetY: 0,
  7506. width: 1,
  7507. height: 1
  7508. };
  7509. }
  7510. this.view.enabled = true;
  7511. this.view.fullWidth = fullWidth;
  7512. this.view.fullHeight = fullHeight;
  7513. this.view.offsetX = x;
  7514. this.view.offsetY = y;
  7515. this.view.width = width;
  7516. this.view.height = height;
  7517. this.updateProjectionMatrix();
  7518. }
  7519. clearViewOffset() {
  7520. if ( this.view !== null ) {
  7521. this.view.enabled = false;
  7522. }
  7523. this.updateProjectionMatrix();
  7524. }
  7525. updateProjectionMatrix() {
  7526. const near = this.near;
  7527. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7528. let height = 2 * top;
  7529. let width = this.aspect * height;
  7530. let left = - 0.5 * width;
  7531. const view = this.view;
  7532. if ( this.view !== null && this.view.enabled ) {
  7533. const fullWidth = view.fullWidth,
  7534. fullHeight = view.fullHeight;
  7535. left += view.offsetX * width / fullWidth;
  7536. top -= view.offsetY * height / fullHeight;
  7537. width *= view.width / fullWidth;
  7538. height *= view.height / fullHeight;
  7539. }
  7540. const skew = this.filmOffset;
  7541. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7542. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7543. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7544. }
  7545. toJSON( meta ) {
  7546. const data = super.toJSON( meta );
  7547. data.object.fov = this.fov;
  7548. data.object.zoom = this.zoom;
  7549. data.object.near = this.near;
  7550. data.object.far = this.far;
  7551. data.object.focus = this.focus;
  7552. data.object.aspect = this.aspect;
  7553. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7554. data.object.filmGauge = this.filmGauge;
  7555. data.object.filmOffset = this.filmOffset;
  7556. return data;
  7557. }
  7558. }
  7559. const fov = - 90; // negative fov is not an error
  7560. const aspect = 1;
  7561. class CubeCamera extends Object3D {
  7562. constructor( near, far, renderTarget ) {
  7563. super();
  7564. this.type = 'CubeCamera';
  7565. this.renderTarget = renderTarget;
  7566. this.coordinateSystem = null;
  7567. this.activeMipmapLevel = 0;
  7568. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7569. cameraPX.layers = this.layers;
  7570. this.add( cameraPX );
  7571. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7572. cameraNX.layers = this.layers;
  7573. this.add( cameraNX );
  7574. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7575. cameraPY.layers = this.layers;
  7576. this.add( cameraPY );
  7577. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7578. cameraNY.layers = this.layers;
  7579. this.add( cameraNY );
  7580. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7581. cameraPZ.layers = this.layers;
  7582. this.add( cameraPZ );
  7583. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7584. cameraNZ.layers = this.layers;
  7585. this.add( cameraNZ );
  7586. }
  7587. updateCoordinateSystem() {
  7588. const coordinateSystem = this.coordinateSystem;
  7589. const cameras = this.children.concat();
  7590. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7591. for ( const camera of cameras ) this.remove( camera );
  7592. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7593. cameraPX.up.set( 0, 1, 0 );
  7594. cameraPX.lookAt( 1, 0, 0 );
  7595. cameraNX.up.set( 0, 1, 0 );
  7596. cameraNX.lookAt( - 1, 0, 0 );
  7597. cameraPY.up.set( 0, 0, - 1 );
  7598. cameraPY.lookAt( 0, 1, 0 );
  7599. cameraNY.up.set( 0, 0, 1 );
  7600. cameraNY.lookAt( 0, - 1, 0 );
  7601. cameraPZ.up.set( 0, 1, 0 );
  7602. cameraPZ.lookAt( 0, 0, 1 );
  7603. cameraNZ.up.set( 0, 1, 0 );
  7604. cameraNZ.lookAt( 0, 0, - 1 );
  7605. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7606. cameraPX.up.set( 0, - 1, 0 );
  7607. cameraPX.lookAt( - 1, 0, 0 );
  7608. cameraNX.up.set( 0, - 1, 0 );
  7609. cameraNX.lookAt( 1, 0, 0 );
  7610. cameraPY.up.set( 0, 0, 1 );
  7611. cameraPY.lookAt( 0, 1, 0 );
  7612. cameraNY.up.set( 0, 0, - 1 );
  7613. cameraNY.lookAt( 0, - 1, 0 );
  7614. cameraPZ.up.set( 0, - 1, 0 );
  7615. cameraPZ.lookAt( 0, 0, 1 );
  7616. cameraNZ.up.set( 0, - 1, 0 );
  7617. cameraNZ.lookAt( 0, 0, - 1 );
  7618. } else {
  7619. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7620. }
  7621. for ( const camera of cameras ) {
  7622. this.add( camera );
  7623. camera.updateMatrixWorld();
  7624. }
  7625. }
  7626. update( renderer, scene ) {
  7627. if ( this.parent === null ) this.updateMatrixWorld();
  7628. const { renderTarget, activeMipmapLevel } = this;
  7629. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7630. this.coordinateSystem = renderer.coordinateSystem;
  7631. this.updateCoordinateSystem();
  7632. }
  7633. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7634. const currentRenderTarget = renderer.getRenderTarget();
  7635. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7636. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7637. const currentXrEnabled = renderer.xr.enabled;
  7638. renderer.xr.enabled = false;
  7639. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7640. renderTarget.texture.generateMipmaps = false;
  7641. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7642. renderer.render( scene, cameraPX );
  7643. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7644. renderer.render( scene, cameraNX );
  7645. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7646. renderer.render( scene, cameraPY );
  7647. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7648. renderer.render( scene, cameraNY );
  7649. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7650. renderer.render( scene, cameraPZ );
  7651. // mipmaps are generated during the last call of render()
  7652. // at this point, all sides of the cube render target are defined
  7653. renderTarget.texture.generateMipmaps = generateMipmaps;
  7654. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7655. renderer.render( scene, cameraNZ );
  7656. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7657. renderer.xr.enabled = currentXrEnabled;
  7658. renderTarget.texture.needsPMREMUpdate = true;
  7659. }
  7660. }
  7661. class CubeTexture extends Texture {
  7662. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7663. images = images !== undefined ? images : [];
  7664. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7665. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7666. this.isCubeTexture = true;
  7667. this.flipY = false;
  7668. }
  7669. get images() {
  7670. return this.image;
  7671. }
  7672. set images( value ) {
  7673. this.image = value;
  7674. }
  7675. }
  7676. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7677. constructor( size = 1, options = {} ) {
  7678. super( size, size, options );
  7679. this.isWebGLCubeRenderTarget = true;
  7680. const image = { width: size, height: size, depth: 1 };
  7681. const images = [ image, image, image, image, image, image ];
  7682. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7683. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7684. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7685. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7686. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7687. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7688. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7689. this.texture.isRenderTargetTexture = true;
  7690. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7691. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7692. }
  7693. fromEquirectangularTexture( renderer, texture ) {
  7694. this.texture.type = texture.type;
  7695. this.texture.colorSpace = texture.colorSpace;
  7696. this.texture.generateMipmaps = texture.generateMipmaps;
  7697. this.texture.minFilter = texture.minFilter;
  7698. this.texture.magFilter = texture.magFilter;
  7699. const shader = {
  7700. uniforms: {
  7701. tEquirect: { value: null },
  7702. },
  7703. vertexShader: /* glsl */`
  7704. varying vec3 vWorldDirection;
  7705. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7706. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7707. }
  7708. void main() {
  7709. vWorldDirection = transformDirection( position, modelMatrix );
  7710. #include <begin_vertex>
  7711. #include <project_vertex>
  7712. }
  7713. `,
  7714. fragmentShader: /* glsl */`
  7715. uniform sampler2D tEquirect;
  7716. varying vec3 vWorldDirection;
  7717. #include <common>
  7718. void main() {
  7719. vec3 direction = normalize( vWorldDirection );
  7720. vec2 sampleUV = equirectUv( direction );
  7721. gl_FragColor = texture2D( tEquirect, sampleUV );
  7722. }
  7723. `
  7724. };
  7725. const geometry = new BoxGeometry( 5, 5, 5 );
  7726. const material = new ShaderMaterial( {
  7727. name: 'CubemapFromEquirect',
  7728. uniforms: cloneUniforms( shader.uniforms ),
  7729. vertexShader: shader.vertexShader,
  7730. fragmentShader: shader.fragmentShader,
  7731. side: BackSide,
  7732. blending: NoBlending
  7733. } );
  7734. material.uniforms.tEquirect.value = texture;
  7735. const mesh = new Mesh( geometry, material );
  7736. const currentMinFilter = texture.minFilter;
  7737. // Avoid blurred poles
  7738. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7739. const camera = new CubeCamera( 1, 10, this );
  7740. camera.update( renderer, mesh );
  7741. texture.minFilter = currentMinFilter;
  7742. mesh.geometry.dispose();
  7743. mesh.material.dispose();
  7744. return this;
  7745. }
  7746. clear( renderer, color, depth, stencil ) {
  7747. const currentRenderTarget = renderer.getRenderTarget();
  7748. for ( let i = 0; i < 6; i ++ ) {
  7749. renderer.setRenderTarget( this, i );
  7750. renderer.clear( color, depth, stencil );
  7751. }
  7752. renderer.setRenderTarget( currentRenderTarget );
  7753. }
  7754. }
  7755. const _vector1 = /*@__PURE__*/ new Vector3();
  7756. const _vector2 = /*@__PURE__*/ new Vector3();
  7757. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7758. class Plane {
  7759. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7760. this.isPlane = true;
  7761. // normal is assumed to be normalized
  7762. this.normal = normal;
  7763. this.constant = constant;
  7764. }
  7765. set( normal, constant ) {
  7766. this.normal.copy( normal );
  7767. this.constant = constant;
  7768. return this;
  7769. }
  7770. setComponents( x, y, z, w ) {
  7771. this.normal.set( x, y, z );
  7772. this.constant = w;
  7773. return this;
  7774. }
  7775. setFromNormalAndCoplanarPoint( normal, point ) {
  7776. this.normal.copy( normal );
  7777. this.constant = - point.dot( this.normal );
  7778. return this;
  7779. }
  7780. setFromCoplanarPoints( a, b, c ) {
  7781. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7782. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7783. this.setFromNormalAndCoplanarPoint( normal, a );
  7784. return this;
  7785. }
  7786. copy( plane ) {
  7787. this.normal.copy( plane.normal );
  7788. this.constant = plane.constant;
  7789. return this;
  7790. }
  7791. normalize() {
  7792. // Note: will lead to a divide by zero if the plane is invalid.
  7793. const inverseNormalLength = 1.0 / this.normal.length();
  7794. this.normal.multiplyScalar( inverseNormalLength );
  7795. this.constant *= inverseNormalLength;
  7796. return this;
  7797. }
  7798. negate() {
  7799. this.constant *= - 1;
  7800. this.normal.negate();
  7801. return this;
  7802. }
  7803. distanceToPoint( point ) {
  7804. return this.normal.dot( point ) + this.constant;
  7805. }
  7806. distanceToSphere( sphere ) {
  7807. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7808. }
  7809. projectPoint( point, target ) {
  7810. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7811. }
  7812. intersectLine( line, target ) {
  7813. const direction = line.delta( _vector1 );
  7814. const denominator = this.normal.dot( direction );
  7815. if ( denominator === 0 ) {
  7816. // line is coplanar, return origin
  7817. if ( this.distanceToPoint( line.start ) === 0 ) {
  7818. return target.copy( line.start );
  7819. }
  7820. // Unsure if this is the correct method to handle this case.
  7821. return null;
  7822. }
  7823. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7824. if ( t < 0 || t > 1 ) {
  7825. return null;
  7826. }
  7827. return target.copy( line.start ).addScaledVector( direction, t );
  7828. }
  7829. intersectsLine( line ) {
  7830. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7831. const startSign = this.distanceToPoint( line.start );
  7832. const endSign = this.distanceToPoint( line.end );
  7833. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7834. }
  7835. intersectsBox( box ) {
  7836. return box.intersectsPlane( this );
  7837. }
  7838. intersectsSphere( sphere ) {
  7839. return sphere.intersectsPlane( this );
  7840. }
  7841. coplanarPoint( target ) {
  7842. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7843. }
  7844. applyMatrix4( matrix, optionalNormalMatrix ) {
  7845. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7846. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7847. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7848. this.constant = - referencePoint.dot( normal );
  7849. return this;
  7850. }
  7851. translate( offset ) {
  7852. this.constant -= offset.dot( this.normal );
  7853. return this;
  7854. }
  7855. equals( plane ) {
  7856. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7857. }
  7858. clone() {
  7859. return new this.constructor().copy( this );
  7860. }
  7861. }
  7862. const _sphere$5 = /*@__PURE__*/ new Sphere();
  7863. const _vector$7 = /*@__PURE__*/ new Vector3();
  7864. class Frustum {
  7865. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7866. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7867. }
  7868. set( p0, p1, p2, p3, p4, p5 ) {
  7869. const planes = this.planes;
  7870. planes[ 0 ].copy( p0 );
  7871. planes[ 1 ].copy( p1 );
  7872. planes[ 2 ].copy( p2 );
  7873. planes[ 3 ].copy( p3 );
  7874. planes[ 4 ].copy( p4 );
  7875. planes[ 5 ].copy( p5 );
  7876. return this;
  7877. }
  7878. copy( frustum ) {
  7879. const planes = this.planes;
  7880. for ( let i = 0; i < 6; i ++ ) {
  7881. planes[ i ].copy( frustum.planes[ i ] );
  7882. }
  7883. return this;
  7884. }
  7885. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7886. const planes = this.planes;
  7887. const me = m.elements;
  7888. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7889. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7890. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7891. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7892. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7893. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7894. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7895. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7896. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7897. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7898. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7899. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7900. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7901. } else {
  7902. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7903. }
  7904. return this;
  7905. }
  7906. intersectsObject( object ) {
  7907. if ( object.boundingSphere !== undefined ) {
  7908. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7909. _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7910. } else {
  7911. const geometry = object.geometry;
  7912. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7913. _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7914. }
  7915. return this.intersectsSphere( _sphere$5 );
  7916. }
  7917. intersectsSprite( sprite ) {
  7918. _sphere$5.center.set( 0, 0, 0 );
  7919. _sphere$5.radius = 0.7071067811865476;
  7920. _sphere$5.applyMatrix4( sprite.matrixWorld );
  7921. return this.intersectsSphere( _sphere$5 );
  7922. }
  7923. intersectsSphere( sphere ) {
  7924. const planes = this.planes;
  7925. const center = sphere.center;
  7926. const negRadius = - sphere.radius;
  7927. for ( let i = 0; i < 6; i ++ ) {
  7928. const distance = planes[ i ].distanceToPoint( center );
  7929. if ( distance < negRadius ) {
  7930. return false;
  7931. }
  7932. }
  7933. return true;
  7934. }
  7935. intersectsBox( box ) {
  7936. const planes = this.planes;
  7937. for ( let i = 0; i < 6; i ++ ) {
  7938. const plane = planes[ i ];
  7939. // corner at max distance
  7940. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7941. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7942. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7943. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7944. return false;
  7945. }
  7946. }
  7947. return true;
  7948. }
  7949. containsPoint( point ) {
  7950. const planes = this.planes;
  7951. for ( let i = 0; i < 6; i ++ ) {
  7952. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7953. return false;
  7954. }
  7955. }
  7956. return true;
  7957. }
  7958. clone() {
  7959. return new this.constructor().copy( this );
  7960. }
  7961. }
  7962. function WebGLAnimation() {
  7963. let context = null;
  7964. let isAnimating = false;
  7965. let animationLoop = null;
  7966. let requestId = null;
  7967. function onAnimationFrame( time, frame ) {
  7968. animationLoop( time, frame );
  7969. requestId = context.requestAnimationFrame( onAnimationFrame );
  7970. }
  7971. return {
  7972. start: function () {
  7973. if ( isAnimating === true ) return;
  7974. if ( animationLoop === null ) return;
  7975. requestId = context.requestAnimationFrame( onAnimationFrame );
  7976. isAnimating = true;
  7977. },
  7978. stop: function () {
  7979. context.cancelAnimationFrame( requestId );
  7980. isAnimating = false;
  7981. },
  7982. setAnimationLoop: function ( callback ) {
  7983. animationLoop = callback;
  7984. },
  7985. setContext: function ( value ) {
  7986. context = value;
  7987. }
  7988. };
  7989. }
  7990. function WebGLAttributes( gl ) {
  7991. const buffers = new WeakMap();
  7992. function createBuffer( attribute, bufferType ) {
  7993. const array = attribute.array;
  7994. const usage = attribute.usage;
  7995. const size = array.byteLength;
  7996. const buffer = gl.createBuffer();
  7997. gl.bindBuffer( bufferType, buffer );
  7998. gl.bufferData( bufferType, array, usage );
  7999. attribute.onUploadCallback();
  8000. let type;
  8001. if ( array instanceof Float32Array ) {
  8002. type = gl.FLOAT;
  8003. } else if ( array instanceof Uint16Array ) {
  8004. if ( attribute.isFloat16BufferAttribute ) {
  8005. type = gl.HALF_FLOAT;
  8006. } else {
  8007. type = gl.UNSIGNED_SHORT;
  8008. }
  8009. } else if ( array instanceof Int16Array ) {
  8010. type = gl.SHORT;
  8011. } else if ( array instanceof Uint32Array ) {
  8012. type = gl.UNSIGNED_INT;
  8013. } else if ( array instanceof Int32Array ) {
  8014. type = gl.INT;
  8015. } else if ( array instanceof Int8Array ) {
  8016. type = gl.BYTE;
  8017. } else if ( array instanceof Uint8Array ) {
  8018. type = gl.UNSIGNED_BYTE;
  8019. } else if ( array instanceof Uint8ClampedArray ) {
  8020. type = gl.UNSIGNED_BYTE;
  8021. } else {
  8022. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  8023. }
  8024. return {
  8025. buffer: buffer,
  8026. type: type,
  8027. bytesPerElement: array.BYTES_PER_ELEMENT,
  8028. version: attribute.version,
  8029. size: size
  8030. };
  8031. }
  8032. function updateBuffer( buffer, attribute, bufferType ) {
  8033. const array = attribute.array;
  8034. const updateRange = attribute._updateRange; // @deprecated, r159
  8035. const updateRanges = attribute.updateRanges;
  8036. gl.bindBuffer( bufferType, buffer );
  8037. if ( updateRange.count === - 1 && updateRanges.length === 0 ) {
  8038. // Not using update ranges
  8039. gl.bufferSubData( bufferType, 0, array );
  8040. }
  8041. if ( updateRanges.length !== 0 ) {
  8042. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  8043. const range = updateRanges[ i ];
  8044. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8045. array, range.start, range.count );
  8046. }
  8047. attribute.clearUpdateRanges();
  8048. }
  8049. // @deprecated, r159
  8050. if ( updateRange.count !== - 1 ) {
  8051. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8052. array, updateRange.offset, updateRange.count );
  8053. updateRange.count = - 1; // reset range
  8054. }
  8055. attribute.onUploadCallback();
  8056. }
  8057. //
  8058. function get( attribute ) {
  8059. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8060. return buffers.get( attribute );
  8061. }
  8062. function remove( attribute ) {
  8063. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8064. const data = buffers.get( attribute );
  8065. if ( data ) {
  8066. gl.deleteBuffer( data.buffer );
  8067. buffers.delete( attribute );
  8068. }
  8069. }
  8070. function update( attribute, bufferType ) {
  8071. if ( attribute.isGLBufferAttribute ) {
  8072. const cached = buffers.get( attribute );
  8073. if ( ! cached || cached.version < attribute.version ) {
  8074. buffers.set( attribute, {
  8075. buffer: attribute.buffer,
  8076. type: attribute.type,
  8077. bytesPerElement: attribute.elementSize,
  8078. version: attribute.version
  8079. } );
  8080. }
  8081. return;
  8082. }
  8083. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8084. const data = buffers.get( attribute );
  8085. if ( data === undefined ) {
  8086. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8087. } else if ( data.version < attribute.version ) {
  8088. if ( data.size !== attribute.array.byteLength ) {
  8089. 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.' );
  8090. }
  8091. updateBuffer( data.buffer, attribute, bufferType );
  8092. data.version = attribute.version;
  8093. }
  8094. }
  8095. return {
  8096. get: get,
  8097. remove: remove,
  8098. update: update
  8099. };
  8100. }
  8101. class PlaneGeometry extends BufferGeometry {
  8102. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8103. super();
  8104. this.type = 'PlaneGeometry';
  8105. this.parameters = {
  8106. width: width,
  8107. height: height,
  8108. widthSegments: widthSegments,
  8109. heightSegments: heightSegments
  8110. };
  8111. const width_half = width / 2;
  8112. const height_half = height / 2;
  8113. const gridX = Math.floor( widthSegments );
  8114. const gridY = Math.floor( heightSegments );
  8115. const gridX1 = gridX + 1;
  8116. const gridY1 = gridY + 1;
  8117. const segment_width = width / gridX;
  8118. const segment_height = height / gridY;
  8119. //
  8120. const indices = [];
  8121. const vertices = [];
  8122. const normals = [];
  8123. const uvs = [];
  8124. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8125. const y = iy * segment_height - height_half;
  8126. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8127. const x = ix * segment_width - width_half;
  8128. vertices.push( x, - y, 0 );
  8129. normals.push( 0, 0, 1 );
  8130. uvs.push( ix / gridX );
  8131. uvs.push( 1 - ( iy / gridY ) );
  8132. }
  8133. }
  8134. for ( let iy = 0; iy < gridY; iy ++ ) {
  8135. for ( let ix = 0; ix < gridX; ix ++ ) {
  8136. const a = ix + gridX1 * iy;
  8137. const b = ix + gridX1 * ( iy + 1 );
  8138. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8139. const d = ( ix + 1 ) + gridX1 * iy;
  8140. indices.push( a, b, d );
  8141. indices.push( b, c, d );
  8142. }
  8143. }
  8144. this.setIndex( indices );
  8145. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8146. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8147. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8148. }
  8149. copy( source ) {
  8150. super.copy( source );
  8151. this.parameters = Object.assign( {}, source.parameters );
  8152. return this;
  8153. }
  8154. static fromJSON( data ) {
  8155. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8156. }
  8157. }
  8158. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8159. 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";
  8160. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8161. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8162. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  8163. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8164. 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";
  8165. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8166. 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";
  8167. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( batchId );\n#endif";
  8168. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8169. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8170. 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";
  8171. 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";
  8172. 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";
  8173. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  8174. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8175. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8176. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8177. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8178. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8179. 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";
  8180. 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";
  8181. 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";
  8182. 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";
  8183. 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";
  8184. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8185. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8186. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8187. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8188. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8189. 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}";
  8190. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  8191. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  8192. 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";
  8193. 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";
  8194. 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";
  8195. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8196. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8197. 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";
  8198. 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";
  8199. 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}";
  8200. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8201. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8202. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8203. 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";
  8204. 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";
  8205. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  8206. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8207. 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";
  8208. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8209. 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";
  8210. 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";
  8211. 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}";
  8212. 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";
  8213. 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";
  8214. 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";
  8215. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8216. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8217. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8218. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  8219. 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";
  8220. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8221. 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";
  8222. 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";
  8223. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8224. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8225. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[MORPHTARGETS_COUNT];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  8226. 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";
  8227. 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";
  8228. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\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";
  8229. 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";
  8230. 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;";
  8231. 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";
  8232. 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";
  8233. 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";
  8234. 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";
  8235. 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";
  8236. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8237. 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";
  8238. 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";
  8239. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8240. 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 );";
  8241. 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}";
  8242. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8243. 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;";
  8244. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8245. 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";
  8246. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8247. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8248. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n#endif";
  8249. 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";
  8250. 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";
  8251. 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}";
  8252. 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";
  8253. 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";
  8254. 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";
  8255. 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";
  8256. 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";
  8257. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8258. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8259. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tfloat startCompression = 0.8 - 0.04;\n\tfloat desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min(color.r, min(color.g, color.b));\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max(color.r, max(color.g, color.b));\n\tif (peak < startCompression) return color;\n\tfloat d = 1. - startCompression;\n\tfloat newPeak = 1. - d * d / (peak + d - startCompression);\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);\n\treturn mix(color, newPeak * vec3(1, 1, 1), g);\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8260. 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";
  8261. 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";
  8262. 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";
  8263. 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";
  8264. 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";
  8265. 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";
  8266. 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}";
  8267. 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}";
  8268. 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}";
  8269. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8270. 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}";
  8271. 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}";
  8272. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8273. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8274. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  8275. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8276. 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}";
  8277. 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}";
  8278. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8279. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8280. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8281. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8282. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8283. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8284. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8285. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8286. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8287. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8288. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8289. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8290. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8291. 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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8292. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8293. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8294. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8295. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8296. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8297. 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}";
  8298. 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}";
  8299. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8300. const ShaderChunk = {
  8301. alphahash_fragment: alphahash_fragment,
  8302. alphahash_pars_fragment: alphahash_pars_fragment,
  8303. alphamap_fragment: alphamap_fragment,
  8304. alphamap_pars_fragment: alphamap_pars_fragment,
  8305. alphatest_fragment: alphatest_fragment,
  8306. alphatest_pars_fragment: alphatest_pars_fragment,
  8307. aomap_fragment: aomap_fragment,
  8308. aomap_pars_fragment: aomap_pars_fragment,
  8309. batching_pars_vertex: batching_pars_vertex,
  8310. batching_vertex: batching_vertex,
  8311. begin_vertex: begin_vertex,
  8312. beginnormal_vertex: beginnormal_vertex,
  8313. bsdfs: bsdfs,
  8314. iridescence_fragment: iridescence_fragment,
  8315. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8316. clipping_planes_fragment: clipping_planes_fragment,
  8317. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8318. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8319. clipping_planes_vertex: clipping_planes_vertex,
  8320. color_fragment: color_fragment,
  8321. color_pars_fragment: color_pars_fragment,
  8322. color_pars_vertex: color_pars_vertex,
  8323. color_vertex: color_vertex,
  8324. common: common,
  8325. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8326. defaultnormal_vertex: defaultnormal_vertex,
  8327. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8328. displacementmap_vertex: displacementmap_vertex,
  8329. emissivemap_fragment: emissivemap_fragment,
  8330. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8331. colorspace_fragment: colorspace_fragment,
  8332. colorspace_pars_fragment: colorspace_pars_fragment,
  8333. envmap_fragment: envmap_fragment,
  8334. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8335. envmap_pars_fragment: envmap_pars_fragment,
  8336. envmap_pars_vertex: envmap_pars_vertex,
  8337. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8338. envmap_vertex: envmap_vertex,
  8339. fog_vertex: fog_vertex,
  8340. fog_pars_vertex: fog_pars_vertex,
  8341. fog_fragment: fog_fragment,
  8342. fog_pars_fragment: fog_pars_fragment,
  8343. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8344. lightmap_fragment: lightmap_fragment,
  8345. lightmap_pars_fragment: lightmap_pars_fragment,
  8346. lights_lambert_fragment: lights_lambert_fragment,
  8347. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8348. lights_pars_begin: lights_pars_begin,
  8349. lights_toon_fragment: lights_toon_fragment,
  8350. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8351. lights_phong_fragment: lights_phong_fragment,
  8352. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8353. lights_physical_fragment: lights_physical_fragment,
  8354. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8355. lights_fragment_begin: lights_fragment_begin,
  8356. lights_fragment_maps: lights_fragment_maps,
  8357. lights_fragment_end: lights_fragment_end,
  8358. logdepthbuf_fragment: logdepthbuf_fragment,
  8359. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8360. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8361. logdepthbuf_vertex: logdepthbuf_vertex,
  8362. map_fragment: map_fragment,
  8363. map_pars_fragment: map_pars_fragment,
  8364. map_particle_fragment: map_particle_fragment,
  8365. map_particle_pars_fragment: map_particle_pars_fragment,
  8366. metalnessmap_fragment: metalnessmap_fragment,
  8367. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8368. morphinstance_vertex: morphinstance_vertex,
  8369. morphcolor_vertex: morphcolor_vertex,
  8370. morphnormal_vertex: morphnormal_vertex,
  8371. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8372. morphtarget_vertex: morphtarget_vertex,
  8373. normal_fragment_begin: normal_fragment_begin,
  8374. normal_fragment_maps: normal_fragment_maps,
  8375. normal_pars_fragment: normal_pars_fragment,
  8376. normal_pars_vertex: normal_pars_vertex,
  8377. normal_vertex: normal_vertex,
  8378. normalmap_pars_fragment: normalmap_pars_fragment,
  8379. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8380. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8381. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8382. iridescence_pars_fragment: iridescence_pars_fragment,
  8383. opaque_fragment: opaque_fragment,
  8384. packing: packing,
  8385. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8386. project_vertex: project_vertex,
  8387. dithering_fragment: dithering_fragment,
  8388. dithering_pars_fragment: dithering_pars_fragment,
  8389. roughnessmap_fragment: roughnessmap_fragment,
  8390. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8391. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8392. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8393. shadowmap_vertex: shadowmap_vertex,
  8394. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8395. skinbase_vertex: skinbase_vertex,
  8396. skinning_pars_vertex: skinning_pars_vertex,
  8397. skinning_vertex: skinning_vertex,
  8398. skinnormal_vertex: skinnormal_vertex,
  8399. specularmap_fragment: specularmap_fragment,
  8400. specularmap_pars_fragment: specularmap_pars_fragment,
  8401. tonemapping_fragment: tonemapping_fragment,
  8402. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8403. transmission_fragment: transmission_fragment,
  8404. transmission_pars_fragment: transmission_pars_fragment,
  8405. uv_pars_fragment: uv_pars_fragment,
  8406. uv_pars_vertex: uv_pars_vertex,
  8407. uv_vertex: uv_vertex,
  8408. worldpos_vertex: worldpos_vertex,
  8409. background_vert: vertex$h,
  8410. background_frag: fragment$h,
  8411. backgroundCube_vert: vertex$g,
  8412. backgroundCube_frag: fragment$g,
  8413. cube_vert: vertex$f,
  8414. cube_frag: fragment$f,
  8415. depth_vert: vertex$e,
  8416. depth_frag: fragment$e,
  8417. distanceRGBA_vert: vertex$d,
  8418. distanceRGBA_frag: fragment$d,
  8419. equirect_vert: vertex$c,
  8420. equirect_frag: fragment$c,
  8421. linedashed_vert: vertex$b,
  8422. linedashed_frag: fragment$b,
  8423. meshbasic_vert: vertex$a,
  8424. meshbasic_frag: fragment$a,
  8425. meshlambert_vert: vertex$9,
  8426. meshlambert_frag: fragment$9,
  8427. meshmatcap_vert: vertex$8,
  8428. meshmatcap_frag: fragment$8,
  8429. meshnormal_vert: vertex$7,
  8430. meshnormal_frag: fragment$7,
  8431. meshphong_vert: vertex$6,
  8432. meshphong_frag: fragment$6,
  8433. meshphysical_vert: vertex$5,
  8434. meshphysical_frag: fragment$5,
  8435. meshtoon_vert: vertex$4,
  8436. meshtoon_frag: fragment$4,
  8437. points_vert: vertex$3,
  8438. points_frag: fragment$3,
  8439. shadow_vert: vertex$2,
  8440. shadow_frag: fragment$2,
  8441. sprite_vert: vertex$1,
  8442. sprite_frag: fragment$1
  8443. };
  8444. /**
  8445. * Uniforms library for shared webgl shaders
  8446. */
  8447. const UniformsLib = {
  8448. common: {
  8449. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8450. opacity: { value: 1.0 },
  8451. map: { value: null },
  8452. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8453. alphaMap: { value: null },
  8454. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8455. alphaTest: { value: 0 }
  8456. },
  8457. specularmap: {
  8458. specularMap: { value: null },
  8459. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8460. },
  8461. envmap: {
  8462. envMap: { value: null },
  8463. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  8464. flipEnvMap: { value: - 1 },
  8465. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8466. ior: { value: 1.5 }, // physical
  8467. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8468. },
  8469. aomap: {
  8470. aoMap: { value: null },
  8471. aoMapIntensity: { value: 1 },
  8472. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8473. },
  8474. lightmap: {
  8475. lightMap: { value: null },
  8476. lightMapIntensity: { value: 1 },
  8477. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8478. },
  8479. bumpmap: {
  8480. bumpMap: { value: null },
  8481. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8482. bumpScale: { value: 1 }
  8483. },
  8484. normalmap: {
  8485. normalMap: { value: null },
  8486. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8487. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8488. },
  8489. displacementmap: {
  8490. displacementMap: { value: null },
  8491. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8492. displacementScale: { value: 1 },
  8493. displacementBias: { value: 0 }
  8494. },
  8495. emissivemap: {
  8496. emissiveMap: { value: null },
  8497. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8498. },
  8499. metalnessmap: {
  8500. metalnessMap: { value: null },
  8501. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8502. },
  8503. roughnessmap: {
  8504. roughnessMap: { value: null },
  8505. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8506. },
  8507. gradientmap: {
  8508. gradientMap: { value: null }
  8509. },
  8510. fog: {
  8511. fogDensity: { value: 0.00025 },
  8512. fogNear: { value: 1 },
  8513. fogFar: { value: 2000 },
  8514. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8515. },
  8516. lights: {
  8517. ambientLightColor: { value: [] },
  8518. lightProbe: { value: [] },
  8519. directionalLights: { value: [], properties: {
  8520. direction: {},
  8521. color: {}
  8522. } },
  8523. directionalLightShadows: { value: [], properties: {
  8524. shadowBias: {},
  8525. shadowNormalBias: {},
  8526. shadowRadius: {},
  8527. shadowMapSize: {}
  8528. } },
  8529. directionalShadowMap: { value: [] },
  8530. directionalShadowMatrix: { value: [] },
  8531. spotLights: { value: [], properties: {
  8532. color: {},
  8533. position: {},
  8534. direction: {},
  8535. distance: {},
  8536. coneCos: {},
  8537. penumbraCos: {},
  8538. decay: {}
  8539. } },
  8540. spotLightShadows: { value: [], properties: {
  8541. shadowBias: {},
  8542. shadowNormalBias: {},
  8543. shadowRadius: {},
  8544. shadowMapSize: {}
  8545. } },
  8546. spotLightMap: { value: [] },
  8547. spotShadowMap: { value: [] },
  8548. spotLightMatrix: { value: [] },
  8549. pointLights: { value: [], properties: {
  8550. color: {},
  8551. position: {},
  8552. decay: {},
  8553. distance: {}
  8554. } },
  8555. pointLightShadows: { value: [], properties: {
  8556. shadowBias: {},
  8557. shadowNormalBias: {},
  8558. shadowRadius: {},
  8559. shadowMapSize: {},
  8560. shadowCameraNear: {},
  8561. shadowCameraFar: {}
  8562. } },
  8563. pointShadowMap: { value: [] },
  8564. pointShadowMatrix: { value: [] },
  8565. hemisphereLights: { value: [], properties: {
  8566. direction: {},
  8567. skyColor: {},
  8568. groundColor: {}
  8569. } },
  8570. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8571. rectAreaLights: { value: [], properties: {
  8572. color: {},
  8573. position: {},
  8574. width: {},
  8575. height: {}
  8576. } },
  8577. ltc_1: { value: null },
  8578. ltc_2: { value: null }
  8579. },
  8580. points: {
  8581. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8582. opacity: { value: 1.0 },
  8583. size: { value: 1.0 },
  8584. scale: { value: 1.0 },
  8585. map: { value: null },
  8586. alphaMap: { value: null },
  8587. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8588. alphaTest: { value: 0 },
  8589. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8590. },
  8591. sprite: {
  8592. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8593. opacity: { value: 1.0 },
  8594. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8595. rotation: { value: 0.0 },
  8596. map: { value: null },
  8597. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8598. alphaMap: { value: null },
  8599. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8600. alphaTest: { value: 0 }
  8601. }
  8602. };
  8603. const ShaderLib = {
  8604. basic: {
  8605. uniforms: /*@__PURE__*/ mergeUniforms( [
  8606. UniformsLib.common,
  8607. UniformsLib.specularmap,
  8608. UniformsLib.envmap,
  8609. UniformsLib.aomap,
  8610. UniformsLib.lightmap,
  8611. UniformsLib.fog
  8612. ] ),
  8613. vertexShader: ShaderChunk.meshbasic_vert,
  8614. fragmentShader: ShaderChunk.meshbasic_frag
  8615. },
  8616. lambert: {
  8617. uniforms: /*@__PURE__*/ mergeUniforms( [
  8618. UniformsLib.common,
  8619. UniformsLib.specularmap,
  8620. UniformsLib.envmap,
  8621. UniformsLib.aomap,
  8622. UniformsLib.lightmap,
  8623. UniformsLib.emissivemap,
  8624. UniformsLib.bumpmap,
  8625. UniformsLib.normalmap,
  8626. UniformsLib.displacementmap,
  8627. UniformsLib.fog,
  8628. UniformsLib.lights,
  8629. {
  8630. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8631. }
  8632. ] ),
  8633. vertexShader: ShaderChunk.meshlambert_vert,
  8634. fragmentShader: ShaderChunk.meshlambert_frag
  8635. },
  8636. phong: {
  8637. uniforms: /*@__PURE__*/ mergeUniforms( [
  8638. UniformsLib.common,
  8639. UniformsLib.specularmap,
  8640. UniformsLib.envmap,
  8641. UniformsLib.aomap,
  8642. UniformsLib.lightmap,
  8643. UniformsLib.emissivemap,
  8644. UniformsLib.bumpmap,
  8645. UniformsLib.normalmap,
  8646. UniformsLib.displacementmap,
  8647. UniformsLib.fog,
  8648. UniformsLib.lights,
  8649. {
  8650. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8651. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8652. shininess: { value: 30 }
  8653. }
  8654. ] ),
  8655. vertexShader: ShaderChunk.meshphong_vert,
  8656. fragmentShader: ShaderChunk.meshphong_frag
  8657. },
  8658. standard: {
  8659. uniforms: /*@__PURE__*/ mergeUniforms( [
  8660. UniformsLib.common,
  8661. UniformsLib.envmap,
  8662. UniformsLib.aomap,
  8663. UniformsLib.lightmap,
  8664. UniformsLib.emissivemap,
  8665. UniformsLib.bumpmap,
  8666. UniformsLib.normalmap,
  8667. UniformsLib.displacementmap,
  8668. UniformsLib.roughnessmap,
  8669. UniformsLib.metalnessmap,
  8670. UniformsLib.fog,
  8671. UniformsLib.lights,
  8672. {
  8673. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8674. roughness: { value: 1.0 },
  8675. metalness: { value: 0.0 },
  8676. envMapIntensity: { value: 1 }
  8677. }
  8678. ] ),
  8679. vertexShader: ShaderChunk.meshphysical_vert,
  8680. fragmentShader: ShaderChunk.meshphysical_frag
  8681. },
  8682. toon: {
  8683. uniforms: /*@__PURE__*/ mergeUniforms( [
  8684. UniformsLib.common,
  8685. UniformsLib.aomap,
  8686. UniformsLib.lightmap,
  8687. UniformsLib.emissivemap,
  8688. UniformsLib.bumpmap,
  8689. UniformsLib.normalmap,
  8690. UniformsLib.displacementmap,
  8691. UniformsLib.gradientmap,
  8692. UniformsLib.fog,
  8693. UniformsLib.lights,
  8694. {
  8695. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8696. }
  8697. ] ),
  8698. vertexShader: ShaderChunk.meshtoon_vert,
  8699. fragmentShader: ShaderChunk.meshtoon_frag
  8700. },
  8701. matcap: {
  8702. uniforms: /*@__PURE__*/ mergeUniforms( [
  8703. UniformsLib.common,
  8704. UniformsLib.bumpmap,
  8705. UniformsLib.normalmap,
  8706. UniformsLib.displacementmap,
  8707. UniformsLib.fog,
  8708. {
  8709. matcap: { value: null }
  8710. }
  8711. ] ),
  8712. vertexShader: ShaderChunk.meshmatcap_vert,
  8713. fragmentShader: ShaderChunk.meshmatcap_frag
  8714. },
  8715. points: {
  8716. uniforms: /*@__PURE__*/ mergeUniforms( [
  8717. UniformsLib.points,
  8718. UniformsLib.fog
  8719. ] ),
  8720. vertexShader: ShaderChunk.points_vert,
  8721. fragmentShader: ShaderChunk.points_frag
  8722. },
  8723. dashed: {
  8724. uniforms: /*@__PURE__*/ mergeUniforms( [
  8725. UniformsLib.common,
  8726. UniformsLib.fog,
  8727. {
  8728. scale: { value: 1 },
  8729. dashSize: { value: 1 },
  8730. totalSize: { value: 2 }
  8731. }
  8732. ] ),
  8733. vertexShader: ShaderChunk.linedashed_vert,
  8734. fragmentShader: ShaderChunk.linedashed_frag
  8735. },
  8736. depth: {
  8737. uniforms: /*@__PURE__*/ mergeUniforms( [
  8738. UniformsLib.common,
  8739. UniformsLib.displacementmap
  8740. ] ),
  8741. vertexShader: ShaderChunk.depth_vert,
  8742. fragmentShader: ShaderChunk.depth_frag
  8743. },
  8744. normal: {
  8745. uniforms: /*@__PURE__*/ mergeUniforms( [
  8746. UniformsLib.common,
  8747. UniformsLib.bumpmap,
  8748. UniformsLib.normalmap,
  8749. UniformsLib.displacementmap,
  8750. {
  8751. opacity: { value: 1.0 }
  8752. }
  8753. ] ),
  8754. vertexShader: ShaderChunk.meshnormal_vert,
  8755. fragmentShader: ShaderChunk.meshnormal_frag
  8756. },
  8757. sprite: {
  8758. uniforms: /*@__PURE__*/ mergeUniforms( [
  8759. UniformsLib.sprite,
  8760. UniformsLib.fog
  8761. ] ),
  8762. vertexShader: ShaderChunk.sprite_vert,
  8763. fragmentShader: ShaderChunk.sprite_frag
  8764. },
  8765. background: {
  8766. uniforms: {
  8767. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8768. t2D: { value: null },
  8769. backgroundIntensity: { value: 1 }
  8770. },
  8771. vertexShader: ShaderChunk.background_vert,
  8772. fragmentShader: ShaderChunk.background_frag
  8773. },
  8774. backgroundCube: {
  8775. uniforms: {
  8776. envMap: { value: null },
  8777. flipEnvMap: { value: - 1 },
  8778. backgroundBlurriness: { value: 0 },
  8779. backgroundIntensity: { value: 1 },
  8780. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  8781. },
  8782. vertexShader: ShaderChunk.backgroundCube_vert,
  8783. fragmentShader: ShaderChunk.backgroundCube_frag
  8784. },
  8785. cube: {
  8786. uniforms: {
  8787. tCube: { value: null },
  8788. tFlip: { value: - 1 },
  8789. opacity: { value: 1.0 }
  8790. },
  8791. vertexShader: ShaderChunk.cube_vert,
  8792. fragmentShader: ShaderChunk.cube_frag
  8793. },
  8794. equirect: {
  8795. uniforms: {
  8796. tEquirect: { value: null },
  8797. },
  8798. vertexShader: ShaderChunk.equirect_vert,
  8799. fragmentShader: ShaderChunk.equirect_frag
  8800. },
  8801. distanceRGBA: {
  8802. uniforms: /*@__PURE__*/ mergeUniforms( [
  8803. UniformsLib.common,
  8804. UniformsLib.displacementmap,
  8805. {
  8806. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8807. nearDistance: { value: 1 },
  8808. farDistance: { value: 1000 }
  8809. }
  8810. ] ),
  8811. vertexShader: ShaderChunk.distanceRGBA_vert,
  8812. fragmentShader: ShaderChunk.distanceRGBA_frag
  8813. },
  8814. shadow: {
  8815. uniforms: /*@__PURE__*/ mergeUniforms( [
  8816. UniformsLib.lights,
  8817. UniformsLib.fog,
  8818. {
  8819. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8820. opacity: { value: 1.0 }
  8821. },
  8822. ] ),
  8823. vertexShader: ShaderChunk.shadow_vert,
  8824. fragmentShader: ShaderChunk.shadow_frag
  8825. }
  8826. };
  8827. ShaderLib.physical = {
  8828. uniforms: /*@__PURE__*/ mergeUniforms( [
  8829. ShaderLib.standard.uniforms,
  8830. {
  8831. clearcoat: { value: 0 },
  8832. clearcoatMap: { value: null },
  8833. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8834. clearcoatNormalMap: { value: null },
  8835. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8836. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8837. clearcoatRoughness: { value: 0 },
  8838. clearcoatRoughnessMap: { value: null },
  8839. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8840. iridescence: { value: 0 },
  8841. iridescenceMap: { value: null },
  8842. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8843. iridescenceIOR: { value: 1.3 },
  8844. iridescenceThicknessMinimum: { value: 100 },
  8845. iridescenceThicknessMaximum: { value: 400 },
  8846. iridescenceThicknessMap: { value: null },
  8847. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8848. sheen: { value: 0 },
  8849. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8850. sheenColorMap: { value: null },
  8851. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8852. sheenRoughness: { value: 1 },
  8853. sheenRoughnessMap: { value: null },
  8854. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8855. transmission: { value: 0 },
  8856. transmissionMap: { value: null },
  8857. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8858. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8859. transmissionSamplerMap: { value: null },
  8860. thickness: { value: 0 },
  8861. thicknessMap: { value: null },
  8862. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8863. attenuationDistance: { value: 0 },
  8864. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8865. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8866. specularColorMap: { value: null },
  8867. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8868. specularIntensity: { value: 1 },
  8869. specularIntensityMap: { value: null },
  8870. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8871. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8872. anisotropyMap: { value: null },
  8873. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8874. }
  8875. ] ),
  8876. vertexShader: ShaderChunk.meshphysical_vert,
  8877. fragmentShader: ShaderChunk.meshphysical_frag
  8878. };
  8879. const _rgb = { r: 0, b: 0, g: 0 };
  8880. const _e1$1 = /*@__PURE__*/ new Euler();
  8881. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8882. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8883. const clearColor = new Color( 0x000000 );
  8884. let clearAlpha = alpha === true ? 0 : 1;
  8885. let planeMesh;
  8886. let boxMesh;
  8887. let currentBackground = null;
  8888. let currentBackgroundVersion = 0;
  8889. let currentTonemapping = null;
  8890. function render( renderList, scene ) {
  8891. let forceClear = false;
  8892. let background = scene.isScene === true ? scene.background : null;
  8893. if ( background && background.isTexture ) {
  8894. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8895. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8896. }
  8897. if ( background === null ) {
  8898. setClear( clearColor, clearAlpha );
  8899. } else if ( background && background.isColor ) {
  8900. setClear( background, 1 );
  8901. forceClear = true;
  8902. }
  8903. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8904. if ( environmentBlendMode === 'additive' ) {
  8905. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8906. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8907. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8908. }
  8909. if ( renderer.autoClear || forceClear ) {
  8910. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8911. }
  8912. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8913. if ( boxMesh === undefined ) {
  8914. boxMesh = new Mesh(
  8915. new BoxGeometry( 1, 1, 1 ),
  8916. new ShaderMaterial( {
  8917. name: 'BackgroundCubeMaterial',
  8918. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8919. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8920. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8921. side: BackSide,
  8922. depthTest: false,
  8923. depthWrite: false,
  8924. fog: false
  8925. } )
  8926. );
  8927. boxMesh.geometry.deleteAttribute( 'normal' );
  8928. boxMesh.geometry.deleteAttribute( 'uv' );
  8929. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8930. this.matrixWorld.copyPosition( camera.matrixWorld );
  8931. };
  8932. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8933. Object.defineProperty( boxMesh.material, 'envMap', {
  8934. get: function () {
  8935. return this.uniforms.envMap.value;
  8936. }
  8937. } );
  8938. objects.update( boxMesh );
  8939. }
  8940. _e1$1.copy( scene.backgroundRotation );
  8941. // accommodate left-handed frame
  8942. _e1$1.x *= - 1; _e1$1.y *= - 1; _e1$1.z *= - 1;
  8943. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  8944. // environment maps which are not cube render targets or PMREMs follow a different convention
  8945. _e1$1.y *= - 1;
  8946. _e1$1.z *= - 1;
  8947. }
  8948. boxMesh.material.uniforms.envMap.value = background;
  8949. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8950. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8951. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8952. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  8953. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8954. if ( currentBackground !== background ||
  8955. currentBackgroundVersion !== background.version ||
  8956. currentTonemapping !== renderer.toneMapping ) {
  8957. boxMesh.material.needsUpdate = true;
  8958. currentBackground = background;
  8959. currentBackgroundVersion = background.version;
  8960. currentTonemapping = renderer.toneMapping;
  8961. }
  8962. boxMesh.layers.enableAll();
  8963. // push to the pre-sorted opaque render list
  8964. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8965. } else if ( background && background.isTexture ) {
  8966. if ( planeMesh === undefined ) {
  8967. planeMesh = new Mesh(
  8968. new PlaneGeometry( 2, 2 ),
  8969. new ShaderMaterial( {
  8970. name: 'BackgroundMaterial',
  8971. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8972. vertexShader: ShaderLib.background.vertexShader,
  8973. fragmentShader: ShaderLib.background.fragmentShader,
  8974. side: FrontSide,
  8975. depthTest: false,
  8976. depthWrite: false,
  8977. fog: false
  8978. } )
  8979. );
  8980. planeMesh.geometry.deleteAttribute( 'normal' );
  8981. // add "map" material property so the renderer can evaluate it like for built-in materials
  8982. Object.defineProperty( planeMesh.material, 'map', {
  8983. get: function () {
  8984. return this.uniforms.t2D.value;
  8985. }
  8986. } );
  8987. objects.update( planeMesh );
  8988. }
  8989. planeMesh.material.uniforms.t2D.value = background;
  8990. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8991. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8992. if ( background.matrixAutoUpdate === true ) {
  8993. background.updateMatrix();
  8994. }
  8995. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8996. if ( currentBackground !== background ||
  8997. currentBackgroundVersion !== background.version ||
  8998. currentTonemapping !== renderer.toneMapping ) {
  8999. planeMesh.material.needsUpdate = true;
  9000. currentBackground = background;
  9001. currentBackgroundVersion = background.version;
  9002. currentTonemapping = renderer.toneMapping;
  9003. }
  9004. planeMesh.layers.enableAll();
  9005. // push to the pre-sorted opaque render list
  9006. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9007. }
  9008. }
  9009. function setClear( color, alpha ) {
  9010. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  9011. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  9012. }
  9013. return {
  9014. getClearColor: function () {
  9015. return clearColor;
  9016. },
  9017. setClearColor: function ( color, alpha = 1 ) {
  9018. clearColor.set( color );
  9019. clearAlpha = alpha;
  9020. setClear( clearColor, clearAlpha );
  9021. },
  9022. getClearAlpha: function () {
  9023. return clearAlpha;
  9024. },
  9025. setClearAlpha: function ( alpha ) {
  9026. clearAlpha = alpha;
  9027. setClear( clearColor, clearAlpha );
  9028. },
  9029. render: render
  9030. };
  9031. }
  9032. function WebGLBindingStates( gl, attributes ) {
  9033. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9034. const bindingStates = {};
  9035. const defaultState = createBindingState( null );
  9036. let currentState = defaultState;
  9037. let forceUpdate = false;
  9038. function setup( object, material, program, geometry, index ) {
  9039. let updateBuffers = false;
  9040. const state = getBindingState( geometry, program, material );
  9041. if ( currentState !== state ) {
  9042. currentState = state;
  9043. bindVertexArrayObject( currentState.object );
  9044. }
  9045. updateBuffers = needsUpdate( object, geometry, program, index );
  9046. if ( updateBuffers ) saveCache( object, geometry, program, index );
  9047. if ( index !== null ) {
  9048. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9049. }
  9050. if ( updateBuffers || forceUpdate ) {
  9051. forceUpdate = false;
  9052. setupVertexAttributes( object, material, program, geometry );
  9053. if ( index !== null ) {
  9054. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9055. }
  9056. }
  9057. }
  9058. function createVertexArrayObject() {
  9059. return gl.createVertexArray();
  9060. }
  9061. function bindVertexArrayObject( vao ) {
  9062. return gl.bindVertexArray( vao );
  9063. }
  9064. function deleteVertexArrayObject( vao ) {
  9065. return gl.deleteVertexArray( vao );
  9066. }
  9067. function getBindingState( geometry, program, material ) {
  9068. const wireframe = ( material.wireframe === true );
  9069. let programMap = bindingStates[ geometry.id ];
  9070. if ( programMap === undefined ) {
  9071. programMap = {};
  9072. bindingStates[ geometry.id ] = programMap;
  9073. }
  9074. let stateMap = programMap[ program.id ];
  9075. if ( stateMap === undefined ) {
  9076. stateMap = {};
  9077. programMap[ program.id ] = stateMap;
  9078. }
  9079. let state = stateMap[ wireframe ];
  9080. if ( state === undefined ) {
  9081. state = createBindingState( createVertexArrayObject() );
  9082. stateMap[ wireframe ] = state;
  9083. }
  9084. return state;
  9085. }
  9086. function createBindingState( vao ) {
  9087. const newAttributes = [];
  9088. const enabledAttributes = [];
  9089. const attributeDivisors = [];
  9090. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9091. newAttributes[ i ] = 0;
  9092. enabledAttributes[ i ] = 0;
  9093. attributeDivisors[ i ] = 0;
  9094. }
  9095. return {
  9096. // for backward compatibility on non-VAO support browser
  9097. geometry: null,
  9098. program: null,
  9099. wireframe: false,
  9100. newAttributes: newAttributes,
  9101. enabledAttributes: enabledAttributes,
  9102. attributeDivisors: attributeDivisors,
  9103. object: vao,
  9104. attributes: {},
  9105. index: null
  9106. };
  9107. }
  9108. function needsUpdate( object, geometry, program, index ) {
  9109. const cachedAttributes = currentState.attributes;
  9110. const geometryAttributes = geometry.attributes;
  9111. let attributesNum = 0;
  9112. const programAttributes = program.getAttributes();
  9113. for ( const name in programAttributes ) {
  9114. const programAttribute = programAttributes[ name ];
  9115. if ( programAttribute.location >= 0 ) {
  9116. const cachedAttribute = cachedAttributes[ name ];
  9117. let geometryAttribute = geometryAttributes[ name ];
  9118. if ( geometryAttribute === undefined ) {
  9119. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9120. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9121. }
  9122. if ( cachedAttribute === undefined ) return true;
  9123. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9124. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9125. attributesNum ++;
  9126. }
  9127. }
  9128. if ( currentState.attributesNum !== attributesNum ) return true;
  9129. if ( currentState.index !== index ) return true;
  9130. return false;
  9131. }
  9132. function saveCache( object, geometry, program, index ) {
  9133. const cache = {};
  9134. const attributes = geometry.attributes;
  9135. let attributesNum = 0;
  9136. const programAttributes = program.getAttributes();
  9137. for ( const name in programAttributes ) {
  9138. const programAttribute = programAttributes[ name ];
  9139. if ( programAttribute.location >= 0 ) {
  9140. let attribute = attributes[ name ];
  9141. if ( attribute === undefined ) {
  9142. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9143. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9144. }
  9145. const data = {};
  9146. data.attribute = attribute;
  9147. if ( attribute && attribute.data ) {
  9148. data.data = attribute.data;
  9149. }
  9150. cache[ name ] = data;
  9151. attributesNum ++;
  9152. }
  9153. }
  9154. currentState.attributes = cache;
  9155. currentState.attributesNum = attributesNum;
  9156. currentState.index = index;
  9157. }
  9158. function initAttributes() {
  9159. const newAttributes = currentState.newAttributes;
  9160. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9161. newAttributes[ i ] = 0;
  9162. }
  9163. }
  9164. function enableAttribute( attribute ) {
  9165. enableAttributeAndDivisor( attribute, 0 );
  9166. }
  9167. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9168. const newAttributes = currentState.newAttributes;
  9169. const enabledAttributes = currentState.enabledAttributes;
  9170. const attributeDivisors = currentState.attributeDivisors;
  9171. newAttributes[ attribute ] = 1;
  9172. if ( enabledAttributes[ attribute ] === 0 ) {
  9173. gl.enableVertexAttribArray( attribute );
  9174. enabledAttributes[ attribute ] = 1;
  9175. }
  9176. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9177. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  9178. attributeDivisors[ attribute ] = meshPerAttribute;
  9179. }
  9180. }
  9181. function disableUnusedAttributes() {
  9182. const newAttributes = currentState.newAttributes;
  9183. const enabledAttributes = currentState.enabledAttributes;
  9184. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9185. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9186. gl.disableVertexAttribArray( i );
  9187. enabledAttributes[ i ] = 0;
  9188. }
  9189. }
  9190. }
  9191. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9192. if ( integer === true ) {
  9193. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9194. } else {
  9195. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9196. }
  9197. }
  9198. function setupVertexAttributes( object, material, program, geometry ) {
  9199. initAttributes();
  9200. const geometryAttributes = geometry.attributes;
  9201. const programAttributes = program.getAttributes();
  9202. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9203. for ( const name in programAttributes ) {
  9204. const programAttribute = programAttributes[ name ];
  9205. if ( programAttribute.location >= 0 ) {
  9206. let geometryAttribute = geometryAttributes[ name ];
  9207. if ( geometryAttribute === undefined ) {
  9208. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9209. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9210. }
  9211. if ( geometryAttribute !== undefined ) {
  9212. const normalized = geometryAttribute.normalized;
  9213. const size = geometryAttribute.itemSize;
  9214. const attribute = attributes.get( geometryAttribute );
  9215. // TODO Attribute may not be available on context restore
  9216. if ( attribute === undefined ) continue;
  9217. const buffer = attribute.buffer;
  9218. const type = attribute.type;
  9219. const bytesPerElement = attribute.bytesPerElement;
  9220. // check for integer attributes
  9221. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  9222. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9223. const data = geometryAttribute.data;
  9224. const stride = data.stride;
  9225. const offset = geometryAttribute.offset;
  9226. if ( data.isInstancedInterleavedBuffer ) {
  9227. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9228. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9229. }
  9230. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9231. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9232. }
  9233. } else {
  9234. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9235. enableAttribute( programAttribute.location + i );
  9236. }
  9237. }
  9238. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9239. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9240. vertexAttribPointer(
  9241. programAttribute.location + i,
  9242. size / programAttribute.locationSize,
  9243. type,
  9244. normalized,
  9245. stride * bytesPerElement,
  9246. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9247. integer
  9248. );
  9249. }
  9250. } else {
  9251. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9252. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9253. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9254. }
  9255. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9256. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9257. }
  9258. } else {
  9259. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9260. enableAttribute( programAttribute.location + i );
  9261. }
  9262. }
  9263. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9264. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9265. vertexAttribPointer(
  9266. programAttribute.location + i,
  9267. size / programAttribute.locationSize,
  9268. type,
  9269. normalized,
  9270. size * bytesPerElement,
  9271. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9272. integer
  9273. );
  9274. }
  9275. }
  9276. } else if ( materialDefaultAttributeValues !== undefined ) {
  9277. const value = materialDefaultAttributeValues[ name ];
  9278. if ( value !== undefined ) {
  9279. switch ( value.length ) {
  9280. case 2:
  9281. gl.vertexAttrib2fv( programAttribute.location, value );
  9282. break;
  9283. case 3:
  9284. gl.vertexAttrib3fv( programAttribute.location, value );
  9285. break;
  9286. case 4:
  9287. gl.vertexAttrib4fv( programAttribute.location, value );
  9288. break;
  9289. default:
  9290. gl.vertexAttrib1fv( programAttribute.location, value );
  9291. }
  9292. }
  9293. }
  9294. }
  9295. }
  9296. disableUnusedAttributes();
  9297. }
  9298. function dispose() {
  9299. reset();
  9300. for ( const geometryId in bindingStates ) {
  9301. const programMap = bindingStates[ geometryId ];
  9302. for ( const programId in programMap ) {
  9303. const stateMap = programMap[ programId ];
  9304. for ( const wireframe in stateMap ) {
  9305. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9306. delete stateMap[ wireframe ];
  9307. }
  9308. delete programMap[ programId ];
  9309. }
  9310. delete bindingStates[ geometryId ];
  9311. }
  9312. }
  9313. function releaseStatesOfGeometry( geometry ) {
  9314. if ( bindingStates[ geometry.id ] === undefined ) return;
  9315. const programMap = bindingStates[ geometry.id ];
  9316. for ( const programId in programMap ) {
  9317. const stateMap = programMap[ programId ];
  9318. for ( const wireframe in stateMap ) {
  9319. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9320. delete stateMap[ wireframe ];
  9321. }
  9322. delete programMap[ programId ];
  9323. }
  9324. delete bindingStates[ geometry.id ];
  9325. }
  9326. function releaseStatesOfProgram( program ) {
  9327. for ( const geometryId in bindingStates ) {
  9328. const programMap = bindingStates[ geometryId ];
  9329. if ( programMap[ program.id ] === undefined ) continue;
  9330. const stateMap = programMap[ program.id ];
  9331. for ( const wireframe in stateMap ) {
  9332. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9333. delete stateMap[ wireframe ];
  9334. }
  9335. delete programMap[ program.id ];
  9336. }
  9337. }
  9338. function reset() {
  9339. resetDefaultState();
  9340. forceUpdate = true;
  9341. if ( currentState === defaultState ) return;
  9342. currentState = defaultState;
  9343. bindVertexArrayObject( currentState.object );
  9344. }
  9345. // for backward-compatibility
  9346. function resetDefaultState() {
  9347. defaultState.geometry = null;
  9348. defaultState.program = null;
  9349. defaultState.wireframe = false;
  9350. }
  9351. return {
  9352. setup: setup,
  9353. reset: reset,
  9354. resetDefaultState: resetDefaultState,
  9355. dispose: dispose,
  9356. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9357. releaseStatesOfProgram: releaseStatesOfProgram,
  9358. initAttributes: initAttributes,
  9359. enableAttribute: enableAttribute,
  9360. disableUnusedAttributes: disableUnusedAttributes
  9361. };
  9362. }
  9363. function WebGLBufferRenderer( gl, extensions, info ) {
  9364. let mode;
  9365. function setMode( value ) {
  9366. mode = value;
  9367. }
  9368. function render( start, count ) {
  9369. gl.drawArrays( mode, start, count );
  9370. info.update( count, mode, 1 );
  9371. }
  9372. function renderInstances( start, count, primcount ) {
  9373. if ( primcount === 0 ) return;
  9374. gl.drawArraysInstanced( mode, start, count, primcount );
  9375. info.update( count, mode, primcount );
  9376. }
  9377. function renderMultiDraw( starts, counts, drawCount ) {
  9378. if ( drawCount === 0 ) return;
  9379. const extension = extensions.get( 'WEBGL_multi_draw' );
  9380. if ( extension === null ) {
  9381. for ( let i = 0; i < drawCount; i ++ ) {
  9382. this.render( starts[ i ], counts[ i ] );
  9383. }
  9384. } else {
  9385. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  9386. let elementCount = 0;
  9387. for ( let i = 0; i < drawCount; i ++ ) {
  9388. elementCount += counts[ i ];
  9389. }
  9390. info.update( elementCount, mode, 1 );
  9391. }
  9392. }
  9393. //
  9394. this.setMode = setMode;
  9395. this.render = render;
  9396. this.renderInstances = renderInstances;
  9397. this.renderMultiDraw = renderMultiDraw;
  9398. }
  9399. function WebGLCapabilities( gl, extensions, parameters ) {
  9400. let maxAnisotropy;
  9401. function getMaxAnisotropy() {
  9402. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9403. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9404. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9405. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9406. } else {
  9407. maxAnisotropy = 0;
  9408. }
  9409. return maxAnisotropy;
  9410. }
  9411. function getMaxPrecision( precision ) {
  9412. if ( precision === 'highp' ) {
  9413. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9414. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9415. return 'highp';
  9416. }
  9417. precision = 'mediump';
  9418. }
  9419. if ( precision === 'mediump' ) {
  9420. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9421. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9422. return 'mediump';
  9423. }
  9424. }
  9425. return 'lowp';
  9426. }
  9427. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9428. const maxPrecision = getMaxPrecision( precision );
  9429. if ( maxPrecision !== precision ) {
  9430. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9431. precision = maxPrecision;
  9432. }
  9433. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9434. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9435. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9436. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9437. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9438. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9439. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9440. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9441. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9442. const vertexTextures = maxVertexTextures > 0;
  9443. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  9444. return {
  9445. isWebGL2: true, // keeping this for backwards compatibility
  9446. getMaxAnisotropy: getMaxAnisotropy,
  9447. getMaxPrecision: getMaxPrecision,
  9448. precision: precision,
  9449. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9450. maxTextures: maxTextures,
  9451. maxVertexTextures: maxVertexTextures,
  9452. maxTextureSize: maxTextureSize,
  9453. maxCubemapSize: maxCubemapSize,
  9454. maxAttributes: maxAttributes,
  9455. maxVertexUniforms: maxVertexUniforms,
  9456. maxVaryings: maxVaryings,
  9457. maxFragmentUniforms: maxFragmentUniforms,
  9458. vertexTextures: vertexTextures,
  9459. maxSamples: maxSamples
  9460. };
  9461. }
  9462. function WebGLClipping( properties ) {
  9463. const scope = this;
  9464. let globalState = null,
  9465. numGlobalPlanes = 0,
  9466. localClippingEnabled = false,
  9467. renderingShadows = false;
  9468. const plane = new Plane(),
  9469. viewNormalMatrix = new Matrix3(),
  9470. uniform = { value: null, needsUpdate: false };
  9471. this.uniform = uniform;
  9472. this.numPlanes = 0;
  9473. this.numIntersection = 0;
  9474. this.init = function ( planes, enableLocalClipping ) {
  9475. const enabled =
  9476. planes.length !== 0 ||
  9477. enableLocalClipping ||
  9478. // enable state of previous frame - the clipping code has to
  9479. // run another frame in order to reset the state:
  9480. numGlobalPlanes !== 0 ||
  9481. localClippingEnabled;
  9482. localClippingEnabled = enableLocalClipping;
  9483. numGlobalPlanes = planes.length;
  9484. return enabled;
  9485. };
  9486. this.beginShadows = function () {
  9487. renderingShadows = true;
  9488. projectPlanes( null );
  9489. };
  9490. this.endShadows = function () {
  9491. renderingShadows = false;
  9492. };
  9493. this.setGlobalState = function ( planes, camera ) {
  9494. globalState = projectPlanes( planes, camera, 0 );
  9495. };
  9496. this.setState = function ( material, camera, useCache ) {
  9497. const planes = material.clippingPlanes,
  9498. clipIntersection = material.clipIntersection,
  9499. clipShadows = material.clipShadows;
  9500. const materialProperties = properties.get( material );
  9501. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9502. // there's no local clipping
  9503. if ( renderingShadows ) {
  9504. // there's no global clipping
  9505. projectPlanes( null );
  9506. } else {
  9507. resetGlobalState();
  9508. }
  9509. } else {
  9510. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9511. lGlobal = nGlobal * 4;
  9512. let dstArray = materialProperties.clippingState || null;
  9513. uniform.value = dstArray; // ensure unique state
  9514. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9515. for ( let i = 0; i !== lGlobal; ++ i ) {
  9516. dstArray[ i ] = globalState[ i ];
  9517. }
  9518. materialProperties.clippingState = dstArray;
  9519. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9520. this.numPlanes += nGlobal;
  9521. }
  9522. };
  9523. function resetGlobalState() {
  9524. if ( uniform.value !== globalState ) {
  9525. uniform.value = globalState;
  9526. uniform.needsUpdate = numGlobalPlanes > 0;
  9527. }
  9528. scope.numPlanes = numGlobalPlanes;
  9529. scope.numIntersection = 0;
  9530. }
  9531. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9532. const nPlanes = planes !== null ? planes.length : 0;
  9533. let dstArray = null;
  9534. if ( nPlanes !== 0 ) {
  9535. dstArray = uniform.value;
  9536. if ( skipTransform !== true || dstArray === null ) {
  9537. const flatSize = dstOffset + nPlanes * 4,
  9538. viewMatrix = camera.matrixWorldInverse;
  9539. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9540. if ( dstArray === null || dstArray.length < flatSize ) {
  9541. dstArray = new Float32Array( flatSize );
  9542. }
  9543. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9544. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9545. plane.normal.toArray( dstArray, i4 );
  9546. dstArray[ i4 + 3 ] = plane.constant;
  9547. }
  9548. }
  9549. uniform.value = dstArray;
  9550. uniform.needsUpdate = true;
  9551. }
  9552. scope.numPlanes = nPlanes;
  9553. scope.numIntersection = 0;
  9554. return dstArray;
  9555. }
  9556. }
  9557. function WebGLCubeMaps( renderer ) {
  9558. let cubemaps = new WeakMap();
  9559. function mapTextureMapping( texture, mapping ) {
  9560. if ( mapping === EquirectangularReflectionMapping ) {
  9561. texture.mapping = CubeReflectionMapping;
  9562. } else if ( mapping === EquirectangularRefractionMapping ) {
  9563. texture.mapping = CubeRefractionMapping;
  9564. }
  9565. return texture;
  9566. }
  9567. function get( texture ) {
  9568. if ( texture && texture.isTexture ) {
  9569. const mapping = texture.mapping;
  9570. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9571. if ( cubemaps.has( texture ) ) {
  9572. const cubemap = cubemaps.get( texture ).texture;
  9573. return mapTextureMapping( cubemap, texture.mapping );
  9574. } else {
  9575. const image = texture.image;
  9576. if ( image && image.height > 0 ) {
  9577. const renderTarget = new WebGLCubeRenderTarget( image.height );
  9578. renderTarget.fromEquirectangularTexture( renderer, texture );
  9579. cubemaps.set( texture, renderTarget );
  9580. texture.addEventListener( 'dispose', onTextureDispose );
  9581. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9582. } else {
  9583. // image not yet ready. try the conversion next frame
  9584. return null;
  9585. }
  9586. }
  9587. }
  9588. }
  9589. return texture;
  9590. }
  9591. function onTextureDispose( event ) {
  9592. const texture = event.target;
  9593. texture.removeEventListener( 'dispose', onTextureDispose );
  9594. const cubemap = cubemaps.get( texture );
  9595. if ( cubemap !== undefined ) {
  9596. cubemaps.delete( texture );
  9597. cubemap.dispose();
  9598. }
  9599. }
  9600. function dispose() {
  9601. cubemaps = new WeakMap();
  9602. }
  9603. return {
  9604. get: get,
  9605. dispose: dispose
  9606. };
  9607. }
  9608. class OrthographicCamera extends Camera {
  9609. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9610. super();
  9611. this.isOrthographicCamera = true;
  9612. this.type = 'OrthographicCamera';
  9613. this.zoom = 1;
  9614. this.view = null;
  9615. this.left = left;
  9616. this.right = right;
  9617. this.top = top;
  9618. this.bottom = bottom;
  9619. this.near = near;
  9620. this.far = far;
  9621. this.updateProjectionMatrix();
  9622. }
  9623. copy( source, recursive ) {
  9624. super.copy( source, recursive );
  9625. this.left = source.left;
  9626. this.right = source.right;
  9627. this.top = source.top;
  9628. this.bottom = source.bottom;
  9629. this.near = source.near;
  9630. this.far = source.far;
  9631. this.zoom = source.zoom;
  9632. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9633. return this;
  9634. }
  9635. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9636. if ( this.view === null ) {
  9637. this.view = {
  9638. enabled: true,
  9639. fullWidth: 1,
  9640. fullHeight: 1,
  9641. offsetX: 0,
  9642. offsetY: 0,
  9643. width: 1,
  9644. height: 1
  9645. };
  9646. }
  9647. this.view.enabled = true;
  9648. this.view.fullWidth = fullWidth;
  9649. this.view.fullHeight = fullHeight;
  9650. this.view.offsetX = x;
  9651. this.view.offsetY = y;
  9652. this.view.width = width;
  9653. this.view.height = height;
  9654. this.updateProjectionMatrix();
  9655. }
  9656. clearViewOffset() {
  9657. if ( this.view !== null ) {
  9658. this.view.enabled = false;
  9659. }
  9660. this.updateProjectionMatrix();
  9661. }
  9662. updateProjectionMatrix() {
  9663. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9664. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9665. const cx = ( this.right + this.left ) / 2;
  9666. const cy = ( this.top + this.bottom ) / 2;
  9667. let left = cx - dx;
  9668. let right = cx + dx;
  9669. let top = cy + dy;
  9670. let bottom = cy - dy;
  9671. if ( this.view !== null && this.view.enabled ) {
  9672. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9673. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9674. left += scaleW * this.view.offsetX;
  9675. right = left + scaleW * this.view.width;
  9676. top -= scaleH * this.view.offsetY;
  9677. bottom = top - scaleH * this.view.height;
  9678. }
  9679. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9680. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9681. }
  9682. toJSON( meta ) {
  9683. const data = super.toJSON( meta );
  9684. data.object.zoom = this.zoom;
  9685. data.object.left = this.left;
  9686. data.object.right = this.right;
  9687. data.object.top = this.top;
  9688. data.object.bottom = this.bottom;
  9689. data.object.near = this.near;
  9690. data.object.far = this.far;
  9691. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9692. return data;
  9693. }
  9694. }
  9695. const LOD_MIN = 4;
  9696. // The standard deviations (radians) associated with the extra mips. These are
  9697. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9698. // geometric shadowing function. These sigma values squared must match the
  9699. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9700. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9701. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9702. // samples and exit early, but not recompile the shader.
  9703. const MAX_SAMPLES = 20;
  9704. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9705. const _clearColor = /*@__PURE__*/ new Color();
  9706. let _oldTarget = null;
  9707. let _oldActiveCubeFace = 0;
  9708. let _oldActiveMipmapLevel = 0;
  9709. let _oldXrEnabled = false;
  9710. // Golden Ratio
  9711. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9712. const INV_PHI = 1 / PHI;
  9713. // Vertices of a dodecahedron (except the opposites, which represent the
  9714. // same axis), used as axis directions evenly spread on a sphere.
  9715. const _axisDirections = [
  9716. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9717. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9718. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9719. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9720. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9721. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9722. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9723. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9724. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9725. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9726. /**
  9727. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9728. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9729. * blur to be quickly accessed based on material roughness. It is packed into a
  9730. * special CubeUV format that allows us to perform custom interpolation so that
  9731. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9732. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9733. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9734. * higher roughness levels. In this way we maintain resolution to smoothly
  9735. * interpolate diffuse lighting while limiting sampling computation.
  9736. *
  9737. * Paper: Fast, Accurate Image-Based Lighting
  9738. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9739. */
  9740. class PMREMGenerator {
  9741. constructor( renderer ) {
  9742. this._renderer = renderer;
  9743. this._pingPongRenderTarget = null;
  9744. this._lodMax = 0;
  9745. this._cubeSize = 0;
  9746. this._lodPlanes = [];
  9747. this._sizeLods = [];
  9748. this._sigmas = [];
  9749. this._blurMaterial = null;
  9750. this._cubemapMaterial = null;
  9751. this._equirectMaterial = null;
  9752. this._compileMaterial( this._blurMaterial );
  9753. }
  9754. /**
  9755. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9756. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9757. * in radians to be applied to the scene before PMREM generation. Optional near
  9758. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9759. * is placed at the origin).
  9760. */
  9761. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9762. _oldTarget = this._renderer.getRenderTarget();
  9763. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9764. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9765. _oldXrEnabled = this._renderer.xr.enabled;
  9766. this._renderer.xr.enabled = false;
  9767. this._setSize( 256 );
  9768. const cubeUVRenderTarget = this._allocateTargets();
  9769. cubeUVRenderTarget.depthBuffer = true;
  9770. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9771. if ( sigma > 0 ) {
  9772. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9773. }
  9774. this._applyPMREM( cubeUVRenderTarget );
  9775. this._cleanup( cubeUVRenderTarget );
  9776. return cubeUVRenderTarget;
  9777. }
  9778. /**
  9779. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9780. * or HDR. The ideal input image size is 1k (1024 x 512),
  9781. * as this matches best with the 256 x 256 cubemap output.
  9782. * The smallest supported equirectangular image size is 64 x 32.
  9783. */
  9784. fromEquirectangular( equirectangular, renderTarget = null ) {
  9785. return this._fromTexture( equirectangular, renderTarget );
  9786. }
  9787. /**
  9788. * Generates a PMREM from an cubemap texture, which can be either LDR
  9789. * or HDR. The ideal input cube size is 256 x 256,
  9790. * as this matches best with the 256 x 256 cubemap output.
  9791. * The smallest supported cube size is 16 x 16.
  9792. */
  9793. fromCubemap( cubemap, renderTarget = null ) {
  9794. return this._fromTexture( cubemap, renderTarget );
  9795. }
  9796. /**
  9797. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9798. * your texture's network fetch for increased concurrency.
  9799. */
  9800. compileCubemapShader() {
  9801. if ( this._cubemapMaterial === null ) {
  9802. this._cubemapMaterial = _getCubemapMaterial();
  9803. this._compileMaterial( this._cubemapMaterial );
  9804. }
  9805. }
  9806. /**
  9807. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9808. * your texture's network fetch for increased concurrency.
  9809. */
  9810. compileEquirectangularShader() {
  9811. if ( this._equirectMaterial === null ) {
  9812. this._equirectMaterial = _getEquirectMaterial();
  9813. this._compileMaterial( this._equirectMaterial );
  9814. }
  9815. }
  9816. /**
  9817. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9818. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9819. * one of them will cause any others to also become unusable.
  9820. */
  9821. dispose() {
  9822. this._dispose();
  9823. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9824. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9825. }
  9826. // private interface
  9827. _setSize( cubeSize ) {
  9828. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9829. this._cubeSize = Math.pow( 2, this._lodMax );
  9830. }
  9831. _dispose() {
  9832. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9833. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9834. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9835. this._lodPlanes[ i ].dispose();
  9836. }
  9837. }
  9838. _cleanup( outputTarget ) {
  9839. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  9840. this._renderer.xr.enabled = _oldXrEnabled;
  9841. outputTarget.scissorTest = false;
  9842. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9843. }
  9844. _fromTexture( texture, renderTarget ) {
  9845. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9846. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9847. } else { // Equirectangular
  9848. this._setSize( texture.image.width / 4 );
  9849. }
  9850. _oldTarget = this._renderer.getRenderTarget();
  9851. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9852. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9853. _oldXrEnabled = this._renderer.xr.enabled;
  9854. this._renderer.xr.enabled = false;
  9855. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9856. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9857. this._applyPMREM( cubeUVRenderTarget );
  9858. this._cleanup( cubeUVRenderTarget );
  9859. return cubeUVRenderTarget;
  9860. }
  9861. _allocateTargets() {
  9862. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9863. const height = 4 * this._cubeSize;
  9864. const params = {
  9865. magFilter: LinearFilter,
  9866. minFilter: LinearFilter,
  9867. generateMipmaps: false,
  9868. type: HalfFloatType,
  9869. format: RGBAFormat,
  9870. colorSpace: LinearSRGBColorSpace,
  9871. depthBuffer: false
  9872. };
  9873. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9874. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9875. if ( this._pingPongRenderTarget !== null ) {
  9876. this._dispose();
  9877. }
  9878. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9879. const { _lodMax } = this;
  9880. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9881. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9882. }
  9883. return cubeUVRenderTarget;
  9884. }
  9885. _compileMaterial( material ) {
  9886. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9887. this._renderer.compile( tmpMesh, _flatCamera );
  9888. }
  9889. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9890. const fov = 90;
  9891. const aspect = 1;
  9892. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9893. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9894. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9895. const renderer = this._renderer;
  9896. const originalAutoClear = renderer.autoClear;
  9897. const toneMapping = renderer.toneMapping;
  9898. renderer.getClearColor( _clearColor );
  9899. renderer.toneMapping = NoToneMapping;
  9900. renderer.autoClear = false;
  9901. const backgroundMaterial = new MeshBasicMaterial( {
  9902. name: 'PMREM.Background',
  9903. side: BackSide,
  9904. depthWrite: false,
  9905. depthTest: false,
  9906. } );
  9907. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9908. let useSolidColor = false;
  9909. const background = scene.background;
  9910. if ( background ) {
  9911. if ( background.isColor ) {
  9912. backgroundMaterial.color.copy( background );
  9913. scene.background = null;
  9914. useSolidColor = true;
  9915. }
  9916. } else {
  9917. backgroundMaterial.color.copy( _clearColor );
  9918. useSolidColor = true;
  9919. }
  9920. for ( let i = 0; i < 6; i ++ ) {
  9921. const col = i % 3;
  9922. if ( col === 0 ) {
  9923. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9924. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9925. } else if ( col === 1 ) {
  9926. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9927. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9928. } else {
  9929. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9930. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9931. }
  9932. const size = this._cubeSize;
  9933. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9934. renderer.setRenderTarget( cubeUVRenderTarget );
  9935. if ( useSolidColor ) {
  9936. renderer.render( backgroundBox, cubeCamera );
  9937. }
  9938. renderer.render( scene, cubeCamera );
  9939. }
  9940. backgroundBox.geometry.dispose();
  9941. backgroundBox.material.dispose();
  9942. renderer.toneMapping = toneMapping;
  9943. renderer.autoClear = originalAutoClear;
  9944. scene.background = background;
  9945. }
  9946. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9947. const renderer = this._renderer;
  9948. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9949. if ( isCubeTexture ) {
  9950. if ( this._cubemapMaterial === null ) {
  9951. this._cubemapMaterial = _getCubemapMaterial();
  9952. }
  9953. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9954. } else {
  9955. if ( this._equirectMaterial === null ) {
  9956. this._equirectMaterial = _getEquirectMaterial();
  9957. }
  9958. }
  9959. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9960. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9961. const uniforms = material.uniforms;
  9962. uniforms[ 'envMap' ].value = texture;
  9963. const size = this._cubeSize;
  9964. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9965. renderer.setRenderTarget( cubeUVRenderTarget );
  9966. renderer.render( mesh, _flatCamera );
  9967. }
  9968. _applyPMREM( cubeUVRenderTarget ) {
  9969. const renderer = this._renderer;
  9970. const autoClear = renderer.autoClear;
  9971. renderer.autoClear = false;
  9972. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9973. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9974. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9975. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9976. }
  9977. renderer.autoClear = autoClear;
  9978. }
  9979. /**
  9980. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9981. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9982. * the blur latitudinally (around the poles), and then longitudinally (towards
  9983. * the poles) to approximate the orthogonally-separable blur. It is least
  9984. * accurate at the poles, but still does a decent job.
  9985. */
  9986. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9987. const pingPongRenderTarget = this._pingPongRenderTarget;
  9988. this._halfBlur(
  9989. cubeUVRenderTarget,
  9990. pingPongRenderTarget,
  9991. lodIn,
  9992. lodOut,
  9993. sigma,
  9994. 'latitudinal',
  9995. poleAxis );
  9996. this._halfBlur(
  9997. pingPongRenderTarget,
  9998. cubeUVRenderTarget,
  9999. lodOut,
  10000. lodOut,
  10001. sigma,
  10002. 'longitudinal',
  10003. poleAxis );
  10004. }
  10005. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10006. const renderer = this._renderer;
  10007. const blurMaterial = this._blurMaterial;
  10008. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10009. console.error(
  10010. 'blur direction must be either latitudinal or longitudinal!' );
  10011. }
  10012. // Number of standard deviations at which to cut off the discrete approximation.
  10013. const STANDARD_DEVIATIONS = 3;
  10014. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  10015. const blurUniforms = blurMaterial.uniforms;
  10016. const pixels = this._sizeLods[ lodIn ] - 1;
  10017. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10018. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10019. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10020. if ( samples > MAX_SAMPLES ) {
  10021. console.warn( `sigmaRadians, ${
  10022. sigmaRadians}, is too large and will clip, as it requested ${
  10023. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10024. }
  10025. const weights = [];
  10026. let sum = 0;
  10027. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10028. const x = i / sigmaPixels;
  10029. const weight = Math.exp( - x * x / 2 );
  10030. weights.push( weight );
  10031. if ( i === 0 ) {
  10032. sum += weight;
  10033. } else if ( i < samples ) {
  10034. sum += 2 * weight;
  10035. }
  10036. }
  10037. for ( let i = 0; i < weights.length; i ++ ) {
  10038. weights[ i ] = weights[ i ] / sum;
  10039. }
  10040. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10041. blurUniforms[ 'samples' ].value = samples;
  10042. blurUniforms[ 'weights' ].value = weights;
  10043. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10044. if ( poleAxis ) {
  10045. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10046. }
  10047. const { _lodMax } = this;
  10048. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10049. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10050. const outputSize = this._sizeLods[ lodOut ];
  10051. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10052. const y = 4 * ( this._cubeSize - outputSize );
  10053. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10054. renderer.setRenderTarget( targetOut );
  10055. renderer.render( blurMesh, _flatCamera );
  10056. }
  10057. }
  10058. function _createPlanes( lodMax ) {
  10059. const lodPlanes = [];
  10060. const sizeLods = [];
  10061. const sigmas = [];
  10062. let lod = lodMax;
  10063. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10064. for ( let i = 0; i < totalLods; i ++ ) {
  10065. const sizeLod = Math.pow( 2, lod );
  10066. sizeLods.push( sizeLod );
  10067. let sigma = 1.0 / sizeLod;
  10068. if ( i > lodMax - LOD_MIN ) {
  10069. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10070. } else if ( i === 0 ) {
  10071. sigma = 0;
  10072. }
  10073. sigmas.push( sigma );
  10074. const texelSize = 1.0 / ( sizeLod - 2 );
  10075. const min = - texelSize;
  10076. const max = 1 + texelSize;
  10077. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10078. const cubeFaces = 6;
  10079. const vertices = 6;
  10080. const positionSize = 3;
  10081. const uvSize = 2;
  10082. const faceIndexSize = 1;
  10083. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10084. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10085. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10086. for ( let face = 0; face < cubeFaces; face ++ ) {
  10087. const x = ( face % 3 ) * 2 / 3 - 1;
  10088. const y = face > 2 ? 0 : - 1;
  10089. const coordinates = [
  10090. x, y, 0,
  10091. x + 2 / 3, y, 0,
  10092. x + 2 / 3, y + 1, 0,
  10093. x, y, 0,
  10094. x + 2 / 3, y + 1, 0,
  10095. x, y + 1, 0
  10096. ];
  10097. position.set( coordinates, positionSize * vertices * face );
  10098. uv.set( uv1, uvSize * vertices * face );
  10099. const fill = [ face, face, face, face, face, face ];
  10100. faceIndex.set( fill, faceIndexSize * vertices * face );
  10101. }
  10102. const planes = new BufferGeometry();
  10103. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10104. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10105. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10106. lodPlanes.push( planes );
  10107. if ( lod > LOD_MIN ) {
  10108. lod --;
  10109. }
  10110. }
  10111. return { lodPlanes, sizeLods, sigmas };
  10112. }
  10113. function _createRenderTarget( width, height, params ) {
  10114. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10115. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10116. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10117. cubeUVRenderTarget.scissorTest = true;
  10118. return cubeUVRenderTarget;
  10119. }
  10120. function _setViewport( target, x, y, width, height ) {
  10121. target.viewport.set( x, y, width, height );
  10122. target.scissor.set( x, y, width, height );
  10123. }
  10124. function _getBlurShader( lodMax, width, height ) {
  10125. const weights = new Float32Array( MAX_SAMPLES );
  10126. const poleAxis = new Vector3( 0, 1, 0 );
  10127. const shaderMaterial = new ShaderMaterial( {
  10128. name: 'SphericalGaussianBlur',
  10129. defines: {
  10130. 'n': MAX_SAMPLES,
  10131. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10132. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10133. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10134. },
  10135. uniforms: {
  10136. 'envMap': { value: null },
  10137. 'samples': { value: 1 },
  10138. 'weights': { value: weights },
  10139. 'latitudinal': { value: false },
  10140. 'dTheta': { value: 0 },
  10141. 'mipInt': { value: 0 },
  10142. 'poleAxis': { value: poleAxis }
  10143. },
  10144. vertexShader: _getCommonVertexShader(),
  10145. fragmentShader: /* glsl */`
  10146. precision mediump float;
  10147. precision mediump int;
  10148. varying vec3 vOutputDirection;
  10149. uniform sampler2D envMap;
  10150. uniform int samples;
  10151. uniform float weights[ n ];
  10152. uniform bool latitudinal;
  10153. uniform float dTheta;
  10154. uniform float mipInt;
  10155. uniform vec3 poleAxis;
  10156. #define ENVMAP_TYPE_CUBE_UV
  10157. #include <cube_uv_reflection_fragment>
  10158. vec3 getSample( float theta, vec3 axis ) {
  10159. float cosTheta = cos( theta );
  10160. // Rodrigues' axis-angle rotation
  10161. vec3 sampleDirection = vOutputDirection * cosTheta
  10162. + cross( axis, vOutputDirection ) * sin( theta )
  10163. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10164. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10165. }
  10166. void main() {
  10167. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10168. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10169. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10170. }
  10171. axis = normalize( axis );
  10172. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10173. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10174. for ( int i = 1; i < n; i++ ) {
  10175. if ( i >= samples ) {
  10176. break;
  10177. }
  10178. float theta = dTheta * float( i );
  10179. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10180. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10181. }
  10182. }
  10183. `,
  10184. blending: NoBlending,
  10185. depthTest: false,
  10186. depthWrite: false
  10187. } );
  10188. return shaderMaterial;
  10189. }
  10190. function _getEquirectMaterial() {
  10191. return new ShaderMaterial( {
  10192. name: 'EquirectangularToCubeUV',
  10193. uniforms: {
  10194. 'envMap': { value: null }
  10195. },
  10196. vertexShader: _getCommonVertexShader(),
  10197. fragmentShader: /* glsl */`
  10198. precision mediump float;
  10199. precision mediump int;
  10200. varying vec3 vOutputDirection;
  10201. uniform sampler2D envMap;
  10202. #include <common>
  10203. void main() {
  10204. vec3 outputDirection = normalize( vOutputDirection );
  10205. vec2 uv = equirectUv( outputDirection );
  10206. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10207. }
  10208. `,
  10209. blending: NoBlending,
  10210. depthTest: false,
  10211. depthWrite: false
  10212. } );
  10213. }
  10214. function _getCubemapMaterial() {
  10215. return new ShaderMaterial( {
  10216. name: 'CubemapToCubeUV',
  10217. uniforms: {
  10218. 'envMap': { value: null },
  10219. 'flipEnvMap': { value: - 1 }
  10220. },
  10221. vertexShader: _getCommonVertexShader(),
  10222. fragmentShader: /* glsl */`
  10223. precision mediump float;
  10224. precision mediump int;
  10225. uniform float flipEnvMap;
  10226. varying vec3 vOutputDirection;
  10227. uniform samplerCube envMap;
  10228. void main() {
  10229. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10230. }
  10231. `,
  10232. blending: NoBlending,
  10233. depthTest: false,
  10234. depthWrite: false
  10235. } );
  10236. }
  10237. function _getCommonVertexShader() {
  10238. return /* glsl */`
  10239. precision mediump float;
  10240. precision mediump int;
  10241. attribute float faceIndex;
  10242. varying vec3 vOutputDirection;
  10243. // RH coordinate system; PMREM face-indexing convention
  10244. vec3 getDirection( vec2 uv, float face ) {
  10245. uv = 2.0 * uv - 1.0;
  10246. vec3 direction = vec3( uv, 1.0 );
  10247. if ( face == 0.0 ) {
  10248. direction = direction.zyx; // ( 1, v, u ) pos x
  10249. } else if ( face == 1.0 ) {
  10250. direction = direction.xzy;
  10251. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10252. } else if ( face == 2.0 ) {
  10253. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10254. } else if ( face == 3.0 ) {
  10255. direction = direction.zyx;
  10256. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10257. } else if ( face == 4.0 ) {
  10258. direction = direction.xzy;
  10259. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10260. } else if ( face == 5.0 ) {
  10261. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10262. }
  10263. return direction;
  10264. }
  10265. void main() {
  10266. vOutputDirection = getDirection( uv, faceIndex );
  10267. gl_Position = vec4( position, 1.0 );
  10268. }
  10269. `;
  10270. }
  10271. function WebGLCubeUVMaps( renderer ) {
  10272. let cubeUVmaps = new WeakMap();
  10273. let pmremGenerator = null;
  10274. function get( texture ) {
  10275. if ( texture && texture.isTexture ) {
  10276. const mapping = texture.mapping;
  10277. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10278. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10279. // equirect/cube map to cubeUV conversion
  10280. if ( isEquirectMap || isCubeMap ) {
  10281. let renderTarget = cubeUVmaps.get( texture );
  10282. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  10283. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  10284. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10285. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10286. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10287. cubeUVmaps.set( texture, renderTarget );
  10288. return renderTarget.texture;
  10289. } else {
  10290. if ( renderTarget !== undefined ) {
  10291. return renderTarget.texture;
  10292. } else {
  10293. const image = texture.image;
  10294. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10295. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10296. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10297. renderTarget.texture.pmremVersion = texture.pmremVersion;
  10298. cubeUVmaps.set( texture, renderTarget );
  10299. texture.addEventListener( 'dispose', onTextureDispose );
  10300. return renderTarget.texture;
  10301. } else {
  10302. // image not yet ready. try the conversion next frame
  10303. return null;
  10304. }
  10305. }
  10306. }
  10307. }
  10308. }
  10309. return texture;
  10310. }
  10311. function isCubeTextureComplete( image ) {
  10312. let count = 0;
  10313. const length = 6;
  10314. for ( let i = 0; i < length; i ++ ) {
  10315. if ( image[ i ] !== undefined ) count ++;
  10316. }
  10317. return count === length;
  10318. }
  10319. function onTextureDispose( event ) {
  10320. const texture = event.target;
  10321. texture.removeEventListener( 'dispose', onTextureDispose );
  10322. const cubemapUV = cubeUVmaps.get( texture );
  10323. if ( cubemapUV !== undefined ) {
  10324. cubeUVmaps.delete( texture );
  10325. cubemapUV.dispose();
  10326. }
  10327. }
  10328. function dispose() {
  10329. cubeUVmaps = new WeakMap();
  10330. if ( pmremGenerator !== null ) {
  10331. pmremGenerator.dispose();
  10332. pmremGenerator = null;
  10333. }
  10334. }
  10335. return {
  10336. get: get,
  10337. dispose: dispose
  10338. };
  10339. }
  10340. function WebGLExtensions( gl ) {
  10341. const extensions = {};
  10342. function getExtension( name ) {
  10343. if ( extensions[ name ] !== undefined ) {
  10344. return extensions[ name ];
  10345. }
  10346. let extension;
  10347. switch ( name ) {
  10348. case 'WEBGL_depth_texture':
  10349. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10350. break;
  10351. case 'EXT_texture_filter_anisotropic':
  10352. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10353. break;
  10354. case 'WEBGL_compressed_texture_s3tc':
  10355. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10356. break;
  10357. case 'WEBGL_compressed_texture_pvrtc':
  10358. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10359. break;
  10360. default:
  10361. extension = gl.getExtension( name );
  10362. }
  10363. extensions[ name ] = extension;
  10364. return extension;
  10365. }
  10366. return {
  10367. has: function ( name ) {
  10368. return getExtension( name ) !== null;
  10369. },
  10370. init: function () {
  10371. getExtension( 'EXT_color_buffer_float' );
  10372. getExtension( 'WEBGL_clip_cull_distance' );
  10373. getExtension( 'OES_texture_float_linear' );
  10374. getExtension( 'EXT_color_buffer_half_float' );
  10375. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10376. },
  10377. get: function ( name ) {
  10378. const extension = getExtension( name );
  10379. if ( extension === null ) {
  10380. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10381. }
  10382. return extension;
  10383. }
  10384. };
  10385. }
  10386. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10387. const geometries = {};
  10388. const wireframeAttributes = new WeakMap();
  10389. function onGeometryDispose( event ) {
  10390. const geometry = event.target;
  10391. if ( geometry.index !== null ) {
  10392. attributes.remove( geometry.index );
  10393. }
  10394. for ( const name in geometry.attributes ) {
  10395. attributes.remove( geometry.attributes[ name ] );
  10396. }
  10397. for ( const name in geometry.morphAttributes ) {
  10398. const array = geometry.morphAttributes[ name ];
  10399. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10400. attributes.remove( array[ i ] );
  10401. }
  10402. }
  10403. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10404. delete geometries[ geometry.id ];
  10405. const attribute = wireframeAttributes.get( geometry );
  10406. if ( attribute ) {
  10407. attributes.remove( attribute );
  10408. wireframeAttributes.delete( geometry );
  10409. }
  10410. bindingStates.releaseStatesOfGeometry( geometry );
  10411. if ( geometry.isInstancedBufferGeometry === true ) {
  10412. delete geometry._maxInstanceCount;
  10413. }
  10414. //
  10415. info.memory.geometries --;
  10416. }
  10417. function get( object, geometry ) {
  10418. if ( geometries[ geometry.id ] === true ) return geometry;
  10419. geometry.addEventListener( 'dispose', onGeometryDispose );
  10420. geometries[ geometry.id ] = true;
  10421. info.memory.geometries ++;
  10422. return geometry;
  10423. }
  10424. function update( geometry ) {
  10425. const geometryAttributes = geometry.attributes;
  10426. // Updating index buffer in VAO now. See WebGLBindingStates.
  10427. for ( const name in geometryAttributes ) {
  10428. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10429. }
  10430. // morph targets
  10431. const morphAttributes = geometry.morphAttributes;
  10432. for ( const name in morphAttributes ) {
  10433. const array = morphAttributes[ name ];
  10434. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10435. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10436. }
  10437. }
  10438. }
  10439. function updateWireframeAttribute( geometry ) {
  10440. const indices = [];
  10441. const geometryIndex = geometry.index;
  10442. const geometryPosition = geometry.attributes.position;
  10443. let version = 0;
  10444. if ( geometryIndex !== null ) {
  10445. const array = geometryIndex.array;
  10446. version = geometryIndex.version;
  10447. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10448. const a = array[ i + 0 ];
  10449. const b = array[ i + 1 ];
  10450. const c = array[ i + 2 ];
  10451. indices.push( a, b, b, c, c, a );
  10452. }
  10453. } else if ( geometryPosition !== undefined ) {
  10454. const array = geometryPosition.array;
  10455. version = geometryPosition.version;
  10456. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10457. const a = i + 0;
  10458. const b = i + 1;
  10459. const c = i + 2;
  10460. indices.push( a, b, b, c, c, a );
  10461. }
  10462. } else {
  10463. return;
  10464. }
  10465. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10466. attribute.version = version;
  10467. // Updating index buffer in VAO now. See WebGLBindingStates
  10468. //
  10469. const previousAttribute = wireframeAttributes.get( geometry );
  10470. if ( previousAttribute ) attributes.remove( previousAttribute );
  10471. //
  10472. wireframeAttributes.set( geometry, attribute );
  10473. }
  10474. function getWireframeAttribute( geometry ) {
  10475. const currentAttribute = wireframeAttributes.get( geometry );
  10476. if ( currentAttribute ) {
  10477. const geometryIndex = geometry.index;
  10478. if ( geometryIndex !== null ) {
  10479. // if the attribute is obsolete, create a new one
  10480. if ( currentAttribute.version < geometryIndex.version ) {
  10481. updateWireframeAttribute( geometry );
  10482. }
  10483. }
  10484. } else {
  10485. updateWireframeAttribute( geometry );
  10486. }
  10487. return wireframeAttributes.get( geometry );
  10488. }
  10489. return {
  10490. get: get,
  10491. update: update,
  10492. getWireframeAttribute: getWireframeAttribute
  10493. };
  10494. }
  10495. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  10496. let mode;
  10497. function setMode( value ) {
  10498. mode = value;
  10499. }
  10500. let type, bytesPerElement;
  10501. function setIndex( value ) {
  10502. type = value.type;
  10503. bytesPerElement = value.bytesPerElement;
  10504. }
  10505. function render( start, count ) {
  10506. gl.drawElements( mode, count, type, start * bytesPerElement );
  10507. info.update( count, mode, 1 );
  10508. }
  10509. function renderInstances( start, count, primcount ) {
  10510. if ( primcount === 0 ) return;
  10511. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  10512. info.update( count, mode, primcount );
  10513. }
  10514. function renderMultiDraw( starts, counts, drawCount ) {
  10515. if ( drawCount === 0 ) return;
  10516. const extension = extensions.get( 'WEBGL_multi_draw' );
  10517. if ( extension === null ) {
  10518. for ( let i = 0; i < drawCount; i ++ ) {
  10519. this.render( starts[ i ] / bytesPerElement, counts[ i ] );
  10520. }
  10521. } else {
  10522. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  10523. let elementCount = 0;
  10524. for ( let i = 0; i < drawCount; i ++ ) {
  10525. elementCount += counts[ i ];
  10526. }
  10527. info.update( elementCount, mode, 1 );
  10528. }
  10529. }
  10530. //
  10531. this.setMode = setMode;
  10532. this.setIndex = setIndex;
  10533. this.render = render;
  10534. this.renderInstances = renderInstances;
  10535. this.renderMultiDraw = renderMultiDraw;
  10536. }
  10537. function WebGLInfo( gl ) {
  10538. const memory = {
  10539. geometries: 0,
  10540. textures: 0
  10541. };
  10542. const render = {
  10543. frame: 0,
  10544. calls: 0,
  10545. triangles: 0,
  10546. points: 0,
  10547. lines: 0
  10548. };
  10549. function update( count, mode, instanceCount ) {
  10550. render.calls ++;
  10551. switch ( mode ) {
  10552. case gl.TRIANGLES:
  10553. render.triangles += instanceCount * ( count / 3 );
  10554. break;
  10555. case gl.LINES:
  10556. render.lines += instanceCount * ( count / 2 );
  10557. break;
  10558. case gl.LINE_STRIP:
  10559. render.lines += instanceCount * ( count - 1 );
  10560. break;
  10561. case gl.LINE_LOOP:
  10562. render.lines += instanceCount * count;
  10563. break;
  10564. case gl.POINTS:
  10565. render.points += instanceCount * count;
  10566. break;
  10567. default:
  10568. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10569. break;
  10570. }
  10571. }
  10572. function reset() {
  10573. render.calls = 0;
  10574. render.triangles = 0;
  10575. render.points = 0;
  10576. render.lines = 0;
  10577. }
  10578. return {
  10579. memory: memory,
  10580. render: render,
  10581. programs: null,
  10582. autoReset: true,
  10583. reset: reset,
  10584. update: update
  10585. };
  10586. }
  10587. function WebGLMorphtargets( gl, capabilities, textures ) {
  10588. const morphTextures = new WeakMap();
  10589. const morph = new Vector4();
  10590. function update( object, geometry, program ) {
  10591. const objectInfluences = object.morphTargetInfluences;
  10592. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10593. // into an array of data textures. Each layer represents a single morph target.
  10594. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10595. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10596. let entry = morphTextures.get( geometry );
  10597. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10598. if ( entry !== undefined ) entry.texture.dispose();
  10599. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10600. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10601. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10602. const morphTargets = geometry.morphAttributes.position || [];
  10603. const morphNormals = geometry.morphAttributes.normal || [];
  10604. const morphColors = geometry.morphAttributes.color || [];
  10605. let vertexDataCount = 0;
  10606. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10607. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10608. if ( hasMorphColors === true ) vertexDataCount = 3;
  10609. let width = geometry.attributes.position.count * vertexDataCount;
  10610. let height = 1;
  10611. if ( width > capabilities.maxTextureSize ) {
  10612. height = Math.ceil( width / capabilities.maxTextureSize );
  10613. width = capabilities.maxTextureSize;
  10614. }
  10615. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10616. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10617. texture.type = FloatType;
  10618. texture.needsUpdate = true;
  10619. // fill buffer
  10620. const vertexDataStride = vertexDataCount * 4;
  10621. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10622. const morphTarget = morphTargets[ i ];
  10623. const morphNormal = morphNormals[ i ];
  10624. const morphColor = morphColors[ i ];
  10625. const offset = width * height * 4 * i;
  10626. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10627. const stride = j * vertexDataStride;
  10628. if ( hasMorphPosition === true ) {
  10629. morph.fromBufferAttribute( morphTarget, j );
  10630. buffer[ offset + stride + 0 ] = morph.x;
  10631. buffer[ offset + stride + 1 ] = morph.y;
  10632. buffer[ offset + stride + 2 ] = morph.z;
  10633. buffer[ offset + stride + 3 ] = 0;
  10634. }
  10635. if ( hasMorphNormals === true ) {
  10636. morph.fromBufferAttribute( morphNormal, j );
  10637. buffer[ offset + stride + 4 ] = morph.x;
  10638. buffer[ offset + stride + 5 ] = morph.y;
  10639. buffer[ offset + stride + 6 ] = morph.z;
  10640. buffer[ offset + stride + 7 ] = 0;
  10641. }
  10642. if ( hasMorphColors === true ) {
  10643. morph.fromBufferAttribute( morphColor, j );
  10644. buffer[ offset + stride + 8 ] = morph.x;
  10645. buffer[ offset + stride + 9 ] = morph.y;
  10646. buffer[ offset + stride + 10 ] = morph.z;
  10647. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10648. }
  10649. }
  10650. }
  10651. entry = {
  10652. count: morphTargetsCount,
  10653. texture: texture,
  10654. size: new Vector2( width, height )
  10655. };
  10656. morphTextures.set( geometry, entry );
  10657. function disposeTexture() {
  10658. texture.dispose();
  10659. morphTextures.delete( geometry );
  10660. geometry.removeEventListener( 'dispose', disposeTexture );
  10661. }
  10662. geometry.addEventListener( 'dispose', disposeTexture );
  10663. }
  10664. //
  10665. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  10666. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  10667. } else {
  10668. let morphInfluencesSum = 0;
  10669. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10670. morphInfluencesSum += objectInfluences[ i ];
  10671. }
  10672. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10673. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10674. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10675. }
  10676. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10677. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10678. }
  10679. return {
  10680. update: update
  10681. };
  10682. }
  10683. function WebGLObjects( gl, geometries, attributes, info ) {
  10684. let updateMap = new WeakMap();
  10685. function update( object ) {
  10686. const frame = info.render.frame;
  10687. const geometry = object.geometry;
  10688. const buffergeometry = geometries.get( object, geometry );
  10689. // Update once per frame
  10690. if ( updateMap.get( buffergeometry ) !== frame ) {
  10691. geometries.update( buffergeometry );
  10692. updateMap.set( buffergeometry, frame );
  10693. }
  10694. if ( object.isInstancedMesh ) {
  10695. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10696. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10697. }
  10698. if ( updateMap.get( object ) !== frame ) {
  10699. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10700. if ( object.instanceColor !== null ) {
  10701. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10702. }
  10703. updateMap.set( object, frame );
  10704. }
  10705. }
  10706. if ( object.isSkinnedMesh ) {
  10707. const skeleton = object.skeleton;
  10708. if ( updateMap.get( skeleton ) !== frame ) {
  10709. skeleton.update();
  10710. updateMap.set( skeleton, frame );
  10711. }
  10712. }
  10713. return buffergeometry;
  10714. }
  10715. function dispose() {
  10716. updateMap = new WeakMap();
  10717. }
  10718. function onInstancedMeshDispose( event ) {
  10719. const instancedMesh = event.target;
  10720. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10721. attributes.remove( instancedMesh.instanceMatrix );
  10722. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10723. }
  10724. return {
  10725. update: update,
  10726. dispose: dispose
  10727. };
  10728. }
  10729. class DepthTexture extends Texture {
  10730. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  10731. format = format !== undefined ? format : DepthFormat;
  10732. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10733. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10734. }
  10735. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10736. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10737. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10738. this.isDepthTexture = true;
  10739. this.image = { width: width, height: height };
  10740. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10741. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10742. this.flipY = false;
  10743. this.generateMipmaps = false;
  10744. this.compareFunction = null;
  10745. }
  10746. copy( source ) {
  10747. super.copy( source );
  10748. this.compareFunction = source.compareFunction;
  10749. return this;
  10750. }
  10751. toJSON( meta ) {
  10752. const data = super.toJSON( meta );
  10753. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10754. return data;
  10755. }
  10756. }
  10757. /**
  10758. * Uniforms of a program.
  10759. * Those form a tree structure with a special top-level container for the root,
  10760. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10761. *
  10762. *
  10763. * Properties of inner nodes including the top-level container:
  10764. *
  10765. * .seq - array of nested uniforms
  10766. * .map - nested uniforms by name
  10767. *
  10768. *
  10769. * Methods of all nodes except the top-level container:
  10770. *
  10771. * .setValue( gl, value, [textures] )
  10772. *
  10773. * uploads a uniform value(s)
  10774. * the 'textures' parameter is needed for sampler uniforms
  10775. *
  10776. *
  10777. * Static methods of the top-level container (textures factorizations):
  10778. *
  10779. * .upload( gl, seq, values, textures )
  10780. *
  10781. * sets uniforms in 'seq' to 'values[id].value'
  10782. *
  10783. * .seqWithValue( seq, values ) : filteredSeq
  10784. *
  10785. * filters 'seq' entries with corresponding entry in values
  10786. *
  10787. *
  10788. * Methods of the top-level container (textures factorizations):
  10789. *
  10790. * .setValue( gl, name, value, textures )
  10791. *
  10792. * sets uniform with name 'name' to 'value'
  10793. *
  10794. * .setOptional( gl, obj, prop )
  10795. *
  10796. * like .set for an optional property of the object
  10797. *
  10798. */
  10799. const emptyTexture = /*@__PURE__*/ new Texture();
  10800. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  10801. emptyShadowTexture.compareFunction = LessEqualCompare;
  10802. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10803. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10804. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10805. // --- Utilities ---
  10806. // Array Caches (provide typed arrays for temporary by size)
  10807. const arrayCacheF32 = [];
  10808. const arrayCacheI32 = [];
  10809. // Float32Array caches used for uploading Matrix uniforms
  10810. const mat4array = new Float32Array( 16 );
  10811. const mat3array = new Float32Array( 9 );
  10812. const mat2array = new Float32Array( 4 );
  10813. // Flattening for arrays of vectors and matrices
  10814. function flatten( array, nBlocks, blockSize ) {
  10815. const firstElem = array[ 0 ];
  10816. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10817. // unoptimized: ! isNaN( firstElem )
  10818. // see http://jacksondunstan.com/articles/983
  10819. const n = nBlocks * blockSize;
  10820. let r = arrayCacheF32[ n ];
  10821. if ( r === undefined ) {
  10822. r = new Float32Array( n );
  10823. arrayCacheF32[ n ] = r;
  10824. }
  10825. if ( nBlocks !== 0 ) {
  10826. firstElem.toArray( r, 0 );
  10827. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10828. offset += blockSize;
  10829. array[ i ].toArray( r, offset );
  10830. }
  10831. }
  10832. return r;
  10833. }
  10834. function arraysEqual( a, b ) {
  10835. if ( a.length !== b.length ) return false;
  10836. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10837. if ( a[ i ] !== b[ i ] ) return false;
  10838. }
  10839. return true;
  10840. }
  10841. function copyArray( a, b ) {
  10842. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10843. a[ i ] = b[ i ];
  10844. }
  10845. }
  10846. // Texture unit allocation
  10847. function allocTexUnits( textures, n ) {
  10848. let r = arrayCacheI32[ n ];
  10849. if ( r === undefined ) {
  10850. r = new Int32Array( n );
  10851. arrayCacheI32[ n ] = r;
  10852. }
  10853. for ( let i = 0; i !== n; ++ i ) {
  10854. r[ i ] = textures.allocateTextureUnit();
  10855. }
  10856. return r;
  10857. }
  10858. // --- Setters ---
  10859. // Note: Defining these methods externally, because they come in a bunch
  10860. // and this way their names minify.
  10861. // Single scalar
  10862. function setValueV1f( gl, v ) {
  10863. const cache = this.cache;
  10864. if ( cache[ 0 ] === v ) return;
  10865. gl.uniform1f( this.addr, v );
  10866. cache[ 0 ] = v;
  10867. }
  10868. // Single float vector (from flat array or THREE.VectorN)
  10869. function setValueV2f( gl, v ) {
  10870. const cache = this.cache;
  10871. if ( v.x !== undefined ) {
  10872. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10873. gl.uniform2f( this.addr, v.x, v.y );
  10874. cache[ 0 ] = v.x;
  10875. cache[ 1 ] = v.y;
  10876. }
  10877. } else {
  10878. if ( arraysEqual( cache, v ) ) return;
  10879. gl.uniform2fv( this.addr, v );
  10880. copyArray( cache, v );
  10881. }
  10882. }
  10883. function setValueV3f( gl, v ) {
  10884. const cache = this.cache;
  10885. if ( v.x !== undefined ) {
  10886. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10887. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10888. cache[ 0 ] = v.x;
  10889. cache[ 1 ] = v.y;
  10890. cache[ 2 ] = v.z;
  10891. }
  10892. } else if ( v.r !== undefined ) {
  10893. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10894. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10895. cache[ 0 ] = v.r;
  10896. cache[ 1 ] = v.g;
  10897. cache[ 2 ] = v.b;
  10898. }
  10899. } else {
  10900. if ( arraysEqual( cache, v ) ) return;
  10901. gl.uniform3fv( this.addr, v );
  10902. copyArray( cache, v );
  10903. }
  10904. }
  10905. function setValueV4f( gl, v ) {
  10906. const cache = this.cache;
  10907. if ( v.x !== undefined ) {
  10908. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10909. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10910. cache[ 0 ] = v.x;
  10911. cache[ 1 ] = v.y;
  10912. cache[ 2 ] = v.z;
  10913. cache[ 3 ] = v.w;
  10914. }
  10915. } else {
  10916. if ( arraysEqual( cache, v ) ) return;
  10917. gl.uniform4fv( this.addr, v );
  10918. copyArray( cache, v );
  10919. }
  10920. }
  10921. // Single matrix (from flat array or THREE.MatrixN)
  10922. function setValueM2( gl, v ) {
  10923. const cache = this.cache;
  10924. const elements = v.elements;
  10925. if ( elements === undefined ) {
  10926. if ( arraysEqual( cache, v ) ) return;
  10927. gl.uniformMatrix2fv( this.addr, false, v );
  10928. copyArray( cache, v );
  10929. } else {
  10930. if ( arraysEqual( cache, elements ) ) return;
  10931. mat2array.set( elements );
  10932. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10933. copyArray( cache, elements );
  10934. }
  10935. }
  10936. function setValueM3( gl, v ) {
  10937. const cache = this.cache;
  10938. const elements = v.elements;
  10939. if ( elements === undefined ) {
  10940. if ( arraysEqual( cache, v ) ) return;
  10941. gl.uniformMatrix3fv( this.addr, false, v );
  10942. copyArray( cache, v );
  10943. } else {
  10944. if ( arraysEqual( cache, elements ) ) return;
  10945. mat3array.set( elements );
  10946. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10947. copyArray( cache, elements );
  10948. }
  10949. }
  10950. function setValueM4( gl, v ) {
  10951. const cache = this.cache;
  10952. const elements = v.elements;
  10953. if ( elements === undefined ) {
  10954. if ( arraysEqual( cache, v ) ) return;
  10955. gl.uniformMatrix4fv( this.addr, false, v );
  10956. copyArray( cache, v );
  10957. } else {
  10958. if ( arraysEqual( cache, elements ) ) return;
  10959. mat4array.set( elements );
  10960. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10961. copyArray( cache, elements );
  10962. }
  10963. }
  10964. // Single integer / boolean
  10965. function setValueV1i( gl, v ) {
  10966. const cache = this.cache;
  10967. if ( cache[ 0 ] === v ) return;
  10968. gl.uniform1i( this.addr, v );
  10969. cache[ 0 ] = v;
  10970. }
  10971. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10972. function setValueV2i( gl, v ) {
  10973. const cache = this.cache;
  10974. if ( v.x !== undefined ) {
  10975. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10976. gl.uniform2i( this.addr, v.x, v.y );
  10977. cache[ 0 ] = v.x;
  10978. cache[ 1 ] = v.y;
  10979. }
  10980. } else {
  10981. if ( arraysEqual( cache, v ) ) return;
  10982. gl.uniform2iv( this.addr, v );
  10983. copyArray( cache, v );
  10984. }
  10985. }
  10986. function setValueV3i( gl, v ) {
  10987. const cache = this.cache;
  10988. if ( v.x !== undefined ) {
  10989. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10990. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10991. cache[ 0 ] = v.x;
  10992. cache[ 1 ] = v.y;
  10993. cache[ 2 ] = v.z;
  10994. }
  10995. } else {
  10996. if ( arraysEqual( cache, v ) ) return;
  10997. gl.uniform3iv( this.addr, v );
  10998. copyArray( cache, v );
  10999. }
  11000. }
  11001. function setValueV4i( gl, v ) {
  11002. const cache = this.cache;
  11003. if ( v.x !== undefined ) {
  11004. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11005. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11006. cache[ 0 ] = v.x;
  11007. cache[ 1 ] = v.y;
  11008. cache[ 2 ] = v.z;
  11009. cache[ 3 ] = v.w;
  11010. }
  11011. } else {
  11012. if ( arraysEqual( cache, v ) ) return;
  11013. gl.uniform4iv( this.addr, v );
  11014. copyArray( cache, v );
  11015. }
  11016. }
  11017. // Single unsigned integer
  11018. function setValueV1ui( gl, v ) {
  11019. const cache = this.cache;
  11020. if ( cache[ 0 ] === v ) return;
  11021. gl.uniform1ui( this.addr, v );
  11022. cache[ 0 ] = v;
  11023. }
  11024. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11025. function setValueV2ui( gl, v ) {
  11026. const cache = this.cache;
  11027. if ( v.x !== undefined ) {
  11028. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11029. gl.uniform2ui( this.addr, v.x, v.y );
  11030. cache[ 0 ] = v.x;
  11031. cache[ 1 ] = v.y;
  11032. }
  11033. } else {
  11034. if ( arraysEqual( cache, v ) ) return;
  11035. gl.uniform2uiv( this.addr, v );
  11036. copyArray( cache, v );
  11037. }
  11038. }
  11039. function setValueV3ui( gl, v ) {
  11040. const cache = this.cache;
  11041. if ( v.x !== undefined ) {
  11042. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11043. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11044. cache[ 0 ] = v.x;
  11045. cache[ 1 ] = v.y;
  11046. cache[ 2 ] = v.z;
  11047. }
  11048. } else {
  11049. if ( arraysEqual( cache, v ) ) return;
  11050. gl.uniform3uiv( this.addr, v );
  11051. copyArray( cache, v );
  11052. }
  11053. }
  11054. function setValueV4ui( gl, v ) {
  11055. const cache = this.cache;
  11056. if ( v.x !== undefined ) {
  11057. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11058. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11059. cache[ 0 ] = v.x;
  11060. cache[ 1 ] = v.y;
  11061. cache[ 2 ] = v.z;
  11062. cache[ 3 ] = v.w;
  11063. }
  11064. } else {
  11065. if ( arraysEqual( cache, v ) ) return;
  11066. gl.uniform4uiv( this.addr, v );
  11067. copyArray( cache, v );
  11068. }
  11069. }
  11070. // Single texture (2D / Cube)
  11071. function setValueT1( gl, v, textures ) {
  11072. const cache = this.cache;
  11073. const unit = textures.allocateTextureUnit();
  11074. if ( cache[ 0 ] !== unit ) {
  11075. gl.uniform1i( this.addr, unit );
  11076. cache[ 0 ] = unit;
  11077. }
  11078. const emptyTexture2D = ( this.type === gl.SAMPLER_2D_SHADOW ) ? emptyShadowTexture : emptyTexture;
  11079. textures.setTexture2D( v || emptyTexture2D, unit );
  11080. }
  11081. function setValueT3D1( gl, v, textures ) {
  11082. const cache = this.cache;
  11083. const unit = textures.allocateTextureUnit();
  11084. if ( cache[ 0 ] !== unit ) {
  11085. gl.uniform1i( this.addr, unit );
  11086. cache[ 0 ] = unit;
  11087. }
  11088. textures.setTexture3D( v || empty3dTexture, unit );
  11089. }
  11090. function setValueT6( gl, v, textures ) {
  11091. const cache = this.cache;
  11092. const unit = textures.allocateTextureUnit();
  11093. if ( cache[ 0 ] !== unit ) {
  11094. gl.uniform1i( this.addr, unit );
  11095. cache[ 0 ] = unit;
  11096. }
  11097. textures.setTextureCube( v || emptyCubeTexture, unit );
  11098. }
  11099. function setValueT2DArray1( gl, v, textures ) {
  11100. const cache = this.cache;
  11101. const unit = textures.allocateTextureUnit();
  11102. if ( cache[ 0 ] !== unit ) {
  11103. gl.uniform1i( this.addr, unit );
  11104. cache[ 0 ] = unit;
  11105. }
  11106. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11107. }
  11108. // Helper to pick the right setter for the singular case
  11109. function getSingularSetter( type ) {
  11110. switch ( type ) {
  11111. case 0x1406: return setValueV1f; // FLOAT
  11112. case 0x8b50: return setValueV2f; // _VEC2
  11113. case 0x8b51: return setValueV3f; // _VEC3
  11114. case 0x8b52: return setValueV4f; // _VEC4
  11115. case 0x8b5a: return setValueM2; // _MAT2
  11116. case 0x8b5b: return setValueM3; // _MAT3
  11117. case 0x8b5c: return setValueM4; // _MAT4
  11118. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11119. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11120. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11121. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11122. case 0x1405: return setValueV1ui; // UINT
  11123. case 0x8dc6: return setValueV2ui; // _VEC2
  11124. case 0x8dc7: return setValueV3ui; // _VEC3
  11125. case 0x8dc8: return setValueV4ui; // _VEC4
  11126. case 0x8b5e: // SAMPLER_2D
  11127. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11128. case 0x8dca: // INT_SAMPLER_2D
  11129. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11130. case 0x8b62: // SAMPLER_2D_SHADOW
  11131. return setValueT1;
  11132. case 0x8b5f: // SAMPLER_3D
  11133. case 0x8dcb: // INT_SAMPLER_3D
  11134. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11135. return setValueT3D1;
  11136. case 0x8b60: // SAMPLER_CUBE
  11137. case 0x8dcc: // INT_SAMPLER_CUBE
  11138. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11139. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11140. return setValueT6;
  11141. case 0x8dc1: // SAMPLER_2D_ARRAY
  11142. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11143. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11144. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11145. return setValueT2DArray1;
  11146. }
  11147. }
  11148. // Array of scalars
  11149. function setValueV1fArray( gl, v ) {
  11150. gl.uniform1fv( this.addr, v );
  11151. }
  11152. // Array of vectors (from flat array or array of THREE.VectorN)
  11153. function setValueV2fArray( gl, v ) {
  11154. const data = flatten( v, this.size, 2 );
  11155. gl.uniform2fv( this.addr, data );
  11156. }
  11157. function setValueV3fArray( gl, v ) {
  11158. const data = flatten( v, this.size, 3 );
  11159. gl.uniform3fv( this.addr, data );
  11160. }
  11161. function setValueV4fArray( gl, v ) {
  11162. const data = flatten( v, this.size, 4 );
  11163. gl.uniform4fv( this.addr, data );
  11164. }
  11165. // Array of matrices (from flat array or array of THREE.MatrixN)
  11166. function setValueM2Array( gl, v ) {
  11167. const data = flatten( v, this.size, 4 );
  11168. gl.uniformMatrix2fv( this.addr, false, data );
  11169. }
  11170. function setValueM3Array( gl, v ) {
  11171. const data = flatten( v, this.size, 9 );
  11172. gl.uniformMatrix3fv( this.addr, false, data );
  11173. }
  11174. function setValueM4Array( gl, v ) {
  11175. const data = flatten( v, this.size, 16 );
  11176. gl.uniformMatrix4fv( this.addr, false, data );
  11177. }
  11178. // Array of integer / boolean
  11179. function setValueV1iArray( gl, v ) {
  11180. gl.uniform1iv( this.addr, v );
  11181. }
  11182. // Array of integer / boolean vectors (from flat array)
  11183. function setValueV2iArray( gl, v ) {
  11184. gl.uniform2iv( this.addr, v );
  11185. }
  11186. function setValueV3iArray( gl, v ) {
  11187. gl.uniform3iv( this.addr, v );
  11188. }
  11189. function setValueV4iArray( gl, v ) {
  11190. gl.uniform4iv( this.addr, v );
  11191. }
  11192. // Array of unsigned integer
  11193. function setValueV1uiArray( gl, v ) {
  11194. gl.uniform1uiv( this.addr, v );
  11195. }
  11196. // Array of unsigned integer vectors (from flat array)
  11197. function setValueV2uiArray( gl, v ) {
  11198. gl.uniform2uiv( this.addr, v );
  11199. }
  11200. function setValueV3uiArray( gl, v ) {
  11201. gl.uniform3uiv( this.addr, v );
  11202. }
  11203. function setValueV4uiArray( gl, v ) {
  11204. gl.uniform4uiv( this.addr, v );
  11205. }
  11206. // Array of textures (2D / 3D / Cube / 2DArray)
  11207. function setValueT1Array( gl, v, textures ) {
  11208. const cache = this.cache;
  11209. const n = v.length;
  11210. const units = allocTexUnits( textures, n );
  11211. if ( ! arraysEqual( cache, units ) ) {
  11212. gl.uniform1iv( this.addr, units );
  11213. copyArray( cache, units );
  11214. }
  11215. for ( let i = 0; i !== n; ++ i ) {
  11216. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11217. }
  11218. }
  11219. function setValueT3DArray( gl, v, textures ) {
  11220. const cache = this.cache;
  11221. const n = v.length;
  11222. const units = allocTexUnits( textures, n );
  11223. if ( ! arraysEqual( cache, units ) ) {
  11224. gl.uniform1iv( this.addr, units );
  11225. copyArray( cache, units );
  11226. }
  11227. for ( let i = 0; i !== n; ++ i ) {
  11228. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11229. }
  11230. }
  11231. function setValueT6Array( gl, v, textures ) {
  11232. const cache = this.cache;
  11233. const n = v.length;
  11234. const units = allocTexUnits( textures, n );
  11235. if ( ! arraysEqual( cache, units ) ) {
  11236. gl.uniform1iv( this.addr, units );
  11237. copyArray( cache, units );
  11238. }
  11239. for ( let i = 0; i !== n; ++ i ) {
  11240. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11241. }
  11242. }
  11243. function setValueT2DArrayArray( gl, v, textures ) {
  11244. const cache = this.cache;
  11245. const n = v.length;
  11246. const units = allocTexUnits( textures, n );
  11247. if ( ! arraysEqual( cache, units ) ) {
  11248. gl.uniform1iv( this.addr, units );
  11249. copyArray( cache, units );
  11250. }
  11251. for ( let i = 0; i !== n; ++ i ) {
  11252. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11253. }
  11254. }
  11255. // Helper to pick the right setter for a pure (bottom-level) array
  11256. function getPureArraySetter( type ) {
  11257. switch ( type ) {
  11258. case 0x1406: return setValueV1fArray; // FLOAT
  11259. case 0x8b50: return setValueV2fArray; // _VEC2
  11260. case 0x8b51: return setValueV3fArray; // _VEC3
  11261. case 0x8b52: return setValueV4fArray; // _VEC4
  11262. case 0x8b5a: return setValueM2Array; // _MAT2
  11263. case 0x8b5b: return setValueM3Array; // _MAT3
  11264. case 0x8b5c: return setValueM4Array; // _MAT4
  11265. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11266. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11267. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11268. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11269. case 0x1405: return setValueV1uiArray; // UINT
  11270. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11271. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11272. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11273. case 0x8b5e: // SAMPLER_2D
  11274. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11275. case 0x8dca: // INT_SAMPLER_2D
  11276. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11277. case 0x8b62: // SAMPLER_2D_SHADOW
  11278. return setValueT1Array;
  11279. case 0x8b5f: // SAMPLER_3D
  11280. case 0x8dcb: // INT_SAMPLER_3D
  11281. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11282. return setValueT3DArray;
  11283. case 0x8b60: // SAMPLER_CUBE
  11284. case 0x8dcc: // INT_SAMPLER_CUBE
  11285. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11286. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11287. return setValueT6Array;
  11288. case 0x8dc1: // SAMPLER_2D_ARRAY
  11289. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11290. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11291. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11292. return setValueT2DArrayArray;
  11293. }
  11294. }
  11295. // --- Uniform Classes ---
  11296. class SingleUniform {
  11297. constructor( id, activeInfo, addr ) {
  11298. this.id = id;
  11299. this.addr = addr;
  11300. this.cache = [];
  11301. this.type = activeInfo.type;
  11302. this.setValue = getSingularSetter( activeInfo.type );
  11303. // this.path = activeInfo.name; // DEBUG
  11304. }
  11305. }
  11306. class PureArrayUniform {
  11307. constructor( id, activeInfo, addr ) {
  11308. this.id = id;
  11309. this.addr = addr;
  11310. this.cache = [];
  11311. this.type = activeInfo.type;
  11312. this.size = activeInfo.size;
  11313. this.setValue = getPureArraySetter( activeInfo.type );
  11314. // this.path = activeInfo.name; // DEBUG
  11315. }
  11316. }
  11317. class StructuredUniform {
  11318. constructor( id ) {
  11319. this.id = id;
  11320. this.seq = [];
  11321. this.map = {};
  11322. }
  11323. setValue( gl, value, textures ) {
  11324. const seq = this.seq;
  11325. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11326. const u = seq[ i ];
  11327. u.setValue( gl, value[ u.id ], textures );
  11328. }
  11329. }
  11330. }
  11331. // --- Top-level ---
  11332. // Parser - builds up the property tree from the path strings
  11333. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11334. // extracts
  11335. // - the identifier (member name or array index)
  11336. // - followed by an optional right bracket (found when array index)
  11337. // - followed by an optional left bracket or dot (type of subscript)
  11338. //
  11339. // Note: These portions can be read in a non-overlapping fashion and
  11340. // allow straightforward parsing of the hierarchy that WebGL encodes
  11341. // in the uniform names.
  11342. function addUniform( container, uniformObject ) {
  11343. container.seq.push( uniformObject );
  11344. container.map[ uniformObject.id ] = uniformObject;
  11345. }
  11346. function parseUniform( activeInfo, addr, container ) {
  11347. const path = activeInfo.name,
  11348. pathLength = path.length;
  11349. // reset RegExp object, because of the early exit of a previous run
  11350. RePathPart.lastIndex = 0;
  11351. while ( true ) {
  11352. const match = RePathPart.exec( path ),
  11353. matchEnd = RePathPart.lastIndex;
  11354. let id = match[ 1 ];
  11355. const idIsIndex = match[ 2 ] === ']',
  11356. subscript = match[ 3 ];
  11357. if ( idIsIndex ) id = id | 0; // convert to integer
  11358. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11359. // bare name or "pure" bottom-level array "[0]" suffix
  11360. addUniform( container, subscript === undefined ?
  11361. new SingleUniform( id, activeInfo, addr ) :
  11362. new PureArrayUniform( id, activeInfo, addr ) );
  11363. break;
  11364. } else {
  11365. // step into inner node / create it in case it doesn't exist
  11366. const map = container.map;
  11367. let next = map[ id ];
  11368. if ( next === undefined ) {
  11369. next = new StructuredUniform( id );
  11370. addUniform( container, next );
  11371. }
  11372. container = next;
  11373. }
  11374. }
  11375. }
  11376. // Root Container
  11377. class WebGLUniforms {
  11378. constructor( gl, program ) {
  11379. this.seq = [];
  11380. this.map = {};
  11381. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11382. for ( let i = 0; i < n; ++ i ) {
  11383. const info = gl.getActiveUniform( program, i ),
  11384. addr = gl.getUniformLocation( program, info.name );
  11385. parseUniform( info, addr, this );
  11386. }
  11387. }
  11388. setValue( gl, name, value, textures ) {
  11389. const u = this.map[ name ];
  11390. if ( u !== undefined ) u.setValue( gl, value, textures );
  11391. }
  11392. setOptional( gl, object, name ) {
  11393. const v = object[ name ];
  11394. if ( v !== undefined ) this.setValue( gl, name, v );
  11395. }
  11396. static upload( gl, seq, values, textures ) {
  11397. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11398. const u = seq[ i ],
  11399. v = values[ u.id ];
  11400. if ( v.needsUpdate !== false ) {
  11401. // note: always updating when .needsUpdate is undefined
  11402. u.setValue( gl, v.value, textures );
  11403. }
  11404. }
  11405. }
  11406. static seqWithValue( seq, values ) {
  11407. const r = [];
  11408. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11409. const u = seq[ i ];
  11410. if ( u.id in values ) r.push( u );
  11411. }
  11412. return r;
  11413. }
  11414. }
  11415. function WebGLShader( gl, type, string ) {
  11416. const shader = gl.createShader( type );
  11417. gl.shaderSource( shader, string );
  11418. gl.compileShader( shader );
  11419. return shader;
  11420. }
  11421. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  11422. const COMPLETION_STATUS_KHR = 0x91B1;
  11423. let programIdCount = 0;
  11424. function handleSource( string, errorLine ) {
  11425. const lines = string.split( '\n' );
  11426. const lines2 = [];
  11427. const from = Math.max( errorLine - 6, 0 );
  11428. const to = Math.min( errorLine + 6, lines.length );
  11429. for ( let i = from; i < to; i ++ ) {
  11430. const line = i + 1;
  11431. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11432. }
  11433. return lines2.join( '\n' );
  11434. }
  11435. function getEncodingComponents( colorSpace ) {
  11436. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11437. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11438. let gamutMapping;
  11439. if ( workingPrimaries === encodingPrimaries ) {
  11440. gamutMapping = '';
  11441. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11442. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11443. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11444. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11445. }
  11446. switch ( colorSpace ) {
  11447. case LinearSRGBColorSpace:
  11448. case LinearDisplayP3ColorSpace:
  11449. return [ gamutMapping, 'LinearTransferOETF' ];
  11450. case SRGBColorSpace:
  11451. case DisplayP3ColorSpace:
  11452. return [ gamutMapping, 'sRGBTransferOETF' ];
  11453. default:
  11454. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11455. return [ gamutMapping, 'LinearTransferOETF' ];
  11456. }
  11457. }
  11458. function getShaderErrors( gl, shader, type ) {
  11459. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11460. const errors = gl.getShaderInfoLog( shader ).trim();
  11461. if ( status && errors === '' ) return '';
  11462. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11463. if ( errorMatches ) {
  11464. // --enable-privileged-webgl-extension
  11465. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11466. const errorLine = parseInt( errorMatches[ 1 ] );
  11467. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11468. } else {
  11469. return errors;
  11470. }
  11471. }
  11472. function getTexelEncodingFunction( functionName, colorSpace ) {
  11473. const components = getEncodingComponents( colorSpace );
  11474. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11475. }
  11476. function getToneMappingFunction( functionName, toneMapping ) {
  11477. let toneMappingName;
  11478. switch ( toneMapping ) {
  11479. case LinearToneMapping:
  11480. toneMappingName = 'Linear';
  11481. break;
  11482. case ReinhardToneMapping:
  11483. toneMappingName = 'Reinhard';
  11484. break;
  11485. case CineonToneMapping:
  11486. toneMappingName = 'OptimizedCineon';
  11487. break;
  11488. case ACESFilmicToneMapping:
  11489. toneMappingName = 'ACESFilmic';
  11490. break;
  11491. case AgXToneMapping:
  11492. toneMappingName = 'AgX';
  11493. break;
  11494. case NeutralToneMapping:
  11495. toneMappingName = 'Neutral';
  11496. break;
  11497. case CustomToneMapping:
  11498. toneMappingName = 'Custom';
  11499. break;
  11500. default:
  11501. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11502. toneMappingName = 'Linear';
  11503. }
  11504. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11505. }
  11506. function generateVertexExtensions( parameters ) {
  11507. const chunks = [
  11508. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  11509. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  11510. ];
  11511. return chunks.filter( filterEmptyLine ).join( '\n' );
  11512. }
  11513. function generateDefines( defines ) {
  11514. const chunks = [];
  11515. for ( const name in defines ) {
  11516. const value = defines[ name ];
  11517. if ( value === false ) continue;
  11518. chunks.push( '#define ' + name + ' ' + value );
  11519. }
  11520. return chunks.join( '\n' );
  11521. }
  11522. function fetchAttributeLocations( gl, program ) {
  11523. const attributes = {};
  11524. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11525. for ( let i = 0; i < n; i ++ ) {
  11526. const info = gl.getActiveAttrib( program, i );
  11527. const name = info.name;
  11528. let locationSize = 1;
  11529. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11530. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11531. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11532. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11533. attributes[ name ] = {
  11534. type: info.type,
  11535. location: gl.getAttribLocation( program, name ),
  11536. locationSize: locationSize
  11537. };
  11538. }
  11539. return attributes;
  11540. }
  11541. function filterEmptyLine( string ) {
  11542. return string !== '';
  11543. }
  11544. function replaceLightNums( string, parameters ) {
  11545. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11546. return string
  11547. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11548. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11549. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11550. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11551. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11552. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11553. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11554. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11555. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11556. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11557. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11558. }
  11559. function replaceClippingPlaneNums( string, parameters ) {
  11560. return string
  11561. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11562. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11563. }
  11564. // Resolve Includes
  11565. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11566. function resolveIncludes( string ) {
  11567. return string.replace( includePattern, includeReplacer );
  11568. }
  11569. const shaderChunkMap = new Map( [
  11570. [ 'encodings_fragment', 'colorspace_fragment' ], // @deprecated, r154
  11571. [ 'encodings_pars_fragment', 'colorspace_pars_fragment' ], // @deprecated, r154
  11572. [ 'output_fragment', 'opaque_fragment' ], // @deprecated, r154
  11573. ] );
  11574. function includeReplacer( match, include ) {
  11575. let string = ShaderChunk[ include ];
  11576. if ( string === undefined ) {
  11577. const newInclude = shaderChunkMap.get( include );
  11578. if ( newInclude !== undefined ) {
  11579. string = ShaderChunk[ newInclude ];
  11580. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11581. } else {
  11582. throw new Error( 'Can not resolve #include <' + include + '>' );
  11583. }
  11584. }
  11585. return resolveIncludes( string );
  11586. }
  11587. // Unroll Loops
  11588. 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;
  11589. function unrollLoops( string ) {
  11590. return string.replace( unrollLoopPattern, loopReplacer );
  11591. }
  11592. function loopReplacer( match, start, end, snippet ) {
  11593. let string = '';
  11594. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11595. string += snippet
  11596. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11597. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11598. }
  11599. return string;
  11600. }
  11601. //
  11602. function generatePrecision( parameters ) {
  11603. let precisionstring = `precision ${parameters.precision} float;
  11604. precision ${parameters.precision} int;
  11605. precision ${parameters.precision} sampler2D;
  11606. precision ${parameters.precision} samplerCube;
  11607. precision ${parameters.precision} sampler3D;
  11608. precision ${parameters.precision} sampler2DArray;
  11609. precision ${parameters.precision} sampler2DShadow;
  11610. precision ${parameters.precision} samplerCubeShadow;
  11611. precision ${parameters.precision} sampler2DArrayShadow;
  11612. precision ${parameters.precision} isampler2D;
  11613. precision ${parameters.precision} isampler3D;
  11614. precision ${parameters.precision} isamplerCube;
  11615. precision ${parameters.precision} isampler2DArray;
  11616. precision ${parameters.precision} usampler2D;
  11617. precision ${parameters.precision} usampler3D;
  11618. precision ${parameters.precision} usamplerCube;
  11619. precision ${parameters.precision} usampler2DArray;
  11620. `;
  11621. if ( parameters.precision === 'highp' ) {
  11622. precisionstring += '\n#define HIGH_PRECISION';
  11623. } else if ( parameters.precision === 'mediump' ) {
  11624. precisionstring += '\n#define MEDIUM_PRECISION';
  11625. } else if ( parameters.precision === 'lowp' ) {
  11626. precisionstring += '\n#define LOW_PRECISION';
  11627. }
  11628. return precisionstring;
  11629. }
  11630. function generateShadowMapTypeDefine( parameters ) {
  11631. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11632. if ( parameters.shadowMapType === PCFShadowMap ) {
  11633. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11634. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11635. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11636. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11637. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11638. }
  11639. return shadowMapTypeDefine;
  11640. }
  11641. function generateEnvMapTypeDefine( parameters ) {
  11642. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11643. if ( parameters.envMap ) {
  11644. switch ( parameters.envMapMode ) {
  11645. case CubeReflectionMapping:
  11646. case CubeRefractionMapping:
  11647. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11648. break;
  11649. case CubeUVReflectionMapping:
  11650. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11651. break;
  11652. }
  11653. }
  11654. return envMapTypeDefine;
  11655. }
  11656. function generateEnvMapModeDefine( parameters ) {
  11657. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11658. if ( parameters.envMap ) {
  11659. switch ( parameters.envMapMode ) {
  11660. case CubeRefractionMapping:
  11661. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11662. break;
  11663. }
  11664. }
  11665. return envMapModeDefine;
  11666. }
  11667. function generateEnvMapBlendingDefine( parameters ) {
  11668. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11669. if ( parameters.envMap ) {
  11670. switch ( parameters.combine ) {
  11671. case MultiplyOperation:
  11672. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11673. break;
  11674. case MixOperation:
  11675. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11676. break;
  11677. case AddOperation:
  11678. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11679. break;
  11680. }
  11681. }
  11682. return envMapBlendingDefine;
  11683. }
  11684. function generateCubeUVSize( parameters ) {
  11685. const imageHeight = parameters.envMapCubeUVHeight;
  11686. if ( imageHeight === null ) return null;
  11687. const maxMip = Math.log2( imageHeight ) - 2;
  11688. const texelHeight = 1.0 / imageHeight;
  11689. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11690. return { texelWidth, texelHeight, maxMip };
  11691. }
  11692. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11693. // TODO Send this event to Three.js DevTools
  11694. // console.log( 'WebGLProgram', cacheKey );
  11695. const gl = renderer.getContext();
  11696. const defines = parameters.defines;
  11697. let vertexShader = parameters.vertexShader;
  11698. let fragmentShader = parameters.fragmentShader;
  11699. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11700. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11701. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11702. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11703. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11704. const customVertexExtensions = generateVertexExtensions( parameters );
  11705. const customDefines = generateDefines( defines );
  11706. const program = gl.createProgram();
  11707. let prefixVertex, prefixFragment;
  11708. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11709. if ( parameters.isRawShaderMaterial ) {
  11710. prefixVertex = [
  11711. '#define SHADER_TYPE ' + parameters.shaderType,
  11712. '#define SHADER_NAME ' + parameters.shaderName,
  11713. customDefines
  11714. ].filter( filterEmptyLine ).join( '\n' );
  11715. if ( prefixVertex.length > 0 ) {
  11716. prefixVertex += '\n';
  11717. }
  11718. prefixFragment = [
  11719. '#define SHADER_TYPE ' + parameters.shaderType,
  11720. '#define SHADER_NAME ' + parameters.shaderName,
  11721. customDefines
  11722. ].filter( filterEmptyLine ).join( '\n' );
  11723. if ( prefixFragment.length > 0 ) {
  11724. prefixFragment += '\n';
  11725. }
  11726. } else {
  11727. prefixVertex = [
  11728. generatePrecision( parameters ),
  11729. '#define SHADER_TYPE ' + parameters.shaderType,
  11730. '#define SHADER_NAME ' + parameters.shaderName,
  11731. customDefines,
  11732. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  11733. parameters.batching ? '#define USE_BATCHING' : '',
  11734. parameters.instancing ? '#define USE_INSTANCING' : '',
  11735. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11736. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  11737. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11738. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11739. parameters.map ? '#define USE_MAP' : '',
  11740. parameters.envMap ? '#define USE_ENVMAP' : '',
  11741. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11742. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11743. parameters.aoMap ? '#define USE_AOMAP' : '',
  11744. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11745. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11746. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11747. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11748. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11749. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11750. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11751. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11752. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11753. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11754. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11755. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11756. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11757. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11758. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11759. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11760. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11761. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11762. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11763. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11764. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11765. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11766. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11767. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11768. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11769. //
  11770. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11771. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11772. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11773. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11774. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11775. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11776. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11777. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11778. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11779. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11780. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11781. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11782. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11783. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11784. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11785. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11786. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11787. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11788. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11789. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11790. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11791. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11792. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11793. //
  11794. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11795. parameters.vertexColors ? '#define USE_COLOR' : '',
  11796. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11797. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11798. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11799. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11800. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11801. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11802. parameters.skinning ? '#define USE_SKINNING' : '',
  11803. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11804. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11805. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  11806. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11807. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11808. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11809. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11810. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11811. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11812. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11813. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11814. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11815. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11816. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11817. 'uniform mat4 modelMatrix;',
  11818. 'uniform mat4 modelViewMatrix;',
  11819. 'uniform mat4 projectionMatrix;',
  11820. 'uniform mat4 viewMatrix;',
  11821. 'uniform mat3 normalMatrix;',
  11822. 'uniform vec3 cameraPosition;',
  11823. 'uniform bool isOrthographic;',
  11824. '#ifdef USE_INSTANCING',
  11825. ' attribute mat4 instanceMatrix;',
  11826. '#endif',
  11827. '#ifdef USE_INSTANCING_COLOR',
  11828. ' attribute vec3 instanceColor;',
  11829. '#endif',
  11830. '#ifdef USE_INSTANCING_MORPH',
  11831. ' uniform sampler2D morphTexture;',
  11832. '#endif',
  11833. 'attribute vec3 position;',
  11834. 'attribute vec3 normal;',
  11835. 'attribute vec2 uv;',
  11836. '#ifdef USE_UV1',
  11837. ' attribute vec2 uv1;',
  11838. '#endif',
  11839. '#ifdef USE_UV2',
  11840. ' attribute vec2 uv2;',
  11841. '#endif',
  11842. '#ifdef USE_UV3',
  11843. ' attribute vec2 uv3;',
  11844. '#endif',
  11845. '#ifdef USE_TANGENT',
  11846. ' attribute vec4 tangent;',
  11847. '#endif',
  11848. '#if defined( USE_COLOR_ALPHA )',
  11849. ' attribute vec4 color;',
  11850. '#elif defined( USE_COLOR )',
  11851. ' attribute vec3 color;',
  11852. '#endif',
  11853. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11854. ' attribute vec3 morphTarget0;',
  11855. ' attribute vec3 morphTarget1;',
  11856. ' attribute vec3 morphTarget2;',
  11857. ' attribute vec3 morphTarget3;',
  11858. ' #ifdef USE_MORPHNORMALS',
  11859. ' attribute vec3 morphNormal0;',
  11860. ' attribute vec3 morphNormal1;',
  11861. ' attribute vec3 morphNormal2;',
  11862. ' attribute vec3 morphNormal3;',
  11863. ' #else',
  11864. ' attribute vec3 morphTarget4;',
  11865. ' attribute vec3 morphTarget5;',
  11866. ' attribute vec3 morphTarget6;',
  11867. ' attribute vec3 morphTarget7;',
  11868. ' #endif',
  11869. '#endif',
  11870. '#ifdef USE_SKINNING',
  11871. ' attribute vec4 skinIndex;',
  11872. ' attribute vec4 skinWeight;',
  11873. '#endif',
  11874. '\n'
  11875. ].filter( filterEmptyLine ).join( '\n' );
  11876. prefixFragment = [
  11877. generatePrecision( parameters ),
  11878. '#define SHADER_TYPE ' + parameters.shaderType,
  11879. '#define SHADER_NAME ' + parameters.shaderName,
  11880. customDefines,
  11881. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11882. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11883. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  11884. parameters.map ? '#define USE_MAP' : '',
  11885. parameters.matcap ? '#define USE_MATCAP' : '',
  11886. parameters.envMap ? '#define USE_ENVMAP' : '',
  11887. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11888. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11889. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11890. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11891. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11892. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11893. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11894. parameters.aoMap ? '#define USE_AOMAP' : '',
  11895. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11896. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11897. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11898. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11899. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11900. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11901. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11902. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11903. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11904. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11905. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11906. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11907. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11908. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11909. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11910. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11911. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11912. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11913. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11914. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11915. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11916. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11917. parameters.sheen ? '#define USE_SHEEN' : '',
  11918. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11919. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11920. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11921. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11922. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11923. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11924. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11925. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11926. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11927. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11928. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11929. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11930. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11931. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11932. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11933. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11934. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11935. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11936. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11937. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11938. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11939. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11940. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11941. 'uniform mat4 viewMatrix;',
  11942. 'uniform vec3 cameraPosition;',
  11943. 'uniform bool isOrthographic;',
  11944. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11945. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11946. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11947. parameters.dithering ? '#define DITHERING' : '',
  11948. parameters.opaque ? '#define OPAQUE' : '',
  11949. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11950. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  11951. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11952. '\n'
  11953. ].filter( filterEmptyLine ).join( '\n' );
  11954. }
  11955. vertexShader = resolveIncludes( vertexShader );
  11956. vertexShader = replaceLightNums( vertexShader, parameters );
  11957. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11958. fragmentShader = resolveIncludes( fragmentShader );
  11959. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11960. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11961. vertexShader = unrollLoops( vertexShader );
  11962. fragmentShader = unrollLoops( fragmentShader );
  11963. if ( parameters.isRawShaderMaterial !== true ) {
  11964. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11965. versionString = '#version 300 es\n';
  11966. prefixVertex = [
  11967. customVertexExtensions,
  11968. '#define attribute in',
  11969. '#define varying out',
  11970. '#define texture2D texture'
  11971. ].join( '\n' ) + '\n' + prefixVertex;
  11972. prefixFragment = [
  11973. '#define varying in',
  11974. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11975. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11976. '#define gl_FragDepthEXT gl_FragDepth',
  11977. '#define texture2D texture',
  11978. '#define textureCube texture',
  11979. '#define texture2DProj textureProj',
  11980. '#define texture2DLodEXT textureLod',
  11981. '#define texture2DProjLodEXT textureProjLod',
  11982. '#define textureCubeLodEXT textureLod',
  11983. '#define texture2DGradEXT textureGrad',
  11984. '#define texture2DProjGradEXT textureProjGrad',
  11985. '#define textureCubeGradEXT textureGrad'
  11986. ].join( '\n' ) + '\n' + prefixFragment;
  11987. }
  11988. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11989. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11990. // console.log( '*VERTEX*', vertexGlsl );
  11991. // console.log( '*FRAGMENT*', fragmentGlsl );
  11992. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11993. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11994. gl.attachShader( program, glVertexShader );
  11995. gl.attachShader( program, glFragmentShader );
  11996. // Force a particular attribute to index 0.
  11997. if ( parameters.index0AttributeName !== undefined ) {
  11998. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11999. } else if ( parameters.morphTargets === true ) {
  12000. // programs with morphTargets displace position out of attribute 0
  12001. gl.bindAttribLocation( program, 0, 'position' );
  12002. }
  12003. gl.linkProgram( program );
  12004. function onFirstUse( self ) {
  12005. // check for link errors
  12006. if ( renderer.debug.checkShaderErrors ) {
  12007. const programLog = gl.getProgramInfoLog( program ).trim();
  12008. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12009. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12010. let runnable = true;
  12011. let haveDiagnostics = true;
  12012. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12013. runnable = false;
  12014. if ( typeof renderer.debug.onShaderError === 'function' ) {
  12015. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  12016. } else {
  12017. // default error reporting
  12018. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12019. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12020. console.error(
  12021. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12022. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  12023. 'Material Name: ' + self.name + '\n' +
  12024. 'Material Type: ' + self.type + '\n\n' +
  12025. 'Program Info Log: ' + programLog + '\n' +
  12026. vertexErrors + '\n' +
  12027. fragmentErrors
  12028. );
  12029. }
  12030. } else if ( programLog !== '' ) {
  12031. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12032. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12033. haveDiagnostics = false;
  12034. }
  12035. if ( haveDiagnostics ) {
  12036. self.diagnostics = {
  12037. runnable: runnable,
  12038. programLog: programLog,
  12039. vertexShader: {
  12040. log: vertexLog,
  12041. prefix: prefixVertex
  12042. },
  12043. fragmentShader: {
  12044. log: fragmentLog,
  12045. prefix: prefixFragment
  12046. }
  12047. };
  12048. }
  12049. }
  12050. // Clean up
  12051. // Crashes in iOS9 and iOS10. #18402
  12052. // gl.detachShader( program, glVertexShader );
  12053. // gl.detachShader( program, glFragmentShader );
  12054. gl.deleteShader( glVertexShader );
  12055. gl.deleteShader( glFragmentShader );
  12056. cachedUniforms = new WebGLUniforms( gl, program );
  12057. cachedAttributes = fetchAttributeLocations( gl, program );
  12058. }
  12059. // set up caching for uniform locations
  12060. let cachedUniforms;
  12061. this.getUniforms = function () {
  12062. if ( cachedUniforms === undefined ) {
  12063. // Populates cachedUniforms and cachedAttributes
  12064. onFirstUse( this );
  12065. }
  12066. return cachedUniforms;
  12067. };
  12068. // set up caching for attribute locations
  12069. let cachedAttributes;
  12070. this.getAttributes = function () {
  12071. if ( cachedAttributes === undefined ) {
  12072. // Populates cachedAttributes and cachedUniforms
  12073. onFirstUse( this );
  12074. }
  12075. return cachedAttributes;
  12076. };
  12077. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  12078. // flag the program as ready immediately. It may cause a stall when it's first used.
  12079. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  12080. this.isReady = function () {
  12081. if ( programReady === false ) {
  12082. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  12083. }
  12084. return programReady;
  12085. };
  12086. // free resource
  12087. this.destroy = function () {
  12088. bindingStates.releaseStatesOfProgram( this );
  12089. gl.deleteProgram( program );
  12090. this.program = undefined;
  12091. };
  12092. //
  12093. this.type = parameters.shaderType;
  12094. this.name = parameters.shaderName;
  12095. this.id = programIdCount ++;
  12096. this.cacheKey = cacheKey;
  12097. this.usedTimes = 1;
  12098. this.program = program;
  12099. this.vertexShader = glVertexShader;
  12100. this.fragmentShader = glFragmentShader;
  12101. return this;
  12102. }
  12103. let _id$1 = 0;
  12104. class WebGLShaderCache {
  12105. constructor() {
  12106. this.shaderCache = new Map();
  12107. this.materialCache = new Map();
  12108. }
  12109. update( material ) {
  12110. const vertexShader = material.vertexShader;
  12111. const fragmentShader = material.fragmentShader;
  12112. const vertexShaderStage = this._getShaderStage( vertexShader );
  12113. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12114. const materialShaders = this._getShaderCacheForMaterial( material );
  12115. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12116. materialShaders.add( vertexShaderStage );
  12117. vertexShaderStage.usedTimes ++;
  12118. }
  12119. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12120. materialShaders.add( fragmentShaderStage );
  12121. fragmentShaderStage.usedTimes ++;
  12122. }
  12123. return this;
  12124. }
  12125. remove( material ) {
  12126. const materialShaders = this.materialCache.get( material );
  12127. for ( const shaderStage of materialShaders ) {
  12128. shaderStage.usedTimes --;
  12129. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12130. }
  12131. this.materialCache.delete( material );
  12132. return this;
  12133. }
  12134. getVertexShaderID( material ) {
  12135. return this._getShaderStage( material.vertexShader ).id;
  12136. }
  12137. getFragmentShaderID( material ) {
  12138. return this._getShaderStage( material.fragmentShader ).id;
  12139. }
  12140. dispose() {
  12141. this.shaderCache.clear();
  12142. this.materialCache.clear();
  12143. }
  12144. _getShaderCacheForMaterial( material ) {
  12145. const cache = this.materialCache;
  12146. let set = cache.get( material );
  12147. if ( set === undefined ) {
  12148. set = new Set();
  12149. cache.set( material, set );
  12150. }
  12151. return set;
  12152. }
  12153. _getShaderStage( code ) {
  12154. const cache = this.shaderCache;
  12155. let stage = cache.get( code );
  12156. if ( stage === undefined ) {
  12157. stage = new WebGLShaderStage( code );
  12158. cache.set( code, stage );
  12159. }
  12160. return stage;
  12161. }
  12162. }
  12163. class WebGLShaderStage {
  12164. constructor( code ) {
  12165. this.id = _id$1 ++;
  12166. this.code = code;
  12167. this.usedTimes = 0;
  12168. }
  12169. }
  12170. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12171. const _programLayers = new Layers();
  12172. const _customShaders = new WebGLShaderCache();
  12173. const _activeChannels = new Set();
  12174. const programs = [];
  12175. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12176. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12177. let precision = capabilities.precision;
  12178. const shaderIDs = {
  12179. MeshDepthMaterial: 'depth',
  12180. MeshDistanceMaterial: 'distanceRGBA',
  12181. MeshNormalMaterial: 'normal',
  12182. MeshBasicMaterial: 'basic',
  12183. MeshLambertMaterial: 'lambert',
  12184. MeshPhongMaterial: 'phong',
  12185. MeshToonMaterial: 'toon',
  12186. MeshStandardMaterial: 'physical',
  12187. MeshPhysicalMaterial: 'physical',
  12188. MeshMatcapMaterial: 'matcap',
  12189. LineBasicMaterial: 'basic',
  12190. LineDashedMaterial: 'dashed',
  12191. PointsMaterial: 'points',
  12192. ShadowMaterial: 'shadow',
  12193. SpriteMaterial: 'sprite'
  12194. };
  12195. function getChannel( value ) {
  12196. _activeChannels.add( value );
  12197. if ( value === 0 ) return 'uv';
  12198. return `uv${ value }`;
  12199. }
  12200. function getParameters( material, lights, shadows, scene, object ) {
  12201. const fog = scene.fog;
  12202. const geometry = object.geometry;
  12203. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12204. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12205. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12206. const shaderID = shaderIDs[ material.type ];
  12207. // heuristics to create shader parameters according to lights in the scene
  12208. // (not to blow over maxLights budget)
  12209. if ( material.precision !== null ) {
  12210. precision = capabilities.getMaxPrecision( material.precision );
  12211. if ( precision !== material.precision ) {
  12212. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12213. }
  12214. }
  12215. //
  12216. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12217. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12218. let morphTextureStride = 0;
  12219. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12220. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12221. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12222. //
  12223. let vertexShader, fragmentShader;
  12224. let customVertexShaderID, customFragmentShaderID;
  12225. if ( shaderID ) {
  12226. const shader = ShaderLib[ shaderID ];
  12227. vertexShader = shader.vertexShader;
  12228. fragmentShader = shader.fragmentShader;
  12229. } else {
  12230. vertexShader = material.vertexShader;
  12231. fragmentShader = material.fragmentShader;
  12232. _customShaders.update( material );
  12233. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12234. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12235. }
  12236. const currentRenderTarget = renderer.getRenderTarget();
  12237. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12238. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  12239. const HAS_MAP = !! material.map;
  12240. const HAS_MATCAP = !! material.matcap;
  12241. const HAS_ENVMAP = !! envMap;
  12242. const HAS_AOMAP = !! material.aoMap;
  12243. const HAS_LIGHTMAP = !! material.lightMap;
  12244. const HAS_BUMPMAP = !! material.bumpMap;
  12245. const HAS_NORMALMAP = !! material.normalMap;
  12246. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12247. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12248. const HAS_METALNESSMAP = !! material.metalnessMap;
  12249. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12250. const HAS_ANISOTROPY = material.anisotropy > 0;
  12251. const HAS_CLEARCOAT = material.clearcoat > 0;
  12252. const HAS_IRIDESCENCE = material.iridescence > 0;
  12253. const HAS_SHEEN = material.sheen > 0;
  12254. const HAS_TRANSMISSION = material.transmission > 0;
  12255. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12256. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12257. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12258. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12259. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12260. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12261. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12262. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12263. const HAS_SPECULARMAP = !! material.specularMap;
  12264. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12265. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12266. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12267. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12268. const HAS_GRADIENTMAP = !! material.gradientMap;
  12269. const HAS_ALPHAMAP = !! material.alphaMap;
  12270. const HAS_ALPHATEST = material.alphaTest > 0;
  12271. const HAS_ALPHAHASH = !! material.alphaHash;
  12272. const HAS_EXTENSIONS = !! material.extensions;
  12273. let toneMapping = NoToneMapping;
  12274. if ( material.toneMapped ) {
  12275. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12276. toneMapping = renderer.toneMapping;
  12277. }
  12278. }
  12279. const parameters = {
  12280. shaderID: shaderID,
  12281. shaderType: material.type,
  12282. shaderName: material.name,
  12283. vertexShader: vertexShader,
  12284. fragmentShader: fragmentShader,
  12285. defines: material.defines,
  12286. customVertexShaderID: customVertexShaderID,
  12287. customFragmentShaderID: customFragmentShaderID,
  12288. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12289. glslVersion: material.glslVersion,
  12290. precision: precision,
  12291. batching: IS_BATCHEDMESH,
  12292. instancing: IS_INSTANCEDMESH,
  12293. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12294. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  12295. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12296. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12297. alphaToCoverage: !! material.alphaToCoverage,
  12298. map: HAS_MAP,
  12299. matcap: HAS_MATCAP,
  12300. envMap: HAS_ENVMAP,
  12301. envMapMode: HAS_ENVMAP && envMap.mapping,
  12302. envMapCubeUVHeight: envMapCubeUVHeight,
  12303. aoMap: HAS_AOMAP,
  12304. lightMap: HAS_LIGHTMAP,
  12305. bumpMap: HAS_BUMPMAP,
  12306. normalMap: HAS_NORMALMAP,
  12307. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12308. emissiveMap: HAS_EMISSIVEMAP,
  12309. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12310. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12311. metalnessMap: HAS_METALNESSMAP,
  12312. roughnessMap: HAS_ROUGHNESSMAP,
  12313. anisotropy: HAS_ANISOTROPY,
  12314. anisotropyMap: HAS_ANISOTROPYMAP,
  12315. clearcoat: HAS_CLEARCOAT,
  12316. clearcoatMap: HAS_CLEARCOATMAP,
  12317. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12318. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12319. iridescence: HAS_IRIDESCENCE,
  12320. iridescenceMap: HAS_IRIDESCENCEMAP,
  12321. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12322. sheen: HAS_SHEEN,
  12323. sheenColorMap: HAS_SHEEN_COLORMAP,
  12324. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12325. specularMap: HAS_SPECULARMAP,
  12326. specularColorMap: HAS_SPECULAR_COLORMAP,
  12327. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12328. transmission: HAS_TRANSMISSION,
  12329. transmissionMap: HAS_TRANSMISSIONMAP,
  12330. thicknessMap: HAS_THICKNESSMAP,
  12331. gradientMap: HAS_GRADIENTMAP,
  12332. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  12333. alphaMap: HAS_ALPHAMAP,
  12334. alphaTest: HAS_ALPHATEST,
  12335. alphaHash: HAS_ALPHAHASH,
  12336. combine: material.combine,
  12337. //
  12338. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12339. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12340. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12341. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12342. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12343. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12344. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12345. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12346. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12347. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12348. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12349. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12350. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12351. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12352. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12353. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12354. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12355. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12356. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12357. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12358. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12359. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12360. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12361. //
  12362. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12363. vertexColors: material.vertexColors,
  12364. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12365. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12366. fog: !! fog,
  12367. useFog: material.fog === true,
  12368. fogExp2: ( !! fog && fog.isFogExp2 ),
  12369. flatShading: material.flatShading === true,
  12370. sizeAttenuation: material.sizeAttenuation === true,
  12371. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12372. skinning: object.isSkinnedMesh === true,
  12373. morphTargets: geometry.morphAttributes.position !== undefined,
  12374. morphNormals: geometry.morphAttributes.normal !== undefined,
  12375. morphColors: geometry.morphAttributes.color !== undefined,
  12376. morphTargetsCount: morphTargetsCount,
  12377. morphTextureStride: morphTextureStride,
  12378. numDirLights: lights.directional.length,
  12379. numPointLights: lights.point.length,
  12380. numSpotLights: lights.spot.length,
  12381. numSpotLightMaps: lights.spotLightMap.length,
  12382. numRectAreaLights: lights.rectArea.length,
  12383. numHemiLights: lights.hemi.length,
  12384. numDirLightShadows: lights.directionalShadowMap.length,
  12385. numPointLightShadows: lights.pointShadowMap.length,
  12386. numSpotLightShadows: lights.spotShadowMap.length,
  12387. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12388. numLightProbes: lights.numLightProbes,
  12389. numClippingPlanes: clipping.numPlanes,
  12390. numClipIntersection: clipping.numIntersection,
  12391. dithering: material.dithering,
  12392. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12393. shadowMapType: renderer.shadowMap.type,
  12394. toneMapping: toneMapping,
  12395. useLegacyLights: renderer._useLegacyLights,
  12396. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12397. premultipliedAlpha: material.premultipliedAlpha,
  12398. doubleSided: material.side === DoubleSide,
  12399. flipSided: material.side === BackSide,
  12400. useDepthPacking: material.depthPacking >= 0,
  12401. depthPacking: material.depthPacking || 0,
  12402. index0AttributeName: material.index0AttributeName,
  12403. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  12404. extensionMultiDraw: HAS_EXTENSIONS && material.extensions.multiDraw === true && extensions.has( 'WEBGL_multi_draw' ),
  12405. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  12406. customProgramCacheKey: material.customProgramCacheKey()
  12407. };
  12408. // the usage of getChannel() determines the active texture channels for this shader
  12409. parameters.vertexUv1s = _activeChannels.has( 1 );
  12410. parameters.vertexUv2s = _activeChannels.has( 2 );
  12411. parameters.vertexUv3s = _activeChannels.has( 3 );
  12412. _activeChannels.clear();
  12413. return parameters;
  12414. }
  12415. function getProgramCacheKey( parameters ) {
  12416. const array = [];
  12417. if ( parameters.shaderID ) {
  12418. array.push( parameters.shaderID );
  12419. } else {
  12420. array.push( parameters.customVertexShaderID );
  12421. array.push( parameters.customFragmentShaderID );
  12422. }
  12423. if ( parameters.defines !== undefined ) {
  12424. for ( const name in parameters.defines ) {
  12425. array.push( name );
  12426. array.push( parameters.defines[ name ] );
  12427. }
  12428. }
  12429. if ( parameters.isRawShaderMaterial === false ) {
  12430. getProgramCacheKeyParameters( array, parameters );
  12431. getProgramCacheKeyBooleans( array, parameters );
  12432. array.push( renderer.outputColorSpace );
  12433. }
  12434. array.push( parameters.customProgramCacheKey );
  12435. return array.join();
  12436. }
  12437. function getProgramCacheKeyParameters( array, parameters ) {
  12438. array.push( parameters.precision );
  12439. array.push( parameters.outputColorSpace );
  12440. array.push( parameters.envMapMode );
  12441. array.push( parameters.envMapCubeUVHeight );
  12442. array.push( parameters.mapUv );
  12443. array.push( parameters.alphaMapUv );
  12444. array.push( parameters.lightMapUv );
  12445. array.push( parameters.aoMapUv );
  12446. array.push( parameters.bumpMapUv );
  12447. array.push( parameters.normalMapUv );
  12448. array.push( parameters.displacementMapUv );
  12449. array.push( parameters.emissiveMapUv );
  12450. array.push( parameters.metalnessMapUv );
  12451. array.push( parameters.roughnessMapUv );
  12452. array.push( parameters.anisotropyMapUv );
  12453. array.push( parameters.clearcoatMapUv );
  12454. array.push( parameters.clearcoatNormalMapUv );
  12455. array.push( parameters.clearcoatRoughnessMapUv );
  12456. array.push( parameters.iridescenceMapUv );
  12457. array.push( parameters.iridescenceThicknessMapUv );
  12458. array.push( parameters.sheenColorMapUv );
  12459. array.push( parameters.sheenRoughnessMapUv );
  12460. array.push( parameters.specularMapUv );
  12461. array.push( parameters.specularColorMapUv );
  12462. array.push( parameters.specularIntensityMapUv );
  12463. array.push( parameters.transmissionMapUv );
  12464. array.push( parameters.thicknessMapUv );
  12465. array.push( parameters.combine );
  12466. array.push( parameters.fogExp2 );
  12467. array.push( parameters.sizeAttenuation );
  12468. array.push( parameters.morphTargetsCount );
  12469. array.push( parameters.morphAttributeCount );
  12470. array.push( parameters.numDirLights );
  12471. array.push( parameters.numPointLights );
  12472. array.push( parameters.numSpotLights );
  12473. array.push( parameters.numSpotLightMaps );
  12474. array.push( parameters.numHemiLights );
  12475. array.push( parameters.numRectAreaLights );
  12476. array.push( parameters.numDirLightShadows );
  12477. array.push( parameters.numPointLightShadows );
  12478. array.push( parameters.numSpotLightShadows );
  12479. array.push( parameters.numSpotLightShadowsWithMaps );
  12480. array.push( parameters.numLightProbes );
  12481. array.push( parameters.shadowMapType );
  12482. array.push( parameters.toneMapping );
  12483. array.push( parameters.numClippingPlanes );
  12484. array.push( parameters.numClipIntersection );
  12485. array.push( parameters.depthPacking );
  12486. }
  12487. function getProgramCacheKeyBooleans( array, parameters ) {
  12488. _programLayers.disableAll();
  12489. if ( parameters.supportsVertexTextures )
  12490. _programLayers.enable( 0 );
  12491. if ( parameters.instancing )
  12492. _programLayers.enable( 1 );
  12493. if ( parameters.instancingColor )
  12494. _programLayers.enable( 2 );
  12495. if ( parameters.instancingMorph )
  12496. _programLayers.enable( 3 );
  12497. if ( parameters.matcap )
  12498. _programLayers.enable( 4 );
  12499. if ( parameters.envMap )
  12500. _programLayers.enable( 5 );
  12501. if ( parameters.normalMapObjectSpace )
  12502. _programLayers.enable( 6 );
  12503. if ( parameters.normalMapTangentSpace )
  12504. _programLayers.enable( 7 );
  12505. if ( parameters.clearcoat )
  12506. _programLayers.enable( 8 );
  12507. if ( parameters.iridescence )
  12508. _programLayers.enable( 9 );
  12509. if ( parameters.alphaTest )
  12510. _programLayers.enable( 10 );
  12511. if ( parameters.vertexColors )
  12512. _programLayers.enable( 11 );
  12513. if ( parameters.vertexAlphas )
  12514. _programLayers.enable( 12 );
  12515. if ( parameters.vertexUv1s )
  12516. _programLayers.enable( 13 );
  12517. if ( parameters.vertexUv2s )
  12518. _programLayers.enable( 14 );
  12519. if ( parameters.vertexUv3s )
  12520. _programLayers.enable( 15 );
  12521. if ( parameters.vertexTangents )
  12522. _programLayers.enable( 16 );
  12523. if ( parameters.anisotropy )
  12524. _programLayers.enable( 17 );
  12525. if ( parameters.alphaHash )
  12526. _programLayers.enable( 18 );
  12527. if ( parameters.batching )
  12528. _programLayers.enable( 19 );
  12529. array.push( _programLayers.mask );
  12530. _programLayers.disableAll();
  12531. if ( parameters.fog )
  12532. _programLayers.enable( 0 );
  12533. if ( parameters.useFog )
  12534. _programLayers.enable( 1 );
  12535. if ( parameters.flatShading )
  12536. _programLayers.enable( 2 );
  12537. if ( parameters.logarithmicDepthBuffer )
  12538. _programLayers.enable( 3 );
  12539. if ( parameters.skinning )
  12540. _programLayers.enable( 4 );
  12541. if ( parameters.morphTargets )
  12542. _programLayers.enable( 5 );
  12543. if ( parameters.morphNormals )
  12544. _programLayers.enable( 6 );
  12545. if ( parameters.morphColors )
  12546. _programLayers.enable( 7 );
  12547. if ( parameters.premultipliedAlpha )
  12548. _programLayers.enable( 8 );
  12549. if ( parameters.shadowMapEnabled )
  12550. _programLayers.enable( 9 );
  12551. if ( parameters.useLegacyLights )
  12552. _programLayers.enable( 10 );
  12553. if ( parameters.doubleSided )
  12554. _programLayers.enable( 11 );
  12555. if ( parameters.flipSided )
  12556. _programLayers.enable( 12 );
  12557. if ( parameters.useDepthPacking )
  12558. _programLayers.enable( 13 );
  12559. if ( parameters.dithering )
  12560. _programLayers.enable( 14 );
  12561. if ( parameters.transmission )
  12562. _programLayers.enable( 15 );
  12563. if ( parameters.sheen )
  12564. _programLayers.enable( 16 );
  12565. if ( parameters.opaque )
  12566. _programLayers.enable( 17 );
  12567. if ( parameters.pointsUvs )
  12568. _programLayers.enable( 18 );
  12569. if ( parameters.decodeVideoTexture )
  12570. _programLayers.enable( 19 );
  12571. if ( parameters.alphaToCoverage )
  12572. _programLayers.enable( 20 );
  12573. array.push( _programLayers.mask );
  12574. }
  12575. function getUniforms( material ) {
  12576. const shaderID = shaderIDs[ material.type ];
  12577. let uniforms;
  12578. if ( shaderID ) {
  12579. const shader = ShaderLib[ shaderID ];
  12580. uniforms = UniformsUtils.clone( shader.uniforms );
  12581. } else {
  12582. uniforms = material.uniforms;
  12583. }
  12584. return uniforms;
  12585. }
  12586. function acquireProgram( parameters, cacheKey ) {
  12587. let program;
  12588. // Check if code has been already compiled
  12589. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12590. const preexistingProgram = programs[ p ];
  12591. if ( preexistingProgram.cacheKey === cacheKey ) {
  12592. program = preexistingProgram;
  12593. ++ program.usedTimes;
  12594. break;
  12595. }
  12596. }
  12597. if ( program === undefined ) {
  12598. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12599. programs.push( program );
  12600. }
  12601. return program;
  12602. }
  12603. function releaseProgram( program ) {
  12604. if ( -- program.usedTimes === 0 ) {
  12605. // Remove from unordered set
  12606. const i = programs.indexOf( program );
  12607. programs[ i ] = programs[ programs.length - 1 ];
  12608. programs.pop();
  12609. // Free WebGL resources
  12610. program.destroy();
  12611. }
  12612. }
  12613. function releaseShaderCache( material ) {
  12614. _customShaders.remove( material );
  12615. }
  12616. function dispose() {
  12617. _customShaders.dispose();
  12618. }
  12619. return {
  12620. getParameters: getParameters,
  12621. getProgramCacheKey: getProgramCacheKey,
  12622. getUniforms: getUniforms,
  12623. acquireProgram: acquireProgram,
  12624. releaseProgram: releaseProgram,
  12625. releaseShaderCache: releaseShaderCache,
  12626. // Exposed for resource monitoring & error feedback via renderer.info:
  12627. programs: programs,
  12628. dispose: dispose
  12629. };
  12630. }
  12631. function WebGLProperties() {
  12632. let properties = new WeakMap();
  12633. function get( object ) {
  12634. let map = properties.get( object );
  12635. if ( map === undefined ) {
  12636. map = {};
  12637. properties.set( object, map );
  12638. }
  12639. return map;
  12640. }
  12641. function remove( object ) {
  12642. properties.delete( object );
  12643. }
  12644. function update( object, key, value ) {
  12645. properties.get( object )[ key ] = value;
  12646. }
  12647. function dispose() {
  12648. properties = new WeakMap();
  12649. }
  12650. return {
  12651. get: get,
  12652. remove: remove,
  12653. update: update,
  12654. dispose: dispose
  12655. };
  12656. }
  12657. function painterSortStable( a, b ) {
  12658. if ( a.groupOrder !== b.groupOrder ) {
  12659. return a.groupOrder - b.groupOrder;
  12660. } else if ( a.renderOrder !== b.renderOrder ) {
  12661. return a.renderOrder - b.renderOrder;
  12662. } else if ( a.material.id !== b.material.id ) {
  12663. return a.material.id - b.material.id;
  12664. } else if ( a.z !== b.z ) {
  12665. return a.z - b.z;
  12666. } else {
  12667. return a.id - b.id;
  12668. }
  12669. }
  12670. function reversePainterSortStable( a, b ) {
  12671. if ( a.groupOrder !== b.groupOrder ) {
  12672. return a.groupOrder - b.groupOrder;
  12673. } else if ( a.renderOrder !== b.renderOrder ) {
  12674. return a.renderOrder - b.renderOrder;
  12675. } else if ( a.z !== b.z ) {
  12676. return b.z - a.z;
  12677. } else {
  12678. return a.id - b.id;
  12679. }
  12680. }
  12681. function WebGLRenderList() {
  12682. const renderItems = [];
  12683. let renderItemsIndex = 0;
  12684. const opaque = [];
  12685. const transmissive = [];
  12686. const transparent = [];
  12687. function init() {
  12688. renderItemsIndex = 0;
  12689. opaque.length = 0;
  12690. transmissive.length = 0;
  12691. transparent.length = 0;
  12692. }
  12693. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12694. let renderItem = renderItems[ renderItemsIndex ];
  12695. if ( renderItem === undefined ) {
  12696. renderItem = {
  12697. id: object.id,
  12698. object: object,
  12699. geometry: geometry,
  12700. material: material,
  12701. groupOrder: groupOrder,
  12702. renderOrder: object.renderOrder,
  12703. z: z,
  12704. group: group
  12705. };
  12706. renderItems[ renderItemsIndex ] = renderItem;
  12707. } else {
  12708. renderItem.id = object.id;
  12709. renderItem.object = object;
  12710. renderItem.geometry = geometry;
  12711. renderItem.material = material;
  12712. renderItem.groupOrder = groupOrder;
  12713. renderItem.renderOrder = object.renderOrder;
  12714. renderItem.z = z;
  12715. renderItem.group = group;
  12716. }
  12717. renderItemsIndex ++;
  12718. return renderItem;
  12719. }
  12720. function push( object, geometry, material, groupOrder, z, group ) {
  12721. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12722. if ( material.transmission > 0.0 ) {
  12723. transmissive.push( renderItem );
  12724. } else if ( material.transparent === true ) {
  12725. transparent.push( renderItem );
  12726. } else {
  12727. opaque.push( renderItem );
  12728. }
  12729. }
  12730. function unshift( object, geometry, material, groupOrder, z, group ) {
  12731. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12732. if ( material.transmission > 0.0 ) {
  12733. transmissive.unshift( renderItem );
  12734. } else if ( material.transparent === true ) {
  12735. transparent.unshift( renderItem );
  12736. } else {
  12737. opaque.unshift( renderItem );
  12738. }
  12739. }
  12740. function sort( customOpaqueSort, customTransparentSort ) {
  12741. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12742. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12743. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12744. }
  12745. function finish() {
  12746. // Clear references from inactive renderItems in the list
  12747. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12748. const renderItem = renderItems[ i ];
  12749. if ( renderItem.id === null ) break;
  12750. renderItem.id = null;
  12751. renderItem.object = null;
  12752. renderItem.geometry = null;
  12753. renderItem.material = null;
  12754. renderItem.group = null;
  12755. }
  12756. }
  12757. return {
  12758. opaque: opaque,
  12759. transmissive: transmissive,
  12760. transparent: transparent,
  12761. init: init,
  12762. push: push,
  12763. unshift: unshift,
  12764. finish: finish,
  12765. sort: sort
  12766. };
  12767. }
  12768. function WebGLRenderLists() {
  12769. let lists = new WeakMap();
  12770. function get( scene, renderCallDepth ) {
  12771. const listArray = lists.get( scene );
  12772. let list;
  12773. if ( listArray === undefined ) {
  12774. list = new WebGLRenderList();
  12775. lists.set( scene, [ list ] );
  12776. } else {
  12777. if ( renderCallDepth >= listArray.length ) {
  12778. list = new WebGLRenderList();
  12779. listArray.push( list );
  12780. } else {
  12781. list = listArray[ renderCallDepth ];
  12782. }
  12783. }
  12784. return list;
  12785. }
  12786. function dispose() {
  12787. lists = new WeakMap();
  12788. }
  12789. return {
  12790. get: get,
  12791. dispose: dispose
  12792. };
  12793. }
  12794. function UniformsCache() {
  12795. const lights = {};
  12796. return {
  12797. get: function ( light ) {
  12798. if ( lights[ light.id ] !== undefined ) {
  12799. return lights[ light.id ];
  12800. }
  12801. let uniforms;
  12802. switch ( light.type ) {
  12803. case 'DirectionalLight':
  12804. uniforms = {
  12805. direction: new Vector3(),
  12806. color: new Color()
  12807. };
  12808. break;
  12809. case 'SpotLight':
  12810. uniforms = {
  12811. position: new Vector3(),
  12812. direction: new Vector3(),
  12813. color: new Color(),
  12814. distance: 0,
  12815. coneCos: 0,
  12816. penumbraCos: 0,
  12817. decay: 0
  12818. };
  12819. break;
  12820. case 'PointLight':
  12821. uniforms = {
  12822. position: new Vector3(),
  12823. color: new Color(),
  12824. distance: 0,
  12825. decay: 0
  12826. };
  12827. break;
  12828. case 'HemisphereLight':
  12829. uniforms = {
  12830. direction: new Vector3(),
  12831. skyColor: new Color(),
  12832. groundColor: new Color()
  12833. };
  12834. break;
  12835. case 'RectAreaLight':
  12836. uniforms = {
  12837. color: new Color(),
  12838. position: new Vector3(),
  12839. halfWidth: new Vector3(),
  12840. halfHeight: new Vector3()
  12841. };
  12842. break;
  12843. }
  12844. lights[ light.id ] = uniforms;
  12845. return uniforms;
  12846. }
  12847. };
  12848. }
  12849. function ShadowUniformsCache() {
  12850. const lights = {};
  12851. return {
  12852. get: function ( light ) {
  12853. if ( lights[ light.id ] !== undefined ) {
  12854. return lights[ light.id ];
  12855. }
  12856. let uniforms;
  12857. switch ( light.type ) {
  12858. case 'DirectionalLight':
  12859. uniforms = {
  12860. shadowBias: 0,
  12861. shadowNormalBias: 0,
  12862. shadowRadius: 1,
  12863. shadowMapSize: new Vector2()
  12864. };
  12865. break;
  12866. case 'SpotLight':
  12867. uniforms = {
  12868. shadowBias: 0,
  12869. shadowNormalBias: 0,
  12870. shadowRadius: 1,
  12871. shadowMapSize: new Vector2()
  12872. };
  12873. break;
  12874. case 'PointLight':
  12875. uniforms = {
  12876. shadowBias: 0,
  12877. shadowNormalBias: 0,
  12878. shadowRadius: 1,
  12879. shadowMapSize: new Vector2(),
  12880. shadowCameraNear: 1,
  12881. shadowCameraFar: 1000
  12882. };
  12883. break;
  12884. // TODO (abelnation): set RectAreaLight shadow uniforms
  12885. }
  12886. lights[ light.id ] = uniforms;
  12887. return uniforms;
  12888. }
  12889. };
  12890. }
  12891. let nextVersion = 0;
  12892. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12893. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12894. }
  12895. function WebGLLights( extensions ) {
  12896. const cache = new UniformsCache();
  12897. const shadowCache = ShadowUniformsCache();
  12898. const state = {
  12899. version: 0,
  12900. hash: {
  12901. directionalLength: - 1,
  12902. pointLength: - 1,
  12903. spotLength: - 1,
  12904. rectAreaLength: - 1,
  12905. hemiLength: - 1,
  12906. numDirectionalShadows: - 1,
  12907. numPointShadows: - 1,
  12908. numSpotShadows: - 1,
  12909. numSpotMaps: - 1,
  12910. numLightProbes: - 1
  12911. },
  12912. ambient: [ 0, 0, 0 ],
  12913. probe: [],
  12914. directional: [],
  12915. directionalShadow: [],
  12916. directionalShadowMap: [],
  12917. directionalShadowMatrix: [],
  12918. spot: [],
  12919. spotLightMap: [],
  12920. spotShadow: [],
  12921. spotShadowMap: [],
  12922. spotLightMatrix: [],
  12923. rectArea: [],
  12924. rectAreaLTC1: null,
  12925. rectAreaLTC2: null,
  12926. point: [],
  12927. pointShadow: [],
  12928. pointShadowMap: [],
  12929. pointShadowMatrix: [],
  12930. hemi: [],
  12931. numSpotLightShadowsWithMaps: 0,
  12932. numLightProbes: 0
  12933. };
  12934. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12935. const vector3 = new Vector3();
  12936. const matrix4 = new Matrix4();
  12937. const matrix42 = new Matrix4();
  12938. function setup( lights, useLegacyLights ) {
  12939. let r = 0, g = 0, b = 0;
  12940. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12941. let directionalLength = 0;
  12942. let pointLength = 0;
  12943. let spotLength = 0;
  12944. let rectAreaLength = 0;
  12945. let hemiLength = 0;
  12946. let numDirectionalShadows = 0;
  12947. let numPointShadows = 0;
  12948. let numSpotShadows = 0;
  12949. let numSpotMaps = 0;
  12950. let numSpotShadowsWithMaps = 0;
  12951. let numLightProbes = 0;
  12952. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12953. lights.sort( shadowCastingAndTexturingLightsFirst );
  12954. // artist-friendly light intensity scaling factor
  12955. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12956. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12957. const light = lights[ i ];
  12958. const color = light.color;
  12959. const intensity = light.intensity;
  12960. const distance = light.distance;
  12961. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12962. if ( light.isAmbientLight ) {
  12963. r += color.r * intensity * scaleFactor;
  12964. g += color.g * intensity * scaleFactor;
  12965. b += color.b * intensity * scaleFactor;
  12966. } else if ( light.isLightProbe ) {
  12967. for ( let j = 0; j < 9; j ++ ) {
  12968. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12969. }
  12970. numLightProbes ++;
  12971. } else if ( light.isDirectionalLight ) {
  12972. const uniforms = cache.get( light );
  12973. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12974. if ( light.castShadow ) {
  12975. const shadow = light.shadow;
  12976. const shadowUniforms = shadowCache.get( light );
  12977. shadowUniforms.shadowBias = shadow.bias;
  12978. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12979. shadowUniforms.shadowRadius = shadow.radius;
  12980. shadowUniforms.shadowMapSize = shadow.mapSize;
  12981. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12982. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12983. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12984. numDirectionalShadows ++;
  12985. }
  12986. state.directional[ directionalLength ] = uniforms;
  12987. directionalLength ++;
  12988. } else if ( light.isSpotLight ) {
  12989. const uniforms = cache.get( light );
  12990. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12991. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12992. uniforms.distance = distance;
  12993. uniforms.coneCos = Math.cos( light.angle );
  12994. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12995. uniforms.decay = light.decay;
  12996. state.spot[ spotLength ] = uniforms;
  12997. const shadow = light.shadow;
  12998. if ( light.map ) {
  12999. state.spotLightMap[ numSpotMaps ] = light.map;
  13000. numSpotMaps ++;
  13001. // make sure the lightMatrix is up to date
  13002. // TODO : do it if required only
  13003. shadow.updateMatrices( light );
  13004. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  13005. }
  13006. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  13007. if ( light.castShadow ) {
  13008. const shadowUniforms = shadowCache.get( light );
  13009. shadowUniforms.shadowBias = shadow.bias;
  13010. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13011. shadowUniforms.shadowRadius = shadow.radius;
  13012. shadowUniforms.shadowMapSize = shadow.mapSize;
  13013. state.spotShadow[ spotLength ] = shadowUniforms;
  13014. state.spotShadowMap[ spotLength ] = shadowMap;
  13015. numSpotShadows ++;
  13016. }
  13017. spotLength ++;
  13018. } else if ( light.isRectAreaLight ) {
  13019. const uniforms = cache.get( light );
  13020. uniforms.color.copy( color ).multiplyScalar( intensity );
  13021. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13022. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13023. state.rectArea[ rectAreaLength ] = uniforms;
  13024. rectAreaLength ++;
  13025. } else if ( light.isPointLight ) {
  13026. const uniforms = cache.get( light );
  13027. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13028. uniforms.distance = light.distance;
  13029. uniforms.decay = light.decay;
  13030. if ( light.castShadow ) {
  13031. const shadow = light.shadow;
  13032. const shadowUniforms = shadowCache.get( light );
  13033. shadowUniforms.shadowBias = shadow.bias;
  13034. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13035. shadowUniforms.shadowRadius = shadow.radius;
  13036. shadowUniforms.shadowMapSize = shadow.mapSize;
  13037. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13038. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13039. state.pointShadow[ pointLength ] = shadowUniforms;
  13040. state.pointShadowMap[ pointLength ] = shadowMap;
  13041. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13042. numPointShadows ++;
  13043. }
  13044. state.point[ pointLength ] = uniforms;
  13045. pointLength ++;
  13046. } else if ( light.isHemisphereLight ) {
  13047. const uniforms = cache.get( light );
  13048. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  13049. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  13050. state.hemi[ hemiLength ] = uniforms;
  13051. hemiLength ++;
  13052. }
  13053. }
  13054. if ( rectAreaLength > 0 ) {
  13055. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13056. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13057. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13058. } else {
  13059. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13060. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13061. }
  13062. }
  13063. state.ambient[ 0 ] = r;
  13064. state.ambient[ 1 ] = g;
  13065. state.ambient[ 2 ] = b;
  13066. const hash = state.hash;
  13067. if ( hash.directionalLength !== directionalLength ||
  13068. hash.pointLength !== pointLength ||
  13069. hash.spotLength !== spotLength ||
  13070. hash.rectAreaLength !== rectAreaLength ||
  13071. hash.hemiLength !== hemiLength ||
  13072. hash.numDirectionalShadows !== numDirectionalShadows ||
  13073. hash.numPointShadows !== numPointShadows ||
  13074. hash.numSpotShadows !== numSpotShadows ||
  13075. hash.numSpotMaps !== numSpotMaps ||
  13076. hash.numLightProbes !== numLightProbes ) {
  13077. state.directional.length = directionalLength;
  13078. state.spot.length = spotLength;
  13079. state.rectArea.length = rectAreaLength;
  13080. state.point.length = pointLength;
  13081. state.hemi.length = hemiLength;
  13082. state.directionalShadow.length = numDirectionalShadows;
  13083. state.directionalShadowMap.length = numDirectionalShadows;
  13084. state.pointShadow.length = numPointShadows;
  13085. state.pointShadowMap.length = numPointShadows;
  13086. state.spotShadow.length = numSpotShadows;
  13087. state.spotShadowMap.length = numSpotShadows;
  13088. state.directionalShadowMatrix.length = numDirectionalShadows;
  13089. state.pointShadowMatrix.length = numPointShadows;
  13090. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13091. state.spotLightMap.length = numSpotMaps;
  13092. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13093. state.numLightProbes = numLightProbes;
  13094. hash.directionalLength = directionalLength;
  13095. hash.pointLength = pointLength;
  13096. hash.spotLength = spotLength;
  13097. hash.rectAreaLength = rectAreaLength;
  13098. hash.hemiLength = hemiLength;
  13099. hash.numDirectionalShadows = numDirectionalShadows;
  13100. hash.numPointShadows = numPointShadows;
  13101. hash.numSpotShadows = numSpotShadows;
  13102. hash.numSpotMaps = numSpotMaps;
  13103. hash.numLightProbes = numLightProbes;
  13104. state.version = nextVersion ++;
  13105. }
  13106. }
  13107. function setupView( lights, camera ) {
  13108. let directionalLength = 0;
  13109. let pointLength = 0;
  13110. let spotLength = 0;
  13111. let rectAreaLength = 0;
  13112. let hemiLength = 0;
  13113. const viewMatrix = camera.matrixWorldInverse;
  13114. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13115. const light = lights[ i ];
  13116. if ( light.isDirectionalLight ) {
  13117. const uniforms = state.directional[ directionalLength ];
  13118. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13119. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13120. uniforms.direction.sub( vector3 );
  13121. uniforms.direction.transformDirection( viewMatrix );
  13122. directionalLength ++;
  13123. } else if ( light.isSpotLight ) {
  13124. const uniforms = state.spot[ spotLength ];
  13125. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13126. uniforms.position.applyMatrix4( viewMatrix );
  13127. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13128. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13129. uniforms.direction.sub( vector3 );
  13130. uniforms.direction.transformDirection( viewMatrix );
  13131. spotLength ++;
  13132. } else if ( light.isRectAreaLight ) {
  13133. const uniforms = state.rectArea[ rectAreaLength ];
  13134. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13135. uniforms.position.applyMatrix4( viewMatrix );
  13136. // extract local rotation of light to derive width/height half vectors
  13137. matrix42.identity();
  13138. matrix4.copy( light.matrixWorld );
  13139. matrix4.premultiply( viewMatrix );
  13140. matrix42.extractRotation( matrix4 );
  13141. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13142. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13143. uniforms.halfWidth.applyMatrix4( matrix42 );
  13144. uniforms.halfHeight.applyMatrix4( matrix42 );
  13145. rectAreaLength ++;
  13146. } else if ( light.isPointLight ) {
  13147. const uniforms = state.point[ pointLength ];
  13148. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13149. uniforms.position.applyMatrix4( viewMatrix );
  13150. pointLength ++;
  13151. } else if ( light.isHemisphereLight ) {
  13152. const uniforms = state.hemi[ hemiLength ];
  13153. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13154. uniforms.direction.transformDirection( viewMatrix );
  13155. hemiLength ++;
  13156. }
  13157. }
  13158. }
  13159. return {
  13160. setup: setup,
  13161. setupView: setupView,
  13162. state: state
  13163. };
  13164. }
  13165. function WebGLRenderState( extensions ) {
  13166. const lights = new WebGLLights( extensions );
  13167. const lightsArray = [];
  13168. const shadowsArray = [];
  13169. function init() {
  13170. lightsArray.length = 0;
  13171. shadowsArray.length = 0;
  13172. }
  13173. function pushLight( light ) {
  13174. lightsArray.push( light );
  13175. }
  13176. function pushShadow( shadowLight ) {
  13177. shadowsArray.push( shadowLight );
  13178. }
  13179. function setupLights( useLegacyLights ) {
  13180. lights.setup( lightsArray, useLegacyLights );
  13181. }
  13182. function setupLightsView( camera ) {
  13183. lights.setupView( lightsArray, camera );
  13184. }
  13185. const state = {
  13186. lightsArray: lightsArray,
  13187. shadowsArray: shadowsArray,
  13188. lights: lights,
  13189. transmissionRenderTarget: null
  13190. };
  13191. return {
  13192. init: init,
  13193. state: state,
  13194. setupLights: setupLights,
  13195. setupLightsView: setupLightsView,
  13196. pushLight: pushLight,
  13197. pushShadow: pushShadow
  13198. };
  13199. }
  13200. function WebGLRenderStates( extensions ) {
  13201. let renderStates = new WeakMap();
  13202. function get( scene, renderCallDepth = 0 ) {
  13203. const renderStateArray = renderStates.get( scene );
  13204. let renderState;
  13205. if ( renderStateArray === undefined ) {
  13206. renderState = new WebGLRenderState( extensions );
  13207. renderStates.set( scene, [ renderState ] );
  13208. } else {
  13209. if ( renderCallDepth >= renderStateArray.length ) {
  13210. renderState = new WebGLRenderState( extensions );
  13211. renderStateArray.push( renderState );
  13212. } else {
  13213. renderState = renderStateArray[ renderCallDepth ];
  13214. }
  13215. }
  13216. return renderState;
  13217. }
  13218. function dispose() {
  13219. renderStates = new WeakMap();
  13220. }
  13221. return {
  13222. get: get,
  13223. dispose: dispose
  13224. };
  13225. }
  13226. class MeshDepthMaterial extends Material {
  13227. constructor( parameters ) {
  13228. super();
  13229. this.isMeshDepthMaterial = true;
  13230. this.type = 'MeshDepthMaterial';
  13231. this.depthPacking = BasicDepthPacking;
  13232. this.map = null;
  13233. this.alphaMap = null;
  13234. this.displacementMap = null;
  13235. this.displacementScale = 1;
  13236. this.displacementBias = 0;
  13237. this.wireframe = false;
  13238. this.wireframeLinewidth = 1;
  13239. this.setValues( parameters );
  13240. }
  13241. copy( source ) {
  13242. super.copy( source );
  13243. this.depthPacking = source.depthPacking;
  13244. this.map = source.map;
  13245. this.alphaMap = source.alphaMap;
  13246. this.displacementMap = source.displacementMap;
  13247. this.displacementScale = source.displacementScale;
  13248. this.displacementBias = source.displacementBias;
  13249. this.wireframe = source.wireframe;
  13250. this.wireframeLinewidth = source.wireframeLinewidth;
  13251. return this;
  13252. }
  13253. }
  13254. class MeshDistanceMaterial extends Material {
  13255. constructor( parameters ) {
  13256. super();
  13257. this.isMeshDistanceMaterial = true;
  13258. this.type = 'MeshDistanceMaterial';
  13259. this.map = null;
  13260. this.alphaMap = null;
  13261. this.displacementMap = null;
  13262. this.displacementScale = 1;
  13263. this.displacementBias = 0;
  13264. this.setValues( parameters );
  13265. }
  13266. copy( source ) {
  13267. super.copy( source );
  13268. this.map = source.map;
  13269. this.alphaMap = source.alphaMap;
  13270. this.displacementMap = source.displacementMap;
  13271. this.displacementScale = source.displacementScale;
  13272. this.displacementBias = source.displacementBias;
  13273. return this;
  13274. }
  13275. }
  13276. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13277. 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}";
  13278. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13279. let _frustum = new Frustum();
  13280. const _shadowMapSize = new Vector2(),
  13281. _viewportSize = new Vector2(),
  13282. _viewport = new Vector4(),
  13283. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13284. _distanceMaterial = new MeshDistanceMaterial(),
  13285. _materialCache = {},
  13286. _maxTextureSize = _capabilities.maxTextureSize;
  13287. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13288. const shadowMaterialVertical = new ShaderMaterial( {
  13289. defines: {
  13290. VSM_SAMPLES: 8
  13291. },
  13292. uniforms: {
  13293. shadow_pass: { value: null },
  13294. resolution: { value: new Vector2() },
  13295. radius: { value: 4.0 }
  13296. },
  13297. vertexShader: vertex,
  13298. fragmentShader: fragment
  13299. } );
  13300. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13301. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13302. const fullScreenTri = new BufferGeometry();
  13303. fullScreenTri.setAttribute(
  13304. 'position',
  13305. new BufferAttribute(
  13306. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13307. 3
  13308. )
  13309. );
  13310. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13311. const scope = this;
  13312. this.enabled = false;
  13313. this.autoUpdate = true;
  13314. this.needsUpdate = false;
  13315. this.type = PCFShadowMap;
  13316. let _previousType = this.type;
  13317. this.render = function ( lights, scene, camera ) {
  13318. if ( scope.enabled === false ) return;
  13319. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13320. if ( lights.length === 0 ) return;
  13321. const currentRenderTarget = _renderer.getRenderTarget();
  13322. const activeCubeFace = _renderer.getActiveCubeFace();
  13323. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13324. const _state = _renderer.state;
  13325. // Set GL state for depth map.
  13326. _state.setBlending( NoBlending );
  13327. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13328. _state.buffers.depth.setTest( true );
  13329. _state.setScissorTest( false );
  13330. // check for shadow map type changes
  13331. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13332. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13333. // render depth map
  13334. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13335. const light = lights[ i ];
  13336. const shadow = light.shadow;
  13337. if ( shadow === undefined ) {
  13338. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13339. continue;
  13340. }
  13341. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13342. _shadowMapSize.copy( shadow.mapSize );
  13343. const shadowFrameExtents = shadow.getFrameExtents();
  13344. _shadowMapSize.multiply( shadowFrameExtents );
  13345. _viewportSize.copy( shadow.mapSize );
  13346. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13347. if ( _shadowMapSize.x > _maxTextureSize ) {
  13348. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13349. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13350. shadow.mapSize.x = _viewportSize.x;
  13351. }
  13352. if ( _shadowMapSize.y > _maxTextureSize ) {
  13353. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13354. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13355. shadow.mapSize.y = _viewportSize.y;
  13356. }
  13357. }
  13358. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13359. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13360. if ( shadow.map !== null ) {
  13361. shadow.map.dispose();
  13362. }
  13363. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13364. shadow.map.texture.name = light.name + '.shadowMap';
  13365. shadow.camera.updateProjectionMatrix();
  13366. }
  13367. _renderer.setRenderTarget( shadow.map );
  13368. _renderer.clear();
  13369. const viewportCount = shadow.getViewportCount();
  13370. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13371. const viewport = shadow.getViewport( vp );
  13372. _viewport.set(
  13373. _viewportSize.x * viewport.x,
  13374. _viewportSize.y * viewport.y,
  13375. _viewportSize.x * viewport.z,
  13376. _viewportSize.y * viewport.w
  13377. );
  13378. _state.viewport( _viewport );
  13379. shadow.updateMatrices( light, vp );
  13380. _frustum = shadow.getFrustum();
  13381. renderObject( scene, camera, shadow.camera, light, this.type );
  13382. }
  13383. // do blur pass for VSM
  13384. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13385. VSMPass( shadow, camera );
  13386. }
  13387. shadow.needsUpdate = false;
  13388. }
  13389. _previousType = this.type;
  13390. scope.needsUpdate = false;
  13391. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13392. };
  13393. function VSMPass( shadow, camera ) {
  13394. const geometry = _objects.update( fullScreenMesh );
  13395. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13396. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13397. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13398. shadowMaterialVertical.needsUpdate = true;
  13399. shadowMaterialHorizontal.needsUpdate = true;
  13400. }
  13401. if ( shadow.mapPass === null ) {
  13402. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13403. }
  13404. // vertical pass
  13405. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13406. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13407. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13408. _renderer.setRenderTarget( shadow.mapPass );
  13409. _renderer.clear();
  13410. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13411. // horizontal pass
  13412. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13413. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13414. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13415. _renderer.setRenderTarget( shadow.map );
  13416. _renderer.clear();
  13417. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13418. }
  13419. function getDepthMaterial( object, material, light, type ) {
  13420. let result = null;
  13421. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13422. if ( customMaterial !== undefined ) {
  13423. result = customMaterial;
  13424. } else {
  13425. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13426. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13427. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13428. ( material.alphaMap && material.alphaTest > 0 ) ||
  13429. ( material.map && material.alphaTest > 0 ) ) {
  13430. // in this case we need a unique material instance reflecting the
  13431. // appropriate state
  13432. const keyA = result.uuid, keyB = material.uuid;
  13433. let materialsForVariant = _materialCache[ keyA ];
  13434. if ( materialsForVariant === undefined ) {
  13435. materialsForVariant = {};
  13436. _materialCache[ keyA ] = materialsForVariant;
  13437. }
  13438. let cachedMaterial = materialsForVariant[ keyB ];
  13439. if ( cachedMaterial === undefined ) {
  13440. cachedMaterial = result.clone();
  13441. materialsForVariant[ keyB ] = cachedMaterial;
  13442. material.addEventListener( 'dispose', onMaterialDispose );
  13443. }
  13444. result = cachedMaterial;
  13445. }
  13446. }
  13447. result.visible = material.visible;
  13448. result.wireframe = material.wireframe;
  13449. if ( type === VSMShadowMap ) {
  13450. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13451. } else {
  13452. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13453. }
  13454. result.alphaMap = material.alphaMap;
  13455. result.alphaTest = material.alphaTest;
  13456. result.map = material.map;
  13457. result.clipShadows = material.clipShadows;
  13458. result.clippingPlanes = material.clippingPlanes;
  13459. result.clipIntersection = material.clipIntersection;
  13460. result.displacementMap = material.displacementMap;
  13461. result.displacementScale = material.displacementScale;
  13462. result.displacementBias = material.displacementBias;
  13463. result.wireframeLinewidth = material.wireframeLinewidth;
  13464. result.linewidth = material.linewidth;
  13465. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13466. const materialProperties = _renderer.properties.get( result );
  13467. materialProperties.light = light;
  13468. }
  13469. return result;
  13470. }
  13471. function renderObject( object, camera, shadowCamera, light, type ) {
  13472. if ( object.visible === false ) return;
  13473. const visible = object.layers.test( camera.layers );
  13474. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13475. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13476. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13477. const geometry = _objects.update( object );
  13478. const material = object.material;
  13479. if ( Array.isArray( material ) ) {
  13480. const groups = geometry.groups;
  13481. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13482. const group = groups[ k ];
  13483. const groupMaterial = material[ group.materialIndex ];
  13484. if ( groupMaterial && groupMaterial.visible ) {
  13485. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13486. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13487. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13488. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13489. }
  13490. }
  13491. } else if ( material.visible ) {
  13492. const depthMaterial = getDepthMaterial( object, material, light, type );
  13493. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13494. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13495. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13496. }
  13497. }
  13498. }
  13499. const children = object.children;
  13500. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13501. renderObject( children[ i ], camera, shadowCamera, light, type );
  13502. }
  13503. }
  13504. function onMaterialDispose( event ) {
  13505. const material = event.target;
  13506. material.removeEventListener( 'dispose', onMaterialDispose );
  13507. // make sure to remove the unique distance/depth materials used for shadow map rendering
  13508. for ( const id in _materialCache ) {
  13509. const cache = _materialCache[ id ];
  13510. const uuid = event.target.uuid;
  13511. if ( uuid in cache ) {
  13512. const shadowMaterial = cache[ uuid ];
  13513. shadowMaterial.dispose();
  13514. delete cache[ uuid ];
  13515. }
  13516. }
  13517. }
  13518. }
  13519. function WebGLState( gl ) {
  13520. function ColorBuffer() {
  13521. let locked = false;
  13522. const color = new Vector4();
  13523. let currentColorMask = null;
  13524. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13525. return {
  13526. setMask: function ( colorMask ) {
  13527. if ( currentColorMask !== colorMask && ! locked ) {
  13528. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13529. currentColorMask = colorMask;
  13530. }
  13531. },
  13532. setLocked: function ( lock ) {
  13533. locked = lock;
  13534. },
  13535. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13536. if ( premultipliedAlpha === true ) {
  13537. r *= a; g *= a; b *= a;
  13538. }
  13539. color.set( r, g, b, a );
  13540. if ( currentColorClear.equals( color ) === false ) {
  13541. gl.clearColor( r, g, b, a );
  13542. currentColorClear.copy( color );
  13543. }
  13544. },
  13545. reset: function () {
  13546. locked = false;
  13547. currentColorMask = null;
  13548. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13549. }
  13550. };
  13551. }
  13552. function DepthBuffer() {
  13553. let locked = false;
  13554. let currentDepthMask = null;
  13555. let currentDepthFunc = null;
  13556. let currentDepthClear = null;
  13557. return {
  13558. setTest: function ( depthTest ) {
  13559. if ( depthTest ) {
  13560. enable( gl.DEPTH_TEST );
  13561. } else {
  13562. disable( gl.DEPTH_TEST );
  13563. }
  13564. },
  13565. setMask: function ( depthMask ) {
  13566. if ( currentDepthMask !== depthMask && ! locked ) {
  13567. gl.depthMask( depthMask );
  13568. currentDepthMask = depthMask;
  13569. }
  13570. },
  13571. setFunc: function ( depthFunc ) {
  13572. if ( currentDepthFunc !== depthFunc ) {
  13573. switch ( depthFunc ) {
  13574. case NeverDepth:
  13575. gl.depthFunc( gl.NEVER );
  13576. break;
  13577. case AlwaysDepth:
  13578. gl.depthFunc( gl.ALWAYS );
  13579. break;
  13580. case LessDepth:
  13581. gl.depthFunc( gl.LESS );
  13582. break;
  13583. case LessEqualDepth:
  13584. gl.depthFunc( gl.LEQUAL );
  13585. break;
  13586. case EqualDepth:
  13587. gl.depthFunc( gl.EQUAL );
  13588. break;
  13589. case GreaterEqualDepth:
  13590. gl.depthFunc( gl.GEQUAL );
  13591. break;
  13592. case GreaterDepth:
  13593. gl.depthFunc( gl.GREATER );
  13594. break;
  13595. case NotEqualDepth:
  13596. gl.depthFunc( gl.NOTEQUAL );
  13597. break;
  13598. default:
  13599. gl.depthFunc( gl.LEQUAL );
  13600. }
  13601. currentDepthFunc = depthFunc;
  13602. }
  13603. },
  13604. setLocked: function ( lock ) {
  13605. locked = lock;
  13606. },
  13607. setClear: function ( depth ) {
  13608. if ( currentDepthClear !== depth ) {
  13609. gl.clearDepth( depth );
  13610. currentDepthClear = depth;
  13611. }
  13612. },
  13613. reset: function () {
  13614. locked = false;
  13615. currentDepthMask = null;
  13616. currentDepthFunc = null;
  13617. currentDepthClear = null;
  13618. }
  13619. };
  13620. }
  13621. function StencilBuffer() {
  13622. let locked = false;
  13623. let currentStencilMask = null;
  13624. let currentStencilFunc = null;
  13625. let currentStencilRef = null;
  13626. let currentStencilFuncMask = null;
  13627. let currentStencilFail = null;
  13628. let currentStencilZFail = null;
  13629. let currentStencilZPass = null;
  13630. let currentStencilClear = null;
  13631. return {
  13632. setTest: function ( stencilTest ) {
  13633. if ( ! locked ) {
  13634. if ( stencilTest ) {
  13635. enable( gl.STENCIL_TEST );
  13636. } else {
  13637. disable( gl.STENCIL_TEST );
  13638. }
  13639. }
  13640. },
  13641. setMask: function ( stencilMask ) {
  13642. if ( currentStencilMask !== stencilMask && ! locked ) {
  13643. gl.stencilMask( stencilMask );
  13644. currentStencilMask = stencilMask;
  13645. }
  13646. },
  13647. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13648. if ( currentStencilFunc !== stencilFunc ||
  13649. currentStencilRef !== stencilRef ||
  13650. currentStencilFuncMask !== stencilMask ) {
  13651. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13652. currentStencilFunc = stencilFunc;
  13653. currentStencilRef = stencilRef;
  13654. currentStencilFuncMask = stencilMask;
  13655. }
  13656. },
  13657. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13658. if ( currentStencilFail !== stencilFail ||
  13659. currentStencilZFail !== stencilZFail ||
  13660. currentStencilZPass !== stencilZPass ) {
  13661. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13662. currentStencilFail = stencilFail;
  13663. currentStencilZFail = stencilZFail;
  13664. currentStencilZPass = stencilZPass;
  13665. }
  13666. },
  13667. setLocked: function ( lock ) {
  13668. locked = lock;
  13669. },
  13670. setClear: function ( stencil ) {
  13671. if ( currentStencilClear !== stencil ) {
  13672. gl.clearStencil( stencil );
  13673. currentStencilClear = stencil;
  13674. }
  13675. },
  13676. reset: function () {
  13677. locked = false;
  13678. currentStencilMask = null;
  13679. currentStencilFunc = null;
  13680. currentStencilRef = null;
  13681. currentStencilFuncMask = null;
  13682. currentStencilFail = null;
  13683. currentStencilZFail = null;
  13684. currentStencilZPass = null;
  13685. currentStencilClear = null;
  13686. }
  13687. };
  13688. }
  13689. //
  13690. const colorBuffer = new ColorBuffer();
  13691. const depthBuffer = new DepthBuffer();
  13692. const stencilBuffer = new StencilBuffer();
  13693. const uboBindings = new WeakMap();
  13694. const uboProgramMap = new WeakMap();
  13695. let enabledCapabilities = {};
  13696. let currentBoundFramebuffers = {};
  13697. let currentDrawbuffers = new WeakMap();
  13698. let defaultDrawbuffers = [];
  13699. let currentProgram = null;
  13700. let currentBlendingEnabled = false;
  13701. let currentBlending = null;
  13702. let currentBlendEquation = null;
  13703. let currentBlendSrc = null;
  13704. let currentBlendDst = null;
  13705. let currentBlendEquationAlpha = null;
  13706. let currentBlendSrcAlpha = null;
  13707. let currentBlendDstAlpha = null;
  13708. let currentBlendColor = new Color( 0, 0, 0 );
  13709. let currentBlendAlpha = 0;
  13710. let currentPremultipledAlpha = false;
  13711. let currentFlipSided = null;
  13712. let currentCullFace = null;
  13713. let currentLineWidth = null;
  13714. let currentPolygonOffsetFactor = null;
  13715. let currentPolygonOffsetUnits = null;
  13716. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13717. let lineWidthAvailable = false;
  13718. let version = 0;
  13719. const glVersion = gl.getParameter( gl.VERSION );
  13720. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13721. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13722. lineWidthAvailable = ( version >= 1.0 );
  13723. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13724. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13725. lineWidthAvailable = ( version >= 2.0 );
  13726. }
  13727. let currentTextureSlot = null;
  13728. let currentBoundTextures = {};
  13729. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13730. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13731. const currentScissor = new Vector4().fromArray( scissorParam );
  13732. const currentViewport = new Vector4().fromArray( viewportParam );
  13733. function createTexture( type, target, count, dimensions ) {
  13734. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13735. const texture = gl.createTexture();
  13736. gl.bindTexture( type, texture );
  13737. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13738. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13739. for ( let i = 0; i < count; i ++ ) {
  13740. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  13741. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13742. } else {
  13743. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13744. }
  13745. }
  13746. return texture;
  13747. }
  13748. const emptyTextures = {};
  13749. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13750. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13751. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13752. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13753. // init
  13754. colorBuffer.setClear( 0, 0, 0, 1 );
  13755. depthBuffer.setClear( 1 );
  13756. stencilBuffer.setClear( 0 );
  13757. enable( gl.DEPTH_TEST );
  13758. depthBuffer.setFunc( LessEqualDepth );
  13759. setFlipSided( false );
  13760. setCullFace( CullFaceBack );
  13761. enable( gl.CULL_FACE );
  13762. setBlending( NoBlending );
  13763. //
  13764. function enable( id ) {
  13765. if ( enabledCapabilities[ id ] !== true ) {
  13766. gl.enable( id );
  13767. enabledCapabilities[ id ] = true;
  13768. }
  13769. }
  13770. function disable( id ) {
  13771. if ( enabledCapabilities[ id ] !== false ) {
  13772. gl.disable( id );
  13773. enabledCapabilities[ id ] = false;
  13774. }
  13775. }
  13776. function bindFramebuffer( target, framebuffer ) {
  13777. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13778. gl.bindFramebuffer( target, framebuffer );
  13779. currentBoundFramebuffers[ target ] = framebuffer;
  13780. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13781. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13782. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13783. }
  13784. if ( target === gl.FRAMEBUFFER ) {
  13785. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13786. }
  13787. return true;
  13788. }
  13789. return false;
  13790. }
  13791. function drawBuffers( renderTarget, framebuffer ) {
  13792. let drawBuffers = defaultDrawbuffers;
  13793. let needsUpdate = false;
  13794. if ( renderTarget ) {
  13795. drawBuffers = currentDrawbuffers.get( framebuffer );
  13796. if ( drawBuffers === undefined ) {
  13797. drawBuffers = [];
  13798. currentDrawbuffers.set( framebuffer, drawBuffers );
  13799. }
  13800. const textures = renderTarget.textures;
  13801. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13802. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13803. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13804. }
  13805. drawBuffers.length = textures.length;
  13806. needsUpdate = true;
  13807. }
  13808. } else {
  13809. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13810. drawBuffers[ 0 ] = gl.BACK;
  13811. needsUpdate = true;
  13812. }
  13813. }
  13814. if ( needsUpdate ) {
  13815. gl.drawBuffers( drawBuffers );
  13816. }
  13817. }
  13818. function useProgram( program ) {
  13819. if ( currentProgram !== program ) {
  13820. gl.useProgram( program );
  13821. currentProgram = program;
  13822. return true;
  13823. }
  13824. return false;
  13825. }
  13826. const equationToGL = {
  13827. [ AddEquation ]: gl.FUNC_ADD,
  13828. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13829. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13830. };
  13831. equationToGL[ MinEquation ] = gl.MIN;
  13832. equationToGL[ MaxEquation ] = gl.MAX;
  13833. const factorToGL = {
  13834. [ ZeroFactor ]: gl.ZERO,
  13835. [ OneFactor ]: gl.ONE,
  13836. [ SrcColorFactor ]: gl.SRC_COLOR,
  13837. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13838. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13839. [ DstColorFactor ]: gl.DST_COLOR,
  13840. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13841. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13842. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13843. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13844. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  13845. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  13846. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  13847. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  13848. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  13849. };
  13850. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  13851. if ( blending === NoBlending ) {
  13852. if ( currentBlendingEnabled === true ) {
  13853. disable( gl.BLEND );
  13854. currentBlendingEnabled = false;
  13855. }
  13856. return;
  13857. }
  13858. if ( currentBlendingEnabled === false ) {
  13859. enable( gl.BLEND );
  13860. currentBlendingEnabled = true;
  13861. }
  13862. if ( blending !== CustomBlending ) {
  13863. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13864. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13865. gl.blendEquation( gl.FUNC_ADD );
  13866. currentBlendEquation = AddEquation;
  13867. currentBlendEquationAlpha = AddEquation;
  13868. }
  13869. if ( premultipliedAlpha ) {
  13870. switch ( blending ) {
  13871. case NormalBlending:
  13872. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13873. break;
  13874. case AdditiveBlending:
  13875. gl.blendFunc( gl.ONE, gl.ONE );
  13876. break;
  13877. case SubtractiveBlending:
  13878. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13879. break;
  13880. case MultiplyBlending:
  13881. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13882. break;
  13883. default:
  13884. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13885. break;
  13886. }
  13887. } else {
  13888. switch ( blending ) {
  13889. case NormalBlending:
  13890. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13891. break;
  13892. case AdditiveBlending:
  13893. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13894. break;
  13895. case SubtractiveBlending:
  13896. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13897. break;
  13898. case MultiplyBlending:
  13899. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13900. break;
  13901. default:
  13902. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13903. break;
  13904. }
  13905. }
  13906. currentBlendSrc = null;
  13907. currentBlendDst = null;
  13908. currentBlendSrcAlpha = null;
  13909. currentBlendDstAlpha = null;
  13910. currentBlendColor.set( 0, 0, 0 );
  13911. currentBlendAlpha = 0;
  13912. currentBlending = blending;
  13913. currentPremultipledAlpha = premultipliedAlpha;
  13914. }
  13915. return;
  13916. }
  13917. // custom blending
  13918. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13919. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13920. blendDstAlpha = blendDstAlpha || blendDst;
  13921. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13922. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13923. currentBlendEquation = blendEquation;
  13924. currentBlendEquationAlpha = blendEquationAlpha;
  13925. }
  13926. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13927. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13928. currentBlendSrc = blendSrc;
  13929. currentBlendDst = blendDst;
  13930. currentBlendSrcAlpha = blendSrcAlpha;
  13931. currentBlendDstAlpha = blendDstAlpha;
  13932. }
  13933. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  13934. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  13935. currentBlendColor.copy( blendColor );
  13936. currentBlendAlpha = blendAlpha;
  13937. }
  13938. currentBlending = blending;
  13939. currentPremultipledAlpha = false;
  13940. }
  13941. function setMaterial( material, frontFaceCW ) {
  13942. material.side === DoubleSide
  13943. ? disable( gl.CULL_FACE )
  13944. : enable( gl.CULL_FACE );
  13945. let flipSided = ( material.side === BackSide );
  13946. if ( frontFaceCW ) flipSided = ! flipSided;
  13947. setFlipSided( flipSided );
  13948. ( material.blending === NormalBlending && material.transparent === false )
  13949. ? setBlending( NoBlending )
  13950. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  13951. depthBuffer.setFunc( material.depthFunc );
  13952. depthBuffer.setTest( material.depthTest );
  13953. depthBuffer.setMask( material.depthWrite );
  13954. colorBuffer.setMask( material.colorWrite );
  13955. const stencilWrite = material.stencilWrite;
  13956. stencilBuffer.setTest( stencilWrite );
  13957. if ( stencilWrite ) {
  13958. stencilBuffer.setMask( material.stencilWriteMask );
  13959. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13960. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13961. }
  13962. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13963. material.alphaToCoverage === true
  13964. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13965. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13966. }
  13967. //
  13968. function setFlipSided( flipSided ) {
  13969. if ( currentFlipSided !== flipSided ) {
  13970. if ( flipSided ) {
  13971. gl.frontFace( gl.CW );
  13972. } else {
  13973. gl.frontFace( gl.CCW );
  13974. }
  13975. currentFlipSided = flipSided;
  13976. }
  13977. }
  13978. function setCullFace( cullFace ) {
  13979. if ( cullFace !== CullFaceNone ) {
  13980. enable( gl.CULL_FACE );
  13981. if ( cullFace !== currentCullFace ) {
  13982. if ( cullFace === CullFaceBack ) {
  13983. gl.cullFace( gl.BACK );
  13984. } else if ( cullFace === CullFaceFront ) {
  13985. gl.cullFace( gl.FRONT );
  13986. } else {
  13987. gl.cullFace( gl.FRONT_AND_BACK );
  13988. }
  13989. }
  13990. } else {
  13991. disable( gl.CULL_FACE );
  13992. }
  13993. currentCullFace = cullFace;
  13994. }
  13995. function setLineWidth( width ) {
  13996. if ( width !== currentLineWidth ) {
  13997. if ( lineWidthAvailable ) gl.lineWidth( width );
  13998. currentLineWidth = width;
  13999. }
  14000. }
  14001. function setPolygonOffset( polygonOffset, factor, units ) {
  14002. if ( polygonOffset ) {
  14003. enable( gl.POLYGON_OFFSET_FILL );
  14004. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14005. gl.polygonOffset( factor, units );
  14006. currentPolygonOffsetFactor = factor;
  14007. currentPolygonOffsetUnits = units;
  14008. }
  14009. } else {
  14010. disable( gl.POLYGON_OFFSET_FILL );
  14011. }
  14012. }
  14013. function setScissorTest( scissorTest ) {
  14014. if ( scissorTest ) {
  14015. enable( gl.SCISSOR_TEST );
  14016. } else {
  14017. disable( gl.SCISSOR_TEST );
  14018. }
  14019. }
  14020. // texture
  14021. function activeTexture( webglSlot ) {
  14022. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14023. if ( currentTextureSlot !== webglSlot ) {
  14024. gl.activeTexture( webglSlot );
  14025. currentTextureSlot = webglSlot;
  14026. }
  14027. }
  14028. function bindTexture( webglType, webglTexture, webglSlot ) {
  14029. if ( webglSlot === undefined ) {
  14030. if ( currentTextureSlot === null ) {
  14031. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14032. } else {
  14033. webglSlot = currentTextureSlot;
  14034. }
  14035. }
  14036. let boundTexture = currentBoundTextures[ webglSlot ];
  14037. if ( boundTexture === undefined ) {
  14038. boundTexture = { type: undefined, texture: undefined };
  14039. currentBoundTextures[ webglSlot ] = boundTexture;
  14040. }
  14041. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14042. if ( currentTextureSlot !== webglSlot ) {
  14043. gl.activeTexture( webglSlot );
  14044. currentTextureSlot = webglSlot;
  14045. }
  14046. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14047. boundTexture.type = webglType;
  14048. boundTexture.texture = webglTexture;
  14049. }
  14050. }
  14051. function unbindTexture() {
  14052. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14053. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14054. gl.bindTexture( boundTexture.type, null );
  14055. boundTexture.type = undefined;
  14056. boundTexture.texture = undefined;
  14057. }
  14058. }
  14059. function compressedTexImage2D() {
  14060. try {
  14061. gl.compressedTexImage2D.apply( gl, arguments );
  14062. } catch ( error ) {
  14063. console.error( 'THREE.WebGLState:', error );
  14064. }
  14065. }
  14066. function compressedTexImage3D() {
  14067. try {
  14068. gl.compressedTexImage3D.apply( gl, arguments );
  14069. } catch ( error ) {
  14070. console.error( 'THREE.WebGLState:', error );
  14071. }
  14072. }
  14073. function texSubImage2D() {
  14074. try {
  14075. gl.texSubImage2D.apply( gl, arguments );
  14076. } catch ( error ) {
  14077. console.error( 'THREE.WebGLState:', error );
  14078. }
  14079. }
  14080. function texSubImage3D() {
  14081. try {
  14082. gl.texSubImage3D.apply( gl, arguments );
  14083. } catch ( error ) {
  14084. console.error( 'THREE.WebGLState:', error );
  14085. }
  14086. }
  14087. function compressedTexSubImage2D() {
  14088. try {
  14089. gl.compressedTexSubImage2D.apply( gl, arguments );
  14090. } catch ( error ) {
  14091. console.error( 'THREE.WebGLState:', error );
  14092. }
  14093. }
  14094. function compressedTexSubImage3D() {
  14095. try {
  14096. gl.compressedTexSubImage3D.apply( gl, arguments );
  14097. } catch ( error ) {
  14098. console.error( 'THREE.WebGLState:', error );
  14099. }
  14100. }
  14101. function texStorage2D() {
  14102. try {
  14103. gl.texStorage2D.apply( gl, arguments );
  14104. } catch ( error ) {
  14105. console.error( 'THREE.WebGLState:', error );
  14106. }
  14107. }
  14108. function texStorage3D() {
  14109. try {
  14110. gl.texStorage3D.apply( gl, arguments );
  14111. } catch ( error ) {
  14112. console.error( 'THREE.WebGLState:', error );
  14113. }
  14114. }
  14115. function texImage2D() {
  14116. try {
  14117. gl.texImage2D.apply( gl, arguments );
  14118. } catch ( error ) {
  14119. console.error( 'THREE.WebGLState:', error );
  14120. }
  14121. }
  14122. function texImage3D() {
  14123. try {
  14124. gl.texImage3D.apply( gl, arguments );
  14125. } catch ( error ) {
  14126. console.error( 'THREE.WebGLState:', error );
  14127. }
  14128. }
  14129. //
  14130. function scissor( scissor ) {
  14131. if ( currentScissor.equals( scissor ) === false ) {
  14132. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14133. currentScissor.copy( scissor );
  14134. }
  14135. }
  14136. function viewport( viewport ) {
  14137. if ( currentViewport.equals( viewport ) === false ) {
  14138. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14139. currentViewport.copy( viewport );
  14140. }
  14141. }
  14142. function updateUBOMapping( uniformsGroup, program ) {
  14143. let mapping = uboProgramMap.get( program );
  14144. if ( mapping === undefined ) {
  14145. mapping = new WeakMap();
  14146. uboProgramMap.set( program, mapping );
  14147. }
  14148. let blockIndex = mapping.get( uniformsGroup );
  14149. if ( blockIndex === undefined ) {
  14150. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14151. mapping.set( uniformsGroup, blockIndex );
  14152. }
  14153. }
  14154. function uniformBlockBinding( uniformsGroup, program ) {
  14155. const mapping = uboProgramMap.get( program );
  14156. const blockIndex = mapping.get( uniformsGroup );
  14157. if ( uboBindings.get( program ) !== blockIndex ) {
  14158. // bind shader specific block index to global block point
  14159. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14160. uboBindings.set( program, blockIndex );
  14161. }
  14162. }
  14163. //
  14164. function reset() {
  14165. // reset state
  14166. gl.disable( gl.BLEND );
  14167. gl.disable( gl.CULL_FACE );
  14168. gl.disable( gl.DEPTH_TEST );
  14169. gl.disable( gl.POLYGON_OFFSET_FILL );
  14170. gl.disable( gl.SCISSOR_TEST );
  14171. gl.disable( gl.STENCIL_TEST );
  14172. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14173. gl.blendEquation( gl.FUNC_ADD );
  14174. gl.blendFunc( gl.ONE, gl.ZERO );
  14175. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14176. gl.blendColor( 0, 0, 0, 0 );
  14177. gl.colorMask( true, true, true, true );
  14178. gl.clearColor( 0, 0, 0, 0 );
  14179. gl.depthMask( true );
  14180. gl.depthFunc( gl.LESS );
  14181. gl.clearDepth( 1 );
  14182. gl.stencilMask( 0xffffffff );
  14183. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14184. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14185. gl.clearStencil( 0 );
  14186. gl.cullFace( gl.BACK );
  14187. gl.frontFace( gl.CCW );
  14188. gl.polygonOffset( 0, 0 );
  14189. gl.activeTexture( gl.TEXTURE0 );
  14190. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14191. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14192. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14193. gl.useProgram( null );
  14194. gl.lineWidth( 1 );
  14195. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14196. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14197. // reset internals
  14198. enabledCapabilities = {};
  14199. currentTextureSlot = null;
  14200. currentBoundTextures = {};
  14201. currentBoundFramebuffers = {};
  14202. currentDrawbuffers = new WeakMap();
  14203. defaultDrawbuffers = [];
  14204. currentProgram = null;
  14205. currentBlendingEnabled = false;
  14206. currentBlending = null;
  14207. currentBlendEquation = null;
  14208. currentBlendSrc = null;
  14209. currentBlendDst = null;
  14210. currentBlendEquationAlpha = null;
  14211. currentBlendSrcAlpha = null;
  14212. currentBlendDstAlpha = null;
  14213. currentBlendColor = new Color( 0, 0, 0 );
  14214. currentBlendAlpha = 0;
  14215. currentPremultipledAlpha = false;
  14216. currentFlipSided = null;
  14217. currentCullFace = null;
  14218. currentLineWidth = null;
  14219. currentPolygonOffsetFactor = null;
  14220. currentPolygonOffsetUnits = null;
  14221. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14222. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14223. colorBuffer.reset();
  14224. depthBuffer.reset();
  14225. stencilBuffer.reset();
  14226. }
  14227. return {
  14228. buffers: {
  14229. color: colorBuffer,
  14230. depth: depthBuffer,
  14231. stencil: stencilBuffer
  14232. },
  14233. enable: enable,
  14234. disable: disable,
  14235. bindFramebuffer: bindFramebuffer,
  14236. drawBuffers: drawBuffers,
  14237. useProgram: useProgram,
  14238. setBlending: setBlending,
  14239. setMaterial: setMaterial,
  14240. setFlipSided: setFlipSided,
  14241. setCullFace: setCullFace,
  14242. setLineWidth: setLineWidth,
  14243. setPolygonOffset: setPolygonOffset,
  14244. setScissorTest: setScissorTest,
  14245. activeTexture: activeTexture,
  14246. bindTexture: bindTexture,
  14247. unbindTexture: unbindTexture,
  14248. compressedTexImage2D: compressedTexImage2D,
  14249. compressedTexImage3D: compressedTexImage3D,
  14250. texImage2D: texImage2D,
  14251. texImage3D: texImage3D,
  14252. updateUBOMapping: updateUBOMapping,
  14253. uniformBlockBinding: uniformBlockBinding,
  14254. texStorage2D: texStorage2D,
  14255. texStorage3D: texStorage3D,
  14256. texSubImage2D: texSubImage2D,
  14257. texSubImage3D: texSubImage3D,
  14258. compressedTexSubImage2D: compressedTexSubImage2D,
  14259. compressedTexSubImage3D: compressedTexSubImage3D,
  14260. scissor: scissor,
  14261. viewport: viewport,
  14262. reset: reset
  14263. };
  14264. }
  14265. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14266. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14267. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14268. const _imageDimensions = new Vector2();
  14269. const _videoTextures = new WeakMap();
  14270. let _canvas;
  14271. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14272. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14273. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14274. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14275. let useOffscreenCanvas = false;
  14276. try {
  14277. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14278. // eslint-disable-next-line compat/compat
  14279. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14280. } catch ( err ) {
  14281. // Ignore any errors
  14282. }
  14283. function createCanvas( width, height ) {
  14284. // Use OffscreenCanvas when available. Specially needed in web workers
  14285. return useOffscreenCanvas ?
  14286. // eslint-disable-next-line compat/compat
  14287. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14288. }
  14289. function resizeImage( image, needsNewCanvas, maxSize ) {
  14290. let scale = 1;
  14291. const dimensions = getDimensions( image );
  14292. // handle case if texture exceeds max size
  14293. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  14294. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  14295. }
  14296. // only perform resize if necessary
  14297. if ( scale < 1 ) {
  14298. // only perform resize for certain image types
  14299. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14300. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14301. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  14302. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  14303. const width = Math.floor( scale * dimensions.width );
  14304. const height = Math.floor( scale * dimensions.height );
  14305. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14306. // cube textures can't reuse the same canvas
  14307. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14308. canvas.width = width;
  14309. canvas.height = height;
  14310. const context = canvas.getContext( '2d' );
  14311. context.drawImage( image, 0, 0, width, height );
  14312. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  14313. return canvas;
  14314. } else {
  14315. if ( 'data' in image ) {
  14316. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  14317. }
  14318. return image;
  14319. }
  14320. }
  14321. return image;
  14322. }
  14323. function textureNeedsGenerateMipmaps( texture ) {
  14324. return texture.generateMipmaps && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14325. }
  14326. function generateMipmap( target ) {
  14327. _gl.generateMipmap( target );
  14328. }
  14329. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14330. if ( internalFormatName !== null ) {
  14331. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14332. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14333. }
  14334. let internalFormat = glFormat;
  14335. if ( glFormat === _gl.RED ) {
  14336. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14337. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14338. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14339. }
  14340. if ( glFormat === _gl.RED_INTEGER ) {
  14341. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14342. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14343. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14344. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14345. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14346. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14347. }
  14348. if ( glFormat === _gl.RG ) {
  14349. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14350. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14351. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14352. }
  14353. if ( glFormat === _gl.RG_INTEGER ) {
  14354. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  14355. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  14356. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  14357. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  14358. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  14359. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  14360. }
  14361. if ( glFormat === _gl.RGBA ) {
  14362. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14363. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14364. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14365. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14366. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14367. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14368. }
  14369. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14370. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14371. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14372. extensions.get( 'EXT_color_buffer_float' );
  14373. }
  14374. return internalFormat;
  14375. }
  14376. function getMipLevels( texture, image ) {
  14377. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14378. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14379. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14380. // user-defined mipmaps
  14381. return texture.mipmaps.length;
  14382. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14383. return image.mipmaps.length;
  14384. } else {
  14385. // texture without mipmaps (only base level)
  14386. return 1;
  14387. }
  14388. }
  14389. //
  14390. function onTextureDispose( event ) {
  14391. const texture = event.target;
  14392. texture.removeEventListener( 'dispose', onTextureDispose );
  14393. deallocateTexture( texture );
  14394. if ( texture.isVideoTexture ) {
  14395. _videoTextures.delete( texture );
  14396. }
  14397. }
  14398. function onRenderTargetDispose( event ) {
  14399. const renderTarget = event.target;
  14400. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14401. deallocateRenderTarget( renderTarget );
  14402. }
  14403. //
  14404. function deallocateTexture( texture ) {
  14405. const textureProperties = properties.get( texture );
  14406. if ( textureProperties.__webglInit === undefined ) return;
  14407. // check if it's necessary to remove the WebGLTexture object
  14408. const source = texture.source;
  14409. const webglTextures = _sources.get( source );
  14410. if ( webglTextures ) {
  14411. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14412. webglTexture.usedTimes --;
  14413. // the WebGLTexture object is not used anymore, remove it
  14414. if ( webglTexture.usedTimes === 0 ) {
  14415. deleteTexture( texture );
  14416. }
  14417. // remove the weak map entry if no WebGLTexture uses the source anymore
  14418. if ( Object.keys( webglTextures ).length === 0 ) {
  14419. _sources.delete( source );
  14420. }
  14421. }
  14422. properties.remove( texture );
  14423. }
  14424. function deleteTexture( texture ) {
  14425. const textureProperties = properties.get( texture );
  14426. _gl.deleteTexture( textureProperties.__webglTexture );
  14427. const source = texture.source;
  14428. const webglTextures = _sources.get( source );
  14429. delete webglTextures[ textureProperties.__cacheKey ];
  14430. info.memory.textures --;
  14431. }
  14432. function deallocateRenderTarget( renderTarget ) {
  14433. const renderTargetProperties = properties.get( renderTarget );
  14434. if ( renderTarget.depthTexture ) {
  14435. renderTarget.depthTexture.dispose();
  14436. }
  14437. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14438. for ( let i = 0; i < 6; i ++ ) {
  14439. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14440. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14441. } else {
  14442. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14443. }
  14444. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14445. }
  14446. } else {
  14447. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14448. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14449. } else {
  14450. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14451. }
  14452. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14453. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14454. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14455. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14456. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14457. }
  14458. }
  14459. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14460. }
  14461. const textures = renderTarget.textures;
  14462. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14463. const attachmentProperties = properties.get( textures[ i ] );
  14464. if ( attachmentProperties.__webglTexture ) {
  14465. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14466. info.memory.textures --;
  14467. }
  14468. properties.remove( textures[ i ] );
  14469. }
  14470. properties.remove( renderTarget );
  14471. }
  14472. //
  14473. let textureUnits = 0;
  14474. function resetTextureUnits() {
  14475. textureUnits = 0;
  14476. }
  14477. function allocateTextureUnit() {
  14478. const textureUnit = textureUnits;
  14479. if ( textureUnit >= capabilities.maxTextures ) {
  14480. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  14481. }
  14482. textureUnits += 1;
  14483. return textureUnit;
  14484. }
  14485. function getTextureCacheKey( texture ) {
  14486. const array = [];
  14487. array.push( texture.wrapS );
  14488. array.push( texture.wrapT );
  14489. array.push( texture.wrapR || 0 );
  14490. array.push( texture.magFilter );
  14491. array.push( texture.minFilter );
  14492. array.push( texture.anisotropy );
  14493. array.push( texture.internalFormat );
  14494. array.push( texture.format );
  14495. array.push( texture.type );
  14496. array.push( texture.generateMipmaps );
  14497. array.push( texture.premultiplyAlpha );
  14498. array.push( texture.flipY );
  14499. array.push( texture.unpackAlignment );
  14500. array.push( texture.colorSpace );
  14501. return array.join();
  14502. }
  14503. //
  14504. function setTexture2D( texture, slot ) {
  14505. const textureProperties = properties.get( texture );
  14506. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14507. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14508. const image = texture.image;
  14509. if ( image === null ) {
  14510. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14511. } else if ( image.complete === false ) {
  14512. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14513. } else {
  14514. uploadTexture( textureProperties, texture, slot );
  14515. return;
  14516. }
  14517. }
  14518. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14519. }
  14520. function setTexture2DArray( texture, slot ) {
  14521. const textureProperties = properties.get( texture );
  14522. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14523. uploadTexture( textureProperties, texture, slot );
  14524. return;
  14525. }
  14526. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14527. }
  14528. function setTexture3D( texture, slot ) {
  14529. const textureProperties = properties.get( texture );
  14530. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14531. uploadTexture( textureProperties, texture, slot );
  14532. return;
  14533. }
  14534. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14535. }
  14536. function setTextureCube( texture, slot ) {
  14537. const textureProperties = properties.get( texture );
  14538. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14539. uploadCubeTexture( textureProperties, texture, slot );
  14540. return;
  14541. }
  14542. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14543. }
  14544. const wrappingToGL = {
  14545. [ RepeatWrapping ]: _gl.REPEAT,
  14546. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14547. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14548. };
  14549. const filterToGL = {
  14550. [ NearestFilter ]: _gl.NEAREST,
  14551. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14552. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14553. [ LinearFilter ]: _gl.LINEAR,
  14554. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14555. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14556. };
  14557. const compareToGL = {
  14558. [ NeverCompare ]: _gl.NEVER,
  14559. [ AlwaysCompare ]: _gl.ALWAYS,
  14560. [ LessCompare ]: _gl.LESS,
  14561. [ LessEqualCompare ]: _gl.LEQUAL,
  14562. [ EqualCompare ]: _gl.EQUAL,
  14563. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14564. [ GreaterCompare ]: _gl.GREATER,
  14565. [ NotEqualCompare ]: _gl.NOTEQUAL
  14566. };
  14567. function setTextureParameters( textureType, texture ) {
  14568. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  14569. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14570. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  14571. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  14572. }
  14573. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14574. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14575. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14576. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14577. }
  14578. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14579. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14580. if ( texture.compareFunction ) {
  14581. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14582. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14583. }
  14584. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14585. if ( texture.magFilter === NearestFilter ) return;
  14586. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14587. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  14588. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14589. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14590. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14591. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14592. }
  14593. }
  14594. }
  14595. function initTexture( textureProperties, texture ) {
  14596. let forceUpload = false;
  14597. if ( textureProperties.__webglInit === undefined ) {
  14598. textureProperties.__webglInit = true;
  14599. texture.addEventListener( 'dispose', onTextureDispose );
  14600. }
  14601. // create Source <-> WebGLTextures mapping if necessary
  14602. const source = texture.source;
  14603. let webglTextures = _sources.get( source );
  14604. if ( webglTextures === undefined ) {
  14605. webglTextures = {};
  14606. _sources.set( source, webglTextures );
  14607. }
  14608. // check if there is already a WebGLTexture object for the given texture parameters
  14609. const textureCacheKey = getTextureCacheKey( texture );
  14610. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14611. // if not, create a new instance of WebGLTexture
  14612. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14613. // create new entry
  14614. webglTextures[ textureCacheKey ] = {
  14615. texture: _gl.createTexture(),
  14616. usedTimes: 0
  14617. };
  14618. info.memory.textures ++;
  14619. // when a new instance of WebGLTexture was created, a texture upload is required
  14620. // even if the image contents are identical
  14621. forceUpload = true;
  14622. }
  14623. webglTextures[ textureCacheKey ].usedTimes ++;
  14624. // every time the texture cache key changes, it's necessary to check if an instance of
  14625. // WebGLTexture can be deleted in order to avoid a memory leak.
  14626. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14627. if ( webglTexture !== undefined ) {
  14628. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14629. if ( webglTexture.usedTimes === 0 ) {
  14630. deleteTexture( texture );
  14631. }
  14632. }
  14633. // store references to cache key and WebGLTexture object
  14634. textureProperties.__cacheKey = textureCacheKey;
  14635. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14636. }
  14637. return forceUpload;
  14638. }
  14639. function uploadTexture( textureProperties, texture, slot ) {
  14640. let textureType = _gl.TEXTURE_2D;
  14641. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14642. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14643. const forceUpload = initTexture( textureProperties, texture );
  14644. const source = texture.source;
  14645. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14646. const sourceProperties = properties.get( source );
  14647. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14648. state.activeTexture( _gl.TEXTURE0 + slot );
  14649. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14650. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14651. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14652. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14653. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14654. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14655. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14656. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  14657. image = verifyColorSpace( texture, image );
  14658. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14659. const glType = utils.convert( texture.type );
  14660. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14661. setTextureParameters( textureType, texture );
  14662. let mipmap;
  14663. const mipmaps = texture.mipmaps;
  14664. const useTexStorage = ( texture.isVideoTexture !== true && glInternalFormat !== RGB_ETC1_Format );
  14665. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14666. const dataReady = source.dataReady;
  14667. const levels = getMipLevels( texture, image );
  14668. if ( texture.isDepthTexture ) {
  14669. // populate depth texture with dummy data
  14670. glInternalFormat = _gl.DEPTH_COMPONENT16;
  14671. if ( texture.type === FloatType ) {
  14672. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14673. } else if ( texture.type === UnsignedIntType ) {
  14674. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14675. } else if ( texture.type === UnsignedInt248Type ) {
  14676. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14677. }
  14678. //
  14679. if ( allocateMemory ) {
  14680. if ( useTexStorage ) {
  14681. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14682. } else {
  14683. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14684. }
  14685. }
  14686. } else if ( texture.isDataTexture ) {
  14687. // use manually created mipmaps if available
  14688. // if there are no manual mipmaps
  14689. // set 0 level mipmap and then use GL to generate other mipmap levels
  14690. if ( mipmaps.length > 0 ) {
  14691. if ( useTexStorage && allocateMemory ) {
  14692. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14693. }
  14694. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14695. mipmap = mipmaps[ i ];
  14696. if ( useTexStorage ) {
  14697. if ( dataReady ) {
  14698. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14699. }
  14700. } else {
  14701. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14702. }
  14703. }
  14704. texture.generateMipmaps = false;
  14705. } else {
  14706. if ( useTexStorage ) {
  14707. if ( allocateMemory ) {
  14708. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14709. }
  14710. if ( dataReady ) {
  14711. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14712. }
  14713. } else {
  14714. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14715. }
  14716. }
  14717. } else if ( texture.isCompressedTexture ) {
  14718. if ( texture.isCompressedArrayTexture ) {
  14719. if ( useTexStorage && allocateMemory ) {
  14720. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14721. }
  14722. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14723. mipmap = mipmaps[ i ];
  14724. if ( texture.format !== RGBAFormat ) {
  14725. if ( glFormat !== null ) {
  14726. if ( useTexStorage ) {
  14727. if ( dataReady ) {
  14728. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14729. }
  14730. } else {
  14731. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14732. }
  14733. } else {
  14734. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14735. }
  14736. } else {
  14737. if ( useTexStorage ) {
  14738. if ( dataReady ) {
  14739. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14740. }
  14741. } else {
  14742. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14743. }
  14744. }
  14745. }
  14746. } else {
  14747. if ( useTexStorage && allocateMemory ) {
  14748. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14749. }
  14750. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14751. mipmap = mipmaps[ i ];
  14752. if ( texture.format !== RGBAFormat ) {
  14753. if ( glFormat !== null ) {
  14754. if ( useTexStorage ) {
  14755. if ( dataReady ) {
  14756. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14757. }
  14758. } else {
  14759. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14760. }
  14761. } else {
  14762. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14763. }
  14764. } else {
  14765. if ( useTexStorage ) {
  14766. if ( dataReady ) {
  14767. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14768. }
  14769. } else {
  14770. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14771. }
  14772. }
  14773. }
  14774. }
  14775. } else if ( texture.isDataArrayTexture ) {
  14776. if ( useTexStorage ) {
  14777. if ( allocateMemory ) {
  14778. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14779. }
  14780. if ( dataReady ) {
  14781. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14782. }
  14783. } else {
  14784. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14785. }
  14786. } else if ( texture.isData3DTexture ) {
  14787. if ( useTexStorage ) {
  14788. if ( allocateMemory ) {
  14789. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14790. }
  14791. if ( dataReady ) {
  14792. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14793. }
  14794. } else {
  14795. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14796. }
  14797. } else if ( texture.isFramebufferTexture ) {
  14798. if ( allocateMemory ) {
  14799. if ( useTexStorage ) {
  14800. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14801. } else {
  14802. let width = image.width, height = image.height;
  14803. for ( let i = 0; i < levels; i ++ ) {
  14804. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14805. width >>= 1;
  14806. height >>= 1;
  14807. }
  14808. }
  14809. }
  14810. } else {
  14811. // regular Texture (image, video, canvas)
  14812. // use manually created mipmaps if available
  14813. // if there are no manual mipmaps
  14814. // set 0 level mipmap and then use GL to generate other mipmap levels
  14815. if ( mipmaps.length > 0 ) {
  14816. if ( useTexStorage && allocateMemory ) {
  14817. const dimensions = getDimensions( mipmaps[ 0 ] );
  14818. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  14819. }
  14820. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14821. mipmap = mipmaps[ i ];
  14822. if ( useTexStorage ) {
  14823. if ( dataReady ) {
  14824. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14825. }
  14826. } else {
  14827. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14828. }
  14829. }
  14830. texture.generateMipmaps = false;
  14831. } else {
  14832. if ( useTexStorage ) {
  14833. if ( allocateMemory ) {
  14834. const dimensions = getDimensions( image );
  14835. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  14836. }
  14837. if ( dataReady ) {
  14838. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14839. }
  14840. } else {
  14841. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14842. }
  14843. }
  14844. }
  14845. if ( textureNeedsGenerateMipmaps( texture ) ) {
  14846. generateMipmap( textureType );
  14847. }
  14848. sourceProperties.__version = source.version;
  14849. if ( texture.onUpdate ) texture.onUpdate( texture );
  14850. }
  14851. textureProperties.__version = texture.version;
  14852. }
  14853. function uploadCubeTexture( textureProperties, texture, slot ) {
  14854. if ( texture.image.length !== 6 ) return;
  14855. const forceUpload = initTexture( textureProperties, texture );
  14856. const source = texture.source;
  14857. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14858. const sourceProperties = properties.get( source );
  14859. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14860. state.activeTexture( _gl.TEXTURE0 + slot );
  14861. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14862. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14863. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14864. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14865. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14866. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14867. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14868. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14869. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14870. const cubeImage = [];
  14871. for ( let i = 0; i < 6; i ++ ) {
  14872. if ( ! isCompressed && ! isDataTexture ) {
  14873. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  14874. } else {
  14875. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14876. }
  14877. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14878. }
  14879. const image = cubeImage[ 0 ],
  14880. glFormat = utils.convert( texture.format, texture.colorSpace ),
  14881. glType = utils.convert( texture.type ),
  14882. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14883. const useTexStorage = ( texture.isVideoTexture !== true );
  14884. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14885. const dataReady = source.dataReady;
  14886. let levels = getMipLevels( texture, image );
  14887. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  14888. let mipmaps;
  14889. if ( isCompressed ) {
  14890. if ( useTexStorage && allocateMemory ) {
  14891. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14892. }
  14893. for ( let i = 0; i < 6; i ++ ) {
  14894. mipmaps = cubeImage[ i ].mipmaps;
  14895. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14896. const mipmap = mipmaps[ j ];
  14897. if ( texture.format !== RGBAFormat ) {
  14898. if ( glFormat !== null ) {
  14899. if ( useTexStorage ) {
  14900. if ( dataReady ) {
  14901. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14902. }
  14903. } else {
  14904. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14905. }
  14906. } else {
  14907. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14908. }
  14909. } else {
  14910. if ( useTexStorage ) {
  14911. if ( dataReady ) {
  14912. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14913. }
  14914. } else {
  14915. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14916. }
  14917. }
  14918. }
  14919. }
  14920. } else {
  14921. mipmaps = texture.mipmaps;
  14922. if ( useTexStorage && allocateMemory ) {
  14923. // TODO: Uniformly handle mipmap definitions
  14924. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14925. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14926. if ( mipmaps.length > 0 ) levels ++;
  14927. const dimensions = getDimensions( cubeImage[ 0 ] );
  14928. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  14929. }
  14930. for ( let i = 0; i < 6; i ++ ) {
  14931. if ( isDataTexture ) {
  14932. if ( useTexStorage ) {
  14933. if ( dataReady ) {
  14934. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14935. }
  14936. } else {
  14937. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14938. }
  14939. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14940. const mipmap = mipmaps[ j ];
  14941. const mipmapImage = mipmap.image[ i ].image;
  14942. if ( useTexStorage ) {
  14943. if ( dataReady ) {
  14944. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14945. }
  14946. } else {
  14947. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14948. }
  14949. }
  14950. } else {
  14951. if ( useTexStorage ) {
  14952. if ( dataReady ) {
  14953. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14954. }
  14955. } else {
  14956. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14957. }
  14958. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14959. const mipmap = mipmaps[ j ];
  14960. if ( useTexStorage ) {
  14961. if ( dataReady ) {
  14962. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14963. }
  14964. } else {
  14965. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14966. }
  14967. }
  14968. }
  14969. }
  14970. }
  14971. if ( textureNeedsGenerateMipmaps( texture ) ) {
  14972. // We assume images for cube map have the same size.
  14973. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14974. }
  14975. sourceProperties.__version = source.version;
  14976. if ( texture.onUpdate ) texture.onUpdate( texture );
  14977. }
  14978. textureProperties.__version = texture.version;
  14979. }
  14980. // Render targets
  14981. // Setup storage for target texture and bind it to correct framebuffer
  14982. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  14983. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14984. const glType = utils.convert( texture.type );
  14985. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14986. const renderTargetProperties = properties.get( renderTarget );
  14987. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14988. const width = Math.max( 1, renderTarget.width >> level );
  14989. const height = Math.max( 1, renderTarget.height >> level );
  14990. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14991. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  14992. } else {
  14993. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  14994. }
  14995. }
  14996. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14997. if ( useMultisampledRTT( renderTarget ) ) {
  14998. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14999. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  15000. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  15001. }
  15002. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15003. }
  15004. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15005. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  15006. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15007. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15008. let glInternalFormat = _gl.DEPTH_COMPONENT24;
  15009. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  15010. const depthTexture = renderTarget.depthTexture;
  15011. if ( depthTexture && depthTexture.isDepthTexture ) {
  15012. if ( depthTexture.type === FloatType ) {
  15013. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  15014. } else if ( depthTexture.type === UnsignedIntType ) {
  15015. glInternalFormat = _gl.DEPTH_COMPONENT24;
  15016. }
  15017. }
  15018. const samples = getRenderTargetSamples( renderTarget );
  15019. if ( useMultisampledRTT( renderTarget ) ) {
  15020. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15021. } else {
  15022. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15023. }
  15024. } else {
  15025. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15026. }
  15027. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15028. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15029. const samples = getRenderTargetSamples( renderTarget );
  15030. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15031. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15032. } else if ( useMultisampledRTT( renderTarget ) ) {
  15033. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15034. } else {
  15035. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15036. }
  15037. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15038. } else {
  15039. const textures = renderTarget.textures;
  15040. for ( let i = 0; i < textures.length; i ++ ) {
  15041. const texture = textures[ i ];
  15042. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15043. const glType = utils.convert( texture.type );
  15044. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15045. const samples = getRenderTargetSamples( renderTarget );
  15046. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15047. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15048. } else if ( useMultisampledRTT( renderTarget ) ) {
  15049. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15050. } else {
  15051. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15052. }
  15053. }
  15054. }
  15055. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15056. }
  15057. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15058. function setupDepthTexture( framebuffer, renderTarget ) {
  15059. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15060. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15061. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15062. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15063. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15064. }
  15065. // upload an empty depth texture with framebuffer size
  15066. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15067. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15068. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15069. renderTarget.depthTexture.image.width = renderTarget.width;
  15070. renderTarget.depthTexture.image.height = renderTarget.height;
  15071. renderTarget.depthTexture.needsUpdate = true;
  15072. }
  15073. setTexture2D( renderTarget.depthTexture, 0 );
  15074. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15075. const samples = getRenderTargetSamples( renderTarget );
  15076. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15077. if ( useMultisampledRTT( renderTarget ) ) {
  15078. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15079. } else {
  15080. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15081. }
  15082. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15083. if ( useMultisampledRTT( renderTarget ) ) {
  15084. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15085. } else {
  15086. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15087. }
  15088. } else {
  15089. throw new Error( 'Unknown depthTexture format' );
  15090. }
  15091. }
  15092. // Setup GL resources for a non-texture depth buffer
  15093. function setupDepthRenderbuffer( renderTarget ) {
  15094. const renderTargetProperties = properties.get( renderTarget );
  15095. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15096. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15097. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15098. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15099. } else {
  15100. if ( isCube ) {
  15101. renderTargetProperties.__webglDepthbuffer = [];
  15102. for ( let i = 0; i < 6; i ++ ) {
  15103. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15104. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15105. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15106. }
  15107. } else {
  15108. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15109. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15110. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15111. }
  15112. }
  15113. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15114. }
  15115. // rebind framebuffer with external textures
  15116. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15117. const renderTargetProperties = properties.get( renderTarget );
  15118. if ( colorTexture !== undefined ) {
  15119. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15120. }
  15121. if ( depthTexture !== undefined ) {
  15122. setupDepthRenderbuffer( renderTarget );
  15123. }
  15124. }
  15125. // Set up GL resources for the render target
  15126. function setupRenderTarget( renderTarget ) {
  15127. const texture = renderTarget.texture;
  15128. const renderTargetProperties = properties.get( renderTarget );
  15129. const textureProperties = properties.get( texture );
  15130. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15131. const textures = renderTarget.textures;
  15132. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15133. const isMultipleRenderTargets = ( textures.length > 1 );
  15134. if ( ! isMultipleRenderTargets ) {
  15135. if ( textureProperties.__webglTexture === undefined ) {
  15136. textureProperties.__webglTexture = _gl.createTexture();
  15137. }
  15138. textureProperties.__version = texture.version;
  15139. info.memory.textures ++;
  15140. }
  15141. // Setup framebuffer
  15142. if ( isCube ) {
  15143. renderTargetProperties.__webglFramebuffer = [];
  15144. for ( let i = 0; i < 6; i ++ ) {
  15145. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15146. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15147. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15148. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15149. }
  15150. } else {
  15151. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15152. }
  15153. }
  15154. } else {
  15155. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15156. renderTargetProperties.__webglFramebuffer = [];
  15157. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15158. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15159. }
  15160. } else {
  15161. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15162. }
  15163. if ( isMultipleRenderTargets ) {
  15164. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15165. const attachmentProperties = properties.get( textures[ i ] );
  15166. if ( attachmentProperties.__webglTexture === undefined ) {
  15167. attachmentProperties.__webglTexture = _gl.createTexture();
  15168. info.memory.textures ++;
  15169. }
  15170. }
  15171. }
  15172. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15173. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15174. renderTargetProperties.__webglColorRenderbuffer = [];
  15175. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15176. for ( let i = 0; i < textures.length; i ++ ) {
  15177. const texture = textures[ i ];
  15178. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15179. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15180. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15181. const glType = utils.convert( texture.type );
  15182. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15183. const samples = getRenderTargetSamples( renderTarget );
  15184. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15185. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15186. }
  15187. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15188. if ( renderTarget.depthBuffer ) {
  15189. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15190. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15191. }
  15192. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15193. }
  15194. }
  15195. // Setup color buffer
  15196. if ( isCube ) {
  15197. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15198. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  15199. for ( let i = 0; i < 6; i ++ ) {
  15200. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15201. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15202. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15203. }
  15204. } else {
  15205. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15206. }
  15207. }
  15208. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15209. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15210. }
  15211. state.unbindTexture();
  15212. } else if ( isMultipleRenderTargets ) {
  15213. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15214. const attachment = textures[ i ];
  15215. const attachmentProperties = properties.get( attachment );
  15216. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15217. setTextureParameters( _gl.TEXTURE_2D, attachment );
  15218. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15219. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  15220. generateMipmap( _gl.TEXTURE_2D );
  15221. }
  15222. }
  15223. state.unbindTexture();
  15224. } else {
  15225. let glTextureType = _gl.TEXTURE_2D;
  15226. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15227. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15228. }
  15229. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15230. setTextureParameters( glTextureType, texture );
  15231. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  15232. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15233. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15234. }
  15235. } else {
  15236. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15237. }
  15238. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15239. generateMipmap( glTextureType );
  15240. }
  15241. state.unbindTexture();
  15242. }
  15243. // Setup depth and stencil buffers
  15244. if ( renderTarget.depthBuffer ) {
  15245. setupDepthRenderbuffer( renderTarget );
  15246. }
  15247. }
  15248. function updateRenderTargetMipmap( renderTarget ) {
  15249. const textures = renderTarget.textures;
  15250. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15251. const texture = textures[ i ];
  15252. if ( textureNeedsGenerateMipmaps( texture ) ) {
  15253. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15254. const webglTexture = properties.get( texture ).__webglTexture;
  15255. state.bindTexture( target, webglTexture );
  15256. generateMipmap( target );
  15257. state.unbindTexture();
  15258. }
  15259. }
  15260. }
  15261. function updateMultisampleRenderTarget( renderTarget ) {
  15262. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15263. const textures = renderTarget.textures;
  15264. const width = renderTarget.width;
  15265. const height = renderTarget.height;
  15266. let mask = _gl.COLOR_BUFFER_BIT;
  15267. const invalidationArray = [];
  15268. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15269. const renderTargetProperties = properties.get( renderTarget );
  15270. const isMultipleRenderTargets = ( textures.length > 1 );
  15271. // If MRT we need to remove FBO attachments
  15272. if ( isMultipleRenderTargets ) {
  15273. for ( let i = 0; i < textures.length; i ++ ) {
  15274. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15275. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15276. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15277. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15278. }
  15279. }
  15280. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15281. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15282. for ( let i = 0; i < textures.length; i ++ ) {
  15283. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  15284. if ( renderTarget.depthBuffer ) {
  15285. invalidationArray.push( depthStyle );
  15286. }
  15287. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  15288. if ( ignoreDepthValues === false ) {
  15289. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15290. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  15291. if ( renderTarget.stencilBuffer && renderTargetProperties.__isTransmissionRenderTarget !== true ) mask |= _gl.STENCIL_BUFFER_BIT;
  15292. }
  15293. if ( isMultipleRenderTargets ) {
  15294. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15295. }
  15296. if ( ignoreDepthValues === true ) {
  15297. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  15298. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15299. }
  15300. if ( isMultipleRenderTargets ) {
  15301. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15302. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15303. }
  15304. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15305. if ( supportsInvalidateFramebuffer ) {
  15306. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  15307. }
  15308. }
  15309. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15310. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15311. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15312. if ( isMultipleRenderTargets ) {
  15313. for ( let i = 0; i < textures.length; i ++ ) {
  15314. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15315. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15316. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15317. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15318. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15319. }
  15320. }
  15321. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15322. }
  15323. }
  15324. function getRenderTargetSamples( renderTarget ) {
  15325. return Math.min( capabilities.maxSamples, renderTarget.samples );
  15326. }
  15327. function useMultisampledRTT( renderTarget ) {
  15328. const renderTargetProperties = properties.get( renderTarget );
  15329. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15330. }
  15331. function updateVideoTexture( texture ) {
  15332. const frame = info.render.frame;
  15333. // Check the last frame we updated the VideoTexture
  15334. if ( _videoTextures.get( texture ) !== frame ) {
  15335. _videoTextures.set( texture, frame );
  15336. texture.update();
  15337. }
  15338. }
  15339. function verifyColorSpace( texture, image ) {
  15340. const colorSpace = texture.colorSpace;
  15341. const format = texture.format;
  15342. const type = texture.type;
  15343. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  15344. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15345. // sRGB
  15346. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15347. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15348. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15349. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15350. }
  15351. } else {
  15352. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15353. }
  15354. }
  15355. return image;
  15356. }
  15357. function getDimensions( image ) {
  15358. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  15359. // if intrinsic data are not available, fallback to width/height
  15360. _imageDimensions.width = image.naturalWidth || image.width;
  15361. _imageDimensions.height = image.naturalHeight || image.height;
  15362. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  15363. _imageDimensions.width = image.displayWidth;
  15364. _imageDimensions.height = image.displayHeight;
  15365. } else {
  15366. _imageDimensions.width = image.width;
  15367. _imageDimensions.height = image.height;
  15368. }
  15369. return _imageDimensions;
  15370. }
  15371. //
  15372. this.allocateTextureUnit = allocateTextureUnit;
  15373. this.resetTextureUnits = resetTextureUnits;
  15374. this.setTexture2D = setTexture2D;
  15375. this.setTexture2DArray = setTexture2DArray;
  15376. this.setTexture3D = setTexture3D;
  15377. this.setTextureCube = setTextureCube;
  15378. this.rebindTextures = rebindTextures;
  15379. this.setupRenderTarget = setupRenderTarget;
  15380. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15381. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15382. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15383. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15384. this.useMultisampledRTT = useMultisampledRTT;
  15385. }
  15386. function WebGLUtils( gl, extensions ) {
  15387. function convert( p, colorSpace = NoColorSpace ) {
  15388. let extension;
  15389. const transfer = ColorManagement.getTransfer( colorSpace );
  15390. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15391. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15392. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15393. if ( p === ByteType ) return gl.BYTE;
  15394. if ( p === ShortType ) return gl.SHORT;
  15395. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15396. if ( p === IntType ) return gl.INT;
  15397. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15398. if ( p === FloatType ) return gl.FLOAT;
  15399. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  15400. if ( p === AlphaFormat ) return gl.ALPHA;
  15401. if ( p === RGBAFormat ) return gl.RGBA;
  15402. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15403. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15404. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15405. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15406. // WebGL2 formats.
  15407. if ( p === RedFormat ) return gl.RED;
  15408. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15409. if ( p === RGFormat ) return gl.RG;
  15410. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15411. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15412. // S3TC
  15413. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15414. if ( transfer === SRGBTransfer ) {
  15415. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15416. if ( extension !== null ) {
  15417. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15418. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15419. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15420. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15421. } else {
  15422. return null;
  15423. }
  15424. } else {
  15425. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15426. if ( extension !== null ) {
  15427. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15428. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15429. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15430. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15431. } else {
  15432. return null;
  15433. }
  15434. }
  15435. }
  15436. // PVRTC
  15437. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15438. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15439. if ( extension !== null ) {
  15440. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15441. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15442. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15443. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15444. } else {
  15445. return null;
  15446. }
  15447. }
  15448. // ETC1
  15449. if ( p === RGB_ETC1_Format ) {
  15450. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15451. if ( extension !== null ) {
  15452. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15453. } else {
  15454. return null;
  15455. }
  15456. }
  15457. // ETC2
  15458. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15459. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15460. if ( extension !== null ) {
  15461. if ( p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15462. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15463. } else {
  15464. return null;
  15465. }
  15466. }
  15467. // ASTC
  15468. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15469. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15470. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15471. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15472. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15473. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15474. if ( extension !== null ) {
  15475. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15476. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15477. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15478. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15479. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15480. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15481. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15482. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15483. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15484. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15485. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15486. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15487. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15488. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15489. } else {
  15490. return null;
  15491. }
  15492. }
  15493. // BPTC
  15494. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15495. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15496. if ( extension !== null ) {
  15497. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15498. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15499. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15500. } else {
  15501. return null;
  15502. }
  15503. }
  15504. // RGTC
  15505. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15506. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15507. if ( extension !== null ) {
  15508. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15509. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15510. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15511. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15512. } else {
  15513. return null;
  15514. }
  15515. }
  15516. //
  15517. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  15518. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15519. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15520. }
  15521. return { convert: convert };
  15522. }
  15523. class ArrayCamera extends PerspectiveCamera {
  15524. constructor( array = [] ) {
  15525. super();
  15526. this.isArrayCamera = true;
  15527. this.cameras = array;
  15528. }
  15529. }
  15530. class Group extends Object3D {
  15531. constructor() {
  15532. super();
  15533. this.isGroup = true;
  15534. this.type = 'Group';
  15535. }
  15536. }
  15537. const _moveEvent = { type: 'move' };
  15538. class WebXRController {
  15539. constructor() {
  15540. this._targetRay = null;
  15541. this._grip = null;
  15542. this._hand = null;
  15543. }
  15544. getHandSpace() {
  15545. if ( this._hand === null ) {
  15546. this._hand = new Group();
  15547. this._hand.matrixAutoUpdate = false;
  15548. this._hand.visible = false;
  15549. this._hand.joints = {};
  15550. this._hand.inputState = { pinching: false };
  15551. }
  15552. return this._hand;
  15553. }
  15554. getTargetRaySpace() {
  15555. if ( this._targetRay === null ) {
  15556. this._targetRay = new Group();
  15557. this._targetRay.matrixAutoUpdate = false;
  15558. this._targetRay.visible = false;
  15559. this._targetRay.hasLinearVelocity = false;
  15560. this._targetRay.linearVelocity = new Vector3();
  15561. this._targetRay.hasAngularVelocity = false;
  15562. this._targetRay.angularVelocity = new Vector3();
  15563. }
  15564. return this._targetRay;
  15565. }
  15566. getGripSpace() {
  15567. if ( this._grip === null ) {
  15568. this._grip = new Group();
  15569. this._grip.matrixAutoUpdate = false;
  15570. this._grip.visible = false;
  15571. this._grip.hasLinearVelocity = false;
  15572. this._grip.linearVelocity = new Vector3();
  15573. this._grip.hasAngularVelocity = false;
  15574. this._grip.angularVelocity = new Vector3();
  15575. }
  15576. return this._grip;
  15577. }
  15578. dispatchEvent( event ) {
  15579. if ( this._targetRay !== null ) {
  15580. this._targetRay.dispatchEvent( event );
  15581. }
  15582. if ( this._grip !== null ) {
  15583. this._grip.dispatchEvent( event );
  15584. }
  15585. if ( this._hand !== null ) {
  15586. this._hand.dispatchEvent( event );
  15587. }
  15588. return this;
  15589. }
  15590. connect( inputSource ) {
  15591. if ( inputSource && inputSource.hand ) {
  15592. const hand = this._hand;
  15593. if ( hand ) {
  15594. for ( const inputjoint of inputSource.hand.values() ) {
  15595. // Initialize hand with joints when connected
  15596. this._getHandJoint( hand, inputjoint );
  15597. }
  15598. }
  15599. }
  15600. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15601. return this;
  15602. }
  15603. disconnect( inputSource ) {
  15604. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15605. if ( this._targetRay !== null ) {
  15606. this._targetRay.visible = false;
  15607. }
  15608. if ( this._grip !== null ) {
  15609. this._grip.visible = false;
  15610. }
  15611. if ( this._hand !== null ) {
  15612. this._hand.visible = false;
  15613. }
  15614. return this;
  15615. }
  15616. update( inputSource, frame, referenceSpace ) {
  15617. let inputPose = null;
  15618. let gripPose = null;
  15619. let handPose = null;
  15620. const targetRay = this._targetRay;
  15621. const grip = this._grip;
  15622. const hand = this._hand;
  15623. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15624. if ( hand && inputSource.hand ) {
  15625. handPose = true;
  15626. for ( const inputjoint of inputSource.hand.values() ) {
  15627. // Update the joints groups with the XRJoint poses
  15628. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15629. // The transform of this joint will be updated with the joint pose on each frame
  15630. const joint = this._getHandJoint( hand, inputjoint );
  15631. if ( jointPose !== null ) {
  15632. joint.matrix.fromArray( jointPose.transform.matrix );
  15633. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15634. joint.matrixWorldNeedsUpdate = true;
  15635. joint.jointRadius = jointPose.radius;
  15636. }
  15637. joint.visible = jointPose !== null;
  15638. }
  15639. // Custom events
  15640. // Check pinchz
  15641. const indexTip = hand.joints[ 'index-finger-tip' ];
  15642. const thumbTip = hand.joints[ 'thumb-tip' ];
  15643. const distance = indexTip.position.distanceTo( thumbTip.position );
  15644. const distanceToPinch = 0.02;
  15645. const threshold = 0.005;
  15646. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15647. hand.inputState.pinching = false;
  15648. this.dispatchEvent( {
  15649. type: 'pinchend',
  15650. handedness: inputSource.handedness,
  15651. target: this
  15652. } );
  15653. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15654. hand.inputState.pinching = true;
  15655. this.dispatchEvent( {
  15656. type: 'pinchstart',
  15657. handedness: inputSource.handedness,
  15658. target: this
  15659. } );
  15660. }
  15661. } else {
  15662. if ( grip !== null && inputSource.gripSpace ) {
  15663. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15664. if ( gripPose !== null ) {
  15665. grip.matrix.fromArray( gripPose.transform.matrix );
  15666. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15667. grip.matrixWorldNeedsUpdate = true;
  15668. if ( gripPose.linearVelocity ) {
  15669. grip.hasLinearVelocity = true;
  15670. grip.linearVelocity.copy( gripPose.linearVelocity );
  15671. } else {
  15672. grip.hasLinearVelocity = false;
  15673. }
  15674. if ( gripPose.angularVelocity ) {
  15675. grip.hasAngularVelocity = true;
  15676. grip.angularVelocity.copy( gripPose.angularVelocity );
  15677. } else {
  15678. grip.hasAngularVelocity = false;
  15679. }
  15680. }
  15681. }
  15682. }
  15683. if ( targetRay !== null ) {
  15684. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15685. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15686. if ( inputPose === null && gripPose !== null ) {
  15687. inputPose = gripPose;
  15688. }
  15689. if ( inputPose !== null ) {
  15690. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15691. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15692. targetRay.matrixWorldNeedsUpdate = true;
  15693. if ( inputPose.linearVelocity ) {
  15694. targetRay.hasLinearVelocity = true;
  15695. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15696. } else {
  15697. targetRay.hasLinearVelocity = false;
  15698. }
  15699. if ( inputPose.angularVelocity ) {
  15700. targetRay.hasAngularVelocity = true;
  15701. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15702. } else {
  15703. targetRay.hasAngularVelocity = false;
  15704. }
  15705. this.dispatchEvent( _moveEvent );
  15706. }
  15707. }
  15708. }
  15709. if ( targetRay !== null ) {
  15710. targetRay.visible = ( inputPose !== null );
  15711. }
  15712. if ( grip !== null ) {
  15713. grip.visible = ( gripPose !== null );
  15714. }
  15715. if ( hand !== null ) {
  15716. hand.visible = ( handPose !== null );
  15717. }
  15718. return this;
  15719. }
  15720. // private method
  15721. _getHandJoint( hand, inputjoint ) {
  15722. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15723. const joint = new Group();
  15724. joint.matrixAutoUpdate = false;
  15725. joint.visible = false;
  15726. hand.joints[ inputjoint.jointName ] = joint;
  15727. hand.add( joint );
  15728. }
  15729. return hand.joints[ inputjoint.jointName ];
  15730. }
  15731. }
  15732. const _occlusion_vertex = `
  15733. void main() {
  15734. gl_Position = vec4( position, 1.0 );
  15735. }`;
  15736. const _occlusion_fragment = `
  15737. uniform sampler2DArray depthColor;
  15738. uniform float depthWidth;
  15739. uniform float depthHeight;
  15740. void main() {
  15741. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  15742. if ( coord.x >= 1.0 ) {
  15743. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  15744. } else {
  15745. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  15746. }
  15747. }`;
  15748. class WebXRDepthSensing {
  15749. constructor() {
  15750. this.texture = null;
  15751. this.mesh = null;
  15752. this.depthNear = 0;
  15753. this.depthFar = 0;
  15754. }
  15755. init( renderer, depthData, renderState ) {
  15756. if ( this.texture === null ) {
  15757. const texture = new Texture();
  15758. const texProps = renderer.properties.get( texture );
  15759. texProps.__webglTexture = depthData.texture;
  15760. if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) {
  15761. this.depthNear = depthData.depthNear;
  15762. this.depthFar = depthData.depthFar;
  15763. }
  15764. this.texture = texture;
  15765. }
  15766. }
  15767. render( renderer, cameraXR ) {
  15768. if ( this.texture !== null ) {
  15769. if ( this.mesh === null ) {
  15770. const viewport = cameraXR.cameras[ 0 ].viewport;
  15771. const material = new ShaderMaterial( {
  15772. vertexShader: _occlusion_vertex,
  15773. fragmentShader: _occlusion_fragment,
  15774. uniforms: {
  15775. depthColor: { value: this.texture },
  15776. depthWidth: { value: viewport.z },
  15777. depthHeight: { value: viewport.w }
  15778. }
  15779. } );
  15780. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  15781. }
  15782. renderer.render( this.mesh, cameraXR );
  15783. }
  15784. }
  15785. reset() {
  15786. this.texture = null;
  15787. this.mesh = null;
  15788. }
  15789. }
  15790. class WebXRManager extends EventDispatcher {
  15791. constructor( renderer, gl ) {
  15792. super();
  15793. const scope = this;
  15794. let session = null;
  15795. let framebufferScaleFactor = 1.0;
  15796. let referenceSpace = null;
  15797. let referenceSpaceType = 'local-floor';
  15798. // Set default foveation to maximum.
  15799. let foveation = 1.0;
  15800. let customReferenceSpace = null;
  15801. let pose = null;
  15802. let glBinding = null;
  15803. let glProjLayer = null;
  15804. let glBaseLayer = null;
  15805. let xrFrame = null;
  15806. const depthSensing = new WebXRDepthSensing();
  15807. const attributes = gl.getContextAttributes();
  15808. let initialRenderTarget = null;
  15809. let newRenderTarget = null;
  15810. const controllers = [];
  15811. const controllerInputSources = [];
  15812. const currentSize = new Vector2();
  15813. let currentPixelRatio = null;
  15814. //
  15815. const cameraL = new PerspectiveCamera();
  15816. cameraL.layers.enable( 1 );
  15817. cameraL.viewport = new Vector4();
  15818. const cameraR = new PerspectiveCamera();
  15819. cameraR.layers.enable( 2 );
  15820. cameraR.viewport = new Vector4();
  15821. const cameras = [ cameraL, cameraR ];
  15822. const cameraXR = new ArrayCamera();
  15823. cameraXR.layers.enable( 1 );
  15824. cameraXR.layers.enable( 2 );
  15825. let _currentDepthNear = null;
  15826. let _currentDepthFar = null;
  15827. //
  15828. this.cameraAutoUpdate = true;
  15829. this.enabled = false;
  15830. this.isPresenting = false;
  15831. this.getController = function ( index ) {
  15832. let controller = controllers[ index ];
  15833. if ( controller === undefined ) {
  15834. controller = new WebXRController();
  15835. controllers[ index ] = controller;
  15836. }
  15837. return controller.getTargetRaySpace();
  15838. };
  15839. this.getControllerGrip = function ( index ) {
  15840. let controller = controllers[ index ];
  15841. if ( controller === undefined ) {
  15842. controller = new WebXRController();
  15843. controllers[ index ] = controller;
  15844. }
  15845. return controller.getGripSpace();
  15846. };
  15847. this.getHand = function ( index ) {
  15848. let controller = controllers[ index ];
  15849. if ( controller === undefined ) {
  15850. controller = new WebXRController();
  15851. controllers[ index ] = controller;
  15852. }
  15853. return controller.getHandSpace();
  15854. };
  15855. //
  15856. function onSessionEvent( event ) {
  15857. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15858. if ( controllerIndex === - 1 ) {
  15859. return;
  15860. }
  15861. const controller = controllers[ controllerIndex ];
  15862. if ( controller !== undefined ) {
  15863. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  15864. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15865. }
  15866. }
  15867. function onSessionEnd() {
  15868. session.removeEventListener( 'select', onSessionEvent );
  15869. session.removeEventListener( 'selectstart', onSessionEvent );
  15870. session.removeEventListener( 'selectend', onSessionEvent );
  15871. session.removeEventListener( 'squeeze', onSessionEvent );
  15872. session.removeEventListener( 'squeezestart', onSessionEvent );
  15873. session.removeEventListener( 'squeezeend', onSessionEvent );
  15874. session.removeEventListener( 'end', onSessionEnd );
  15875. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15876. for ( let i = 0; i < controllers.length; i ++ ) {
  15877. const inputSource = controllerInputSources[ i ];
  15878. if ( inputSource === null ) continue;
  15879. controllerInputSources[ i ] = null;
  15880. controllers[ i ].disconnect( inputSource );
  15881. }
  15882. _currentDepthNear = null;
  15883. _currentDepthFar = null;
  15884. depthSensing.reset();
  15885. // restore framebuffer/rendering state
  15886. renderer.setRenderTarget( initialRenderTarget );
  15887. glBaseLayer = null;
  15888. glProjLayer = null;
  15889. glBinding = null;
  15890. session = null;
  15891. newRenderTarget = null;
  15892. //
  15893. animation.stop();
  15894. scope.isPresenting = false;
  15895. renderer.setPixelRatio( currentPixelRatio );
  15896. renderer.setSize( currentSize.width, currentSize.height, false );
  15897. scope.dispatchEvent( { type: 'sessionend' } );
  15898. }
  15899. this.setFramebufferScaleFactor = function ( value ) {
  15900. framebufferScaleFactor = value;
  15901. if ( scope.isPresenting === true ) {
  15902. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15903. }
  15904. };
  15905. this.setReferenceSpaceType = function ( value ) {
  15906. referenceSpaceType = value;
  15907. if ( scope.isPresenting === true ) {
  15908. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15909. }
  15910. };
  15911. this.getReferenceSpace = function () {
  15912. return customReferenceSpace || referenceSpace;
  15913. };
  15914. this.setReferenceSpace = function ( space ) {
  15915. customReferenceSpace = space;
  15916. };
  15917. this.getBaseLayer = function () {
  15918. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15919. };
  15920. this.getBinding = function () {
  15921. return glBinding;
  15922. };
  15923. this.getFrame = function () {
  15924. return xrFrame;
  15925. };
  15926. this.getSession = function () {
  15927. return session;
  15928. };
  15929. this.setSession = async function ( value ) {
  15930. session = value;
  15931. if ( session !== null ) {
  15932. initialRenderTarget = renderer.getRenderTarget();
  15933. session.addEventListener( 'select', onSessionEvent );
  15934. session.addEventListener( 'selectstart', onSessionEvent );
  15935. session.addEventListener( 'selectend', onSessionEvent );
  15936. session.addEventListener( 'squeeze', onSessionEvent );
  15937. session.addEventListener( 'squeezestart', onSessionEvent );
  15938. session.addEventListener( 'squeezeend', onSessionEvent );
  15939. session.addEventListener( 'end', onSessionEnd );
  15940. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15941. if ( attributes.xrCompatible !== true ) {
  15942. await gl.makeXRCompatible();
  15943. }
  15944. currentPixelRatio = renderer.getPixelRatio();
  15945. renderer.getSize( currentSize );
  15946. if ( session.renderState.layers === undefined ) {
  15947. const layerInit = {
  15948. antialias: attributes.antialias,
  15949. alpha: true,
  15950. depth: attributes.depth,
  15951. stencil: attributes.stencil,
  15952. framebufferScaleFactor: framebufferScaleFactor
  15953. };
  15954. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15955. session.updateRenderState( { baseLayer: glBaseLayer } );
  15956. renderer.setPixelRatio( 1 );
  15957. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  15958. newRenderTarget = new WebGLRenderTarget(
  15959. glBaseLayer.framebufferWidth,
  15960. glBaseLayer.framebufferHeight,
  15961. {
  15962. format: RGBAFormat,
  15963. type: UnsignedByteType,
  15964. colorSpace: renderer.outputColorSpace,
  15965. stencilBuffer: attributes.stencil
  15966. }
  15967. );
  15968. } else {
  15969. let depthFormat = null;
  15970. let depthType = null;
  15971. let glDepthFormat = null;
  15972. if ( attributes.depth ) {
  15973. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15974. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15975. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15976. }
  15977. const projectionlayerInit = {
  15978. colorFormat: gl.RGBA8,
  15979. depthFormat: glDepthFormat,
  15980. scaleFactor: framebufferScaleFactor
  15981. };
  15982. glBinding = new XRWebGLBinding( session, gl );
  15983. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15984. session.updateRenderState( { layers: [ glProjLayer ] } );
  15985. renderer.setPixelRatio( 1 );
  15986. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  15987. newRenderTarget = new WebGLRenderTarget(
  15988. glProjLayer.textureWidth,
  15989. glProjLayer.textureHeight,
  15990. {
  15991. format: RGBAFormat,
  15992. type: UnsignedByteType,
  15993. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15994. stencilBuffer: attributes.stencil,
  15995. colorSpace: renderer.outputColorSpace,
  15996. samples: attributes.antialias ? 4 : 0
  15997. } );
  15998. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15999. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  16000. }
  16001. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  16002. this.setFoveation( foveation );
  16003. customReferenceSpace = null;
  16004. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  16005. animation.setContext( session );
  16006. animation.start();
  16007. scope.isPresenting = true;
  16008. scope.dispatchEvent( { type: 'sessionstart' } );
  16009. }
  16010. };
  16011. this.getEnvironmentBlendMode = function () {
  16012. if ( session !== null ) {
  16013. return session.environmentBlendMode;
  16014. }
  16015. };
  16016. function onInputSourcesChange( event ) {
  16017. // Notify disconnected
  16018. for ( let i = 0; i < event.removed.length; i ++ ) {
  16019. const inputSource = event.removed[ i ];
  16020. const index = controllerInputSources.indexOf( inputSource );
  16021. if ( index >= 0 ) {
  16022. controllerInputSources[ index ] = null;
  16023. controllers[ index ].disconnect( inputSource );
  16024. }
  16025. }
  16026. // Notify connected
  16027. for ( let i = 0; i < event.added.length; i ++ ) {
  16028. const inputSource = event.added[ i ];
  16029. let controllerIndex = controllerInputSources.indexOf( inputSource );
  16030. if ( controllerIndex === - 1 ) {
  16031. // Assign input source a controller that currently has no input source
  16032. for ( let i = 0; i < controllers.length; i ++ ) {
  16033. if ( i >= controllerInputSources.length ) {
  16034. controllerInputSources.push( inputSource );
  16035. controllerIndex = i;
  16036. break;
  16037. } else if ( controllerInputSources[ i ] === null ) {
  16038. controllerInputSources[ i ] = inputSource;
  16039. controllerIndex = i;
  16040. break;
  16041. }
  16042. }
  16043. // If all controllers do currently receive input we ignore new ones
  16044. if ( controllerIndex === - 1 ) break;
  16045. }
  16046. const controller = controllers[ controllerIndex ];
  16047. if ( controller ) {
  16048. controller.connect( inputSource );
  16049. }
  16050. }
  16051. }
  16052. //
  16053. const cameraLPos = new Vector3();
  16054. const cameraRPos = new Vector3();
  16055. /**
  16056. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16057. * the cameras' projection and world matrices have already been set.
  16058. * And that near and far planes are identical for both cameras.
  16059. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16060. */
  16061. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16062. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16063. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16064. const ipd = cameraLPos.distanceTo( cameraRPos );
  16065. const projL = cameraL.projectionMatrix.elements;
  16066. const projR = cameraR.projectionMatrix.elements;
  16067. // VR systems will have identical far and near planes, and
  16068. // most likely identical top and bottom frustum extents.
  16069. // Use the left camera for these values.
  16070. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16071. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16072. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16073. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16074. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16075. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16076. const left = near * leftFov;
  16077. const right = near * rightFov;
  16078. // Calculate the new camera's position offset from the
  16079. // left camera. xOffset should be roughly half `ipd`.
  16080. const zOffset = ipd / ( - leftFov + rightFov );
  16081. const xOffset = zOffset * - leftFov;
  16082. // TODO: Better way to apply this offset?
  16083. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16084. camera.translateX( xOffset );
  16085. camera.translateZ( zOffset );
  16086. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16087. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16088. // Find the union of the frustum values of the cameras and scale
  16089. // the values so that the near plane's position does not change in world space,
  16090. // although must now be relative to the new union camera.
  16091. const near2 = near + zOffset;
  16092. const far2 = far + zOffset;
  16093. const left2 = left - xOffset;
  16094. const right2 = right + ( ipd - xOffset );
  16095. const top2 = topFov * far / far2 * near2;
  16096. const bottom2 = bottomFov * far / far2 * near2;
  16097. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16098. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16099. }
  16100. function updateCamera( camera, parent ) {
  16101. if ( parent === null ) {
  16102. camera.matrixWorld.copy( camera.matrix );
  16103. } else {
  16104. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16105. }
  16106. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16107. }
  16108. this.updateCamera = function ( camera ) {
  16109. if ( session === null ) return;
  16110. if ( depthSensing.texture !== null ) {
  16111. camera.near = depthSensing.depthNear;
  16112. camera.far = depthSensing.depthFar;
  16113. }
  16114. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  16115. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  16116. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16117. // Note that the new renderState won't apply until the next frame. See #18320
  16118. session.updateRenderState( {
  16119. depthNear: cameraXR.near,
  16120. depthFar: cameraXR.far
  16121. } );
  16122. _currentDepthNear = cameraXR.near;
  16123. _currentDepthFar = cameraXR.far;
  16124. cameraL.near = _currentDepthNear;
  16125. cameraL.far = _currentDepthFar;
  16126. cameraR.near = _currentDepthNear;
  16127. cameraR.far = _currentDepthFar;
  16128. cameraL.updateProjectionMatrix();
  16129. cameraR.updateProjectionMatrix();
  16130. camera.updateProjectionMatrix();
  16131. }
  16132. const parent = camera.parent;
  16133. const cameras = cameraXR.cameras;
  16134. updateCamera( cameraXR, parent );
  16135. for ( let i = 0; i < cameras.length; i ++ ) {
  16136. updateCamera( cameras[ i ], parent );
  16137. }
  16138. // update projection matrix for proper view frustum culling
  16139. if ( cameras.length === 2 ) {
  16140. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16141. } else {
  16142. // assume single camera setup (AR)
  16143. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16144. }
  16145. // update user camera and its children
  16146. updateUserCamera( camera, cameraXR, parent );
  16147. };
  16148. function updateUserCamera( camera, cameraXR, parent ) {
  16149. if ( parent === null ) {
  16150. camera.matrix.copy( cameraXR.matrixWorld );
  16151. } else {
  16152. camera.matrix.copy( parent.matrixWorld );
  16153. camera.matrix.invert();
  16154. camera.matrix.multiply( cameraXR.matrixWorld );
  16155. }
  16156. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16157. camera.updateMatrixWorld( true );
  16158. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16159. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16160. if ( camera.isPerspectiveCamera ) {
  16161. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16162. camera.zoom = 1;
  16163. }
  16164. }
  16165. this.getCamera = function () {
  16166. return cameraXR;
  16167. };
  16168. this.getFoveation = function () {
  16169. if ( glProjLayer === null && glBaseLayer === null ) {
  16170. return undefined;
  16171. }
  16172. return foveation;
  16173. };
  16174. this.setFoveation = function ( value ) {
  16175. // 0 = no foveation = full resolution
  16176. // 1 = maximum foveation = the edges render at lower resolution
  16177. foveation = value;
  16178. if ( glProjLayer !== null ) {
  16179. glProjLayer.fixedFoveation = value;
  16180. }
  16181. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16182. glBaseLayer.fixedFoveation = value;
  16183. }
  16184. };
  16185. this.hasDepthSensing = function () {
  16186. return depthSensing.texture !== null;
  16187. };
  16188. // Animation Loop
  16189. let onAnimationFrameCallback = null;
  16190. function onAnimationFrame( time, frame ) {
  16191. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16192. xrFrame = frame;
  16193. if ( pose !== null ) {
  16194. const views = pose.views;
  16195. if ( glBaseLayer !== null ) {
  16196. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16197. renderer.setRenderTarget( newRenderTarget );
  16198. }
  16199. let cameraXRNeedsUpdate = false;
  16200. // check if it's necessary to rebuild cameraXR's camera list
  16201. if ( views.length !== cameraXR.cameras.length ) {
  16202. cameraXR.cameras.length = 0;
  16203. cameraXRNeedsUpdate = true;
  16204. }
  16205. for ( let i = 0; i < views.length; i ++ ) {
  16206. const view = views[ i ];
  16207. let viewport = null;
  16208. if ( glBaseLayer !== null ) {
  16209. viewport = glBaseLayer.getViewport( view );
  16210. } else {
  16211. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16212. viewport = glSubImage.viewport;
  16213. // For side-by-side projection, we only produce a single texture for both eyes.
  16214. if ( i === 0 ) {
  16215. renderer.setRenderTargetTextures(
  16216. newRenderTarget,
  16217. glSubImage.colorTexture,
  16218. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16219. renderer.setRenderTarget( newRenderTarget );
  16220. }
  16221. }
  16222. let camera = cameras[ i ];
  16223. if ( camera === undefined ) {
  16224. camera = new PerspectiveCamera();
  16225. camera.layers.enable( i );
  16226. camera.viewport = new Vector4();
  16227. cameras[ i ] = camera;
  16228. }
  16229. camera.matrix.fromArray( view.transform.matrix );
  16230. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16231. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16232. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16233. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16234. if ( i === 0 ) {
  16235. cameraXR.matrix.copy( camera.matrix );
  16236. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16237. }
  16238. if ( cameraXRNeedsUpdate === true ) {
  16239. cameraXR.cameras.push( camera );
  16240. }
  16241. }
  16242. //
  16243. const enabledFeatures = session.enabledFeatures;
  16244. if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) {
  16245. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  16246. if ( depthData && depthData.isValid && depthData.texture ) {
  16247. depthSensing.init( renderer, depthData, session.renderState );
  16248. }
  16249. }
  16250. }
  16251. //
  16252. for ( let i = 0; i < controllers.length; i ++ ) {
  16253. const inputSource = controllerInputSources[ i ];
  16254. const controller = controllers[ i ];
  16255. if ( inputSource !== null && controller !== undefined ) {
  16256. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16257. }
  16258. }
  16259. depthSensing.render( renderer, cameraXR );
  16260. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16261. if ( frame.detectedPlanes ) {
  16262. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16263. }
  16264. xrFrame = null;
  16265. }
  16266. const animation = new WebGLAnimation();
  16267. animation.setAnimationLoop( onAnimationFrame );
  16268. this.setAnimationLoop = function ( callback ) {
  16269. onAnimationFrameCallback = callback;
  16270. };
  16271. this.dispose = function () {};
  16272. }
  16273. }
  16274. const _e1 = /*@__PURE__*/ new Euler();
  16275. const _m1 = /*@__PURE__*/ new Matrix4();
  16276. function WebGLMaterials( renderer, properties ) {
  16277. function refreshTransformUniform( map, uniform ) {
  16278. if ( map.matrixAutoUpdate === true ) {
  16279. map.updateMatrix();
  16280. }
  16281. uniform.value.copy( map.matrix );
  16282. }
  16283. function refreshFogUniforms( uniforms, fog ) {
  16284. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16285. if ( fog.isFog ) {
  16286. uniforms.fogNear.value = fog.near;
  16287. uniforms.fogFar.value = fog.far;
  16288. } else if ( fog.isFogExp2 ) {
  16289. uniforms.fogDensity.value = fog.density;
  16290. }
  16291. }
  16292. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16293. if ( material.isMeshBasicMaterial ) {
  16294. refreshUniformsCommon( uniforms, material );
  16295. } else if ( material.isMeshLambertMaterial ) {
  16296. refreshUniformsCommon( uniforms, material );
  16297. } else if ( material.isMeshToonMaterial ) {
  16298. refreshUniformsCommon( uniforms, material );
  16299. refreshUniformsToon( uniforms, material );
  16300. } else if ( material.isMeshPhongMaterial ) {
  16301. refreshUniformsCommon( uniforms, material );
  16302. refreshUniformsPhong( uniforms, material );
  16303. } else if ( material.isMeshStandardMaterial ) {
  16304. refreshUniformsCommon( uniforms, material );
  16305. refreshUniformsStandard( uniforms, material );
  16306. if ( material.isMeshPhysicalMaterial ) {
  16307. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16308. }
  16309. } else if ( material.isMeshMatcapMaterial ) {
  16310. refreshUniformsCommon( uniforms, material );
  16311. refreshUniformsMatcap( uniforms, material );
  16312. } else if ( material.isMeshDepthMaterial ) {
  16313. refreshUniformsCommon( uniforms, material );
  16314. } else if ( material.isMeshDistanceMaterial ) {
  16315. refreshUniformsCommon( uniforms, material );
  16316. refreshUniformsDistance( uniforms, material );
  16317. } else if ( material.isMeshNormalMaterial ) {
  16318. refreshUniformsCommon( uniforms, material );
  16319. } else if ( material.isLineBasicMaterial ) {
  16320. refreshUniformsLine( uniforms, material );
  16321. if ( material.isLineDashedMaterial ) {
  16322. refreshUniformsDash( uniforms, material );
  16323. }
  16324. } else if ( material.isPointsMaterial ) {
  16325. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16326. } else if ( material.isSpriteMaterial ) {
  16327. refreshUniformsSprites( uniforms, material );
  16328. } else if ( material.isShadowMaterial ) {
  16329. uniforms.color.value.copy( material.color );
  16330. uniforms.opacity.value = material.opacity;
  16331. } else if ( material.isShaderMaterial ) {
  16332. material.uniformsNeedUpdate = false; // #15581
  16333. }
  16334. }
  16335. function refreshUniformsCommon( uniforms, material ) {
  16336. uniforms.opacity.value = material.opacity;
  16337. if ( material.color ) {
  16338. uniforms.diffuse.value.copy( material.color );
  16339. }
  16340. if ( material.emissive ) {
  16341. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16342. }
  16343. if ( material.map ) {
  16344. uniforms.map.value = material.map;
  16345. refreshTransformUniform( material.map, uniforms.mapTransform );
  16346. }
  16347. if ( material.alphaMap ) {
  16348. uniforms.alphaMap.value = material.alphaMap;
  16349. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16350. }
  16351. if ( material.bumpMap ) {
  16352. uniforms.bumpMap.value = material.bumpMap;
  16353. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16354. uniforms.bumpScale.value = material.bumpScale;
  16355. if ( material.side === BackSide ) {
  16356. uniforms.bumpScale.value *= - 1;
  16357. }
  16358. }
  16359. if ( material.normalMap ) {
  16360. uniforms.normalMap.value = material.normalMap;
  16361. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16362. uniforms.normalScale.value.copy( material.normalScale );
  16363. if ( material.side === BackSide ) {
  16364. uniforms.normalScale.value.negate();
  16365. }
  16366. }
  16367. if ( material.displacementMap ) {
  16368. uniforms.displacementMap.value = material.displacementMap;
  16369. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16370. uniforms.displacementScale.value = material.displacementScale;
  16371. uniforms.displacementBias.value = material.displacementBias;
  16372. }
  16373. if ( material.emissiveMap ) {
  16374. uniforms.emissiveMap.value = material.emissiveMap;
  16375. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16376. }
  16377. if ( material.specularMap ) {
  16378. uniforms.specularMap.value = material.specularMap;
  16379. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16380. }
  16381. if ( material.alphaTest > 0 ) {
  16382. uniforms.alphaTest.value = material.alphaTest;
  16383. }
  16384. const materialProperties = properties.get( material );
  16385. const envMap = materialProperties.envMap;
  16386. const envMapRotation = materialProperties.envMapRotation;
  16387. if ( envMap ) {
  16388. uniforms.envMap.value = envMap;
  16389. _e1.copy( envMapRotation );
  16390. // accommodate left-handed frame
  16391. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  16392. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  16393. // environment maps which are not cube render targets or PMREMs follow a different convention
  16394. _e1.y *= - 1;
  16395. _e1.z *= - 1;
  16396. }
  16397. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  16398. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16399. uniforms.reflectivity.value = material.reflectivity;
  16400. uniforms.ior.value = material.ior;
  16401. uniforms.refractionRatio.value = material.refractionRatio;
  16402. }
  16403. if ( material.lightMap ) {
  16404. uniforms.lightMap.value = material.lightMap;
  16405. // artist-friendly light intensity scaling factor
  16406. const scaleFactor = ( renderer._useLegacyLights === true ) ? Math.PI : 1;
  16407. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16408. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16409. }
  16410. if ( material.aoMap ) {
  16411. uniforms.aoMap.value = material.aoMap;
  16412. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16413. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16414. }
  16415. }
  16416. function refreshUniformsLine( uniforms, material ) {
  16417. uniforms.diffuse.value.copy( material.color );
  16418. uniforms.opacity.value = material.opacity;
  16419. if ( material.map ) {
  16420. uniforms.map.value = material.map;
  16421. refreshTransformUniform( material.map, uniforms.mapTransform );
  16422. }
  16423. }
  16424. function refreshUniformsDash( uniforms, material ) {
  16425. uniforms.dashSize.value = material.dashSize;
  16426. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16427. uniforms.scale.value = material.scale;
  16428. }
  16429. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16430. uniforms.diffuse.value.copy( material.color );
  16431. uniforms.opacity.value = material.opacity;
  16432. uniforms.size.value = material.size * pixelRatio;
  16433. uniforms.scale.value = height * 0.5;
  16434. if ( material.map ) {
  16435. uniforms.map.value = material.map;
  16436. refreshTransformUniform( material.map, uniforms.uvTransform );
  16437. }
  16438. if ( material.alphaMap ) {
  16439. uniforms.alphaMap.value = material.alphaMap;
  16440. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16441. }
  16442. if ( material.alphaTest > 0 ) {
  16443. uniforms.alphaTest.value = material.alphaTest;
  16444. }
  16445. }
  16446. function refreshUniformsSprites( uniforms, material ) {
  16447. uniforms.diffuse.value.copy( material.color );
  16448. uniforms.opacity.value = material.opacity;
  16449. uniforms.rotation.value = material.rotation;
  16450. if ( material.map ) {
  16451. uniforms.map.value = material.map;
  16452. refreshTransformUniform( material.map, uniforms.mapTransform );
  16453. }
  16454. if ( material.alphaMap ) {
  16455. uniforms.alphaMap.value = material.alphaMap;
  16456. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16457. }
  16458. if ( material.alphaTest > 0 ) {
  16459. uniforms.alphaTest.value = material.alphaTest;
  16460. }
  16461. }
  16462. function refreshUniformsPhong( uniforms, material ) {
  16463. uniforms.specular.value.copy( material.specular );
  16464. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16465. }
  16466. function refreshUniformsToon( uniforms, material ) {
  16467. if ( material.gradientMap ) {
  16468. uniforms.gradientMap.value = material.gradientMap;
  16469. }
  16470. }
  16471. function refreshUniformsStandard( uniforms, material ) {
  16472. uniforms.metalness.value = material.metalness;
  16473. if ( material.metalnessMap ) {
  16474. uniforms.metalnessMap.value = material.metalnessMap;
  16475. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16476. }
  16477. uniforms.roughness.value = material.roughness;
  16478. if ( material.roughnessMap ) {
  16479. uniforms.roughnessMap.value = material.roughnessMap;
  16480. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16481. }
  16482. if ( material.envMap ) {
  16483. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16484. uniforms.envMapIntensity.value = material.envMapIntensity;
  16485. }
  16486. }
  16487. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16488. uniforms.ior.value = material.ior; // also part of uniforms common
  16489. if ( material.sheen > 0 ) {
  16490. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16491. uniforms.sheenRoughness.value = material.sheenRoughness;
  16492. if ( material.sheenColorMap ) {
  16493. uniforms.sheenColorMap.value = material.sheenColorMap;
  16494. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16495. }
  16496. if ( material.sheenRoughnessMap ) {
  16497. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16498. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16499. }
  16500. }
  16501. if ( material.clearcoat > 0 ) {
  16502. uniforms.clearcoat.value = material.clearcoat;
  16503. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16504. if ( material.clearcoatMap ) {
  16505. uniforms.clearcoatMap.value = material.clearcoatMap;
  16506. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16507. }
  16508. if ( material.clearcoatRoughnessMap ) {
  16509. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16510. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16511. }
  16512. if ( material.clearcoatNormalMap ) {
  16513. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16514. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16515. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16516. if ( material.side === BackSide ) {
  16517. uniforms.clearcoatNormalScale.value.negate();
  16518. }
  16519. }
  16520. }
  16521. if ( material.iridescence > 0 ) {
  16522. uniforms.iridescence.value = material.iridescence;
  16523. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16524. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16525. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16526. if ( material.iridescenceMap ) {
  16527. uniforms.iridescenceMap.value = material.iridescenceMap;
  16528. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16529. }
  16530. if ( material.iridescenceThicknessMap ) {
  16531. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16532. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16533. }
  16534. }
  16535. if ( material.transmission > 0 ) {
  16536. uniforms.transmission.value = material.transmission;
  16537. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16538. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16539. if ( material.transmissionMap ) {
  16540. uniforms.transmissionMap.value = material.transmissionMap;
  16541. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16542. }
  16543. uniforms.thickness.value = material.thickness;
  16544. if ( material.thicknessMap ) {
  16545. uniforms.thicknessMap.value = material.thicknessMap;
  16546. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16547. }
  16548. uniforms.attenuationDistance.value = material.attenuationDistance;
  16549. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16550. }
  16551. if ( material.anisotropy > 0 ) {
  16552. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16553. if ( material.anisotropyMap ) {
  16554. uniforms.anisotropyMap.value = material.anisotropyMap;
  16555. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16556. }
  16557. }
  16558. uniforms.specularIntensity.value = material.specularIntensity;
  16559. uniforms.specularColor.value.copy( material.specularColor );
  16560. if ( material.specularColorMap ) {
  16561. uniforms.specularColorMap.value = material.specularColorMap;
  16562. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16563. }
  16564. if ( material.specularIntensityMap ) {
  16565. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16566. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16567. }
  16568. }
  16569. function refreshUniformsMatcap( uniforms, material ) {
  16570. if ( material.matcap ) {
  16571. uniforms.matcap.value = material.matcap;
  16572. }
  16573. }
  16574. function refreshUniformsDistance( uniforms, material ) {
  16575. const light = properties.get( material ).light;
  16576. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16577. uniforms.nearDistance.value = light.shadow.camera.near;
  16578. uniforms.farDistance.value = light.shadow.camera.far;
  16579. }
  16580. return {
  16581. refreshFogUniforms: refreshFogUniforms,
  16582. refreshMaterialUniforms: refreshMaterialUniforms
  16583. };
  16584. }
  16585. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16586. let buffers = {};
  16587. let updateList = {};
  16588. let allocatedBindingPoints = [];
  16589. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  16590. function bind( uniformsGroup, program ) {
  16591. const webglProgram = program.program;
  16592. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16593. }
  16594. function update( uniformsGroup, program ) {
  16595. let buffer = buffers[ uniformsGroup.id ];
  16596. if ( buffer === undefined ) {
  16597. prepareUniformsGroup( uniformsGroup );
  16598. buffer = createBuffer( uniformsGroup );
  16599. buffers[ uniformsGroup.id ] = buffer;
  16600. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16601. }
  16602. // ensure to update the binding points/block indices mapping for this program
  16603. const webglProgram = program.program;
  16604. state.updateUBOMapping( uniformsGroup, webglProgram );
  16605. // update UBO once per frame
  16606. const frame = info.render.frame;
  16607. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16608. updateBufferData( uniformsGroup );
  16609. updateList[ uniformsGroup.id ] = frame;
  16610. }
  16611. }
  16612. function createBuffer( uniformsGroup ) {
  16613. // the setup of an UBO is independent of a particular shader program but global
  16614. const bindingPointIndex = allocateBindingPointIndex();
  16615. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16616. const buffer = gl.createBuffer();
  16617. const size = uniformsGroup.__size;
  16618. const usage = uniformsGroup.usage;
  16619. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16620. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16621. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16622. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16623. return buffer;
  16624. }
  16625. function allocateBindingPointIndex() {
  16626. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16627. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16628. allocatedBindingPoints.push( i );
  16629. return i;
  16630. }
  16631. }
  16632. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16633. return 0;
  16634. }
  16635. function updateBufferData( uniformsGroup ) {
  16636. const buffer = buffers[ uniformsGroup.id ];
  16637. const uniforms = uniformsGroup.uniforms;
  16638. const cache = uniformsGroup.__cache;
  16639. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16640. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16641. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16642. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16643. const uniform = uniformArray[ j ];
  16644. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  16645. const offset = uniform.__offset;
  16646. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16647. let arrayOffset = 0;
  16648. for ( let k = 0; k < values.length; k ++ ) {
  16649. const value = values[ k ];
  16650. const info = getUniformSize( value );
  16651. // TODO add integer and struct support
  16652. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16653. uniform.__data[ 0 ] = value;
  16654. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16655. } else if ( value.isMatrix3 ) {
  16656. // manually converting 3x3 to 3x4
  16657. uniform.__data[ 0 ] = value.elements[ 0 ];
  16658. uniform.__data[ 1 ] = value.elements[ 1 ];
  16659. uniform.__data[ 2 ] = value.elements[ 2 ];
  16660. uniform.__data[ 3 ] = 0;
  16661. uniform.__data[ 4 ] = value.elements[ 3 ];
  16662. uniform.__data[ 5 ] = value.elements[ 4 ];
  16663. uniform.__data[ 6 ] = value.elements[ 5 ];
  16664. uniform.__data[ 7 ] = 0;
  16665. uniform.__data[ 8 ] = value.elements[ 6 ];
  16666. uniform.__data[ 9 ] = value.elements[ 7 ];
  16667. uniform.__data[ 10 ] = value.elements[ 8 ];
  16668. uniform.__data[ 11 ] = 0;
  16669. } else {
  16670. value.toArray( uniform.__data, arrayOffset );
  16671. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16672. }
  16673. }
  16674. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16675. }
  16676. }
  16677. }
  16678. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16679. }
  16680. function hasUniformChanged( uniform, index, indexArray, cache ) {
  16681. const value = uniform.value;
  16682. const indexString = index + '_' + indexArray;
  16683. if ( cache[ indexString ] === undefined ) {
  16684. // cache entry does not exist so far
  16685. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16686. cache[ indexString ] = value;
  16687. } else {
  16688. cache[ indexString ] = value.clone();
  16689. }
  16690. return true;
  16691. } else {
  16692. const cachedObject = cache[ indexString ];
  16693. // compare current value with cached entry
  16694. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16695. if ( cachedObject !== value ) {
  16696. cache[ indexString ] = value;
  16697. return true;
  16698. }
  16699. } else {
  16700. if ( cachedObject.equals( value ) === false ) {
  16701. cachedObject.copy( value );
  16702. return true;
  16703. }
  16704. }
  16705. }
  16706. return false;
  16707. }
  16708. function prepareUniformsGroup( uniformsGroup ) {
  16709. // determine total buffer size according to the STD140 layout
  16710. // Hint: STD140 is the only supported layout in WebGL 2
  16711. const uniforms = uniformsGroup.uniforms;
  16712. let offset = 0; // global buffer offset in bytes
  16713. const chunkSize = 16; // size of a chunk in bytes
  16714. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16715. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16716. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16717. const uniform = uniformArray[ j ];
  16718. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16719. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  16720. const value = values[ k ];
  16721. const info = getUniformSize( value );
  16722. // Calculate the chunk offset
  16723. const chunkOffsetUniform = offset % chunkSize;
  16724. // Check for chunk overflow
  16725. if ( chunkOffsetUniform !== 0 && ( chunkSize - chunkOffsetUniform ) < info.boundary ) {
  16726. // Add padding and adjust offset
  16727. offset += ( chunkSize - chunkOffsetUniform );
  16728. }
  16729. // the following two properties will be used for partial buffer updates
  16730. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  16731. uniform.__offset = offset;
  16732. // Update the global offset
  16733. offset += info.storage;
  16734. }
  16735. }
  16736. }
  16737. // ensure correct final padding
  16738. const chunkOffset = offset % chunkSize;
  16739. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16740. //
  16741. uniformsGroup.__size = offset;
  16742. uniformsGroup.__cache = {};
  16743. return this;
  16744. }
  16745. function getUniformSize( value ) {
  16746. const info = {
  16747. boundary: 0, // bytes
  16748. storage: 0 // bytes
  16749. };
  16750. // determine sizes according to STD140
  16751. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16752. // float/int/bool
  16753. info.boundary = 4;
  16754. info.storage = 4;
  16755. } else if ( value.isVector2 ) {
  16756. // vec2
  16757. info.boundary = 8;
  16758. info.storage = 8;
  16759. } else if ( value.isVector3 || value.isColor ) {
  16760. // vec3
  16761. info.boundary = 16;
  16762. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16763. } else if ( value.isVector4 ) {
  16764. // vec4
  16765. info.boundary = 16;
  16766. info.storage = 16;
  16767. } else if ( value.isMatrix3 ) {
  16768. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16769. info.boundary = 48;
  16770. info.storage = 48;
  16771. } else if ( value.isMatrix4 ) {
  16772. // mat4
  16773. info.boundary = 64;
  16774. info.storage = 64;
  16775. } else if ( value.isTexture ) {
  16776. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16777. } else {
  16778. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16779. }
  16780. return info;
  16781. }
  16782. function onUniformsGroupsDispose( event ) {
  16783. const uniformsGroup = event.target;
  16784. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16785. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16786. allocatedBindingPoints.splice( index, 1 );
  16787. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16788. delete buffers[ uniformsGroup.id ];
  16789. delete updateList[ uniformsGroup.id ];
  16790. }
  16791. function dispose() {
  16792. for ( const id in buffers ) {
  16793. gl.deleteBuffer( buffers[ id ] );
  16794. }
  16795. allocatedBindingPoints = [];
  16796. buffers = {};
  16797. updateList = {};
  16798. }
  16799. return {
  16800. bind: bind,
  16801. update: update,
  16802. dispose: dispose
  16803. };
  16804. }
  16805. class WebGLRenderer {
  16806. constructor( parameters = {} ) {
  16807. const {
  16808. canvas = createCanvasElement(),
  16809. context = null,
  16810. depth = true,
  16811. stencil = false,
  16812. alpha = false,
  16813. antialias = false,
  16814. premultipliedAlpha = true,
  16815. preserveDrawingBuffer = false,
  16816. powerPreference = 'default',
  16817. failIfMajorPerformanceCaveat = false,
  16818. } = parameters;
  16819. this.isWebGLRenderer = true;
  16820. let _alpha;
  16821. if ( context !== null ) {
  16822. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  16823. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  16824. }
  16825. _alpha = context.getContextAttributes().alpha;
  16826. } else {
  16827. _alpha = alpha;
  16828. }
  16829. const uintClearColor = new Uint32Array( 4 );
  16830. const intClearColor = new Int32Array( 4 );
  16831. let currentRenderList = null;
  16832. let currentRenderState = null;
  16833. // render() can be called from within a callback triggered by another render.
  16834. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16835. const renderListStack = [];
  16836. const renderStateStack = [];
  16837. // public properties
  16838. this.domElement = canvas;
  16839. // Debug configuration container
  16840. this.debug = {
  16841. /**
  16842. * Enables error checking and reporting when shader programs are being compiled
  16843. * @type {boolean}
  16844. */
  16845. checkShaderErrors: true,
  16846. /**
  16847. * Callback for custom error reporting.
  16848. * @type {?Function}
  16849. */
  16850. onShaderError: null
  16851. };
  16852. // clearing
  16853. this.autoClear = true;
  16854. this.autoClearColor = true;
  16855. this.autoClearDepth = true;
  16856. this.autoClearStencil = true;
  16857. // scene graph
  16858. this.sortObjects = true;
  16859. // user-defined clipping
  16860. this.clippingPlanes = [];
  16861. this.localClippingEnabled = false;
  16862. // physically based shading
  16863. this._outputColorSpace = SRGBColorSpace;
  16864. // physical lights
  16865. this._useLegacyLights = false;
  16866. // tone mapping
  16867. this.toneMapping = NoToneMapping;
  16868. this.toneMappingExposure = 1.0;
  16869. // internal properties
  16870. const _this = this;
  16871. let _isContextLost = false;
  16872. // internal state cache
  16873. let _currentActiveCubeFace = 0;
  16874. let _currentActiveMipmapLevel = 0;
  16875. let _currentRenderTarget = null;
  16876. let _currentMaterialId = - 1;
  16877. let _currentCamera = null;
  16878. const _currentViewport = new Vector4();
  16879. const _currentScissor = new Vector4();
  16880. let _currentScissorTest = null;
  16881. const _currentClearColor = new Color( 0x000000 );
  16882. let _currentClearAlpha = 0;
  16883. //
  16884. let _width = canvas.width;
  16885. let _height = canvas.height;
  16886. let _pixelRatio = 1;
  16887. let _opaqueSort = null;
  16888. let _transparentSort = null;
  16889. const _viewport = new Vector4( 0, 0, _width, _height );
  16890. const _scissor = new Vector4( 0, 0, _width, _height );
  16891. let _scissorTest = false;
  16892. // frustum
  16893. const _frustum = new Frustum();
  16894. // clipping
  16895. let _clippingEnabled = false;
  16896. let _localClippingEnabled = false;
  16897. // camera matrices cache
  16898. const _projScreenMatrix = new Matrix4();
  16899. const _vector2 = new Vector2();
  16900. const _vector3 = new Vector3();
  16901. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16902. function getTargetPixelRatio() {
  16903. return _currentRenderTarget === null ? _pixelRatio : 1;
  16904. }
  16905. // initialize
  16906. let _gl = context;
  16907. function getContext( contextName, contextAttributes ) {
  16908. const context = canvas.getContext( contextName, contextAttributes );
  16909. if ( context !== null ) return context;
  16910. return null;
  16911. }
  16912. try {
  16913. const contextAttributes = {
  16914. alpha: true,
  16915. depth,
  16916. stencil,
  16917. antialias,
  16918. premultipliedAlpha,
  16919. preserveDrawingBuffer,
  16920. powerPreference,
  16921. failIfMajorPerformanceCaveat,
  16922. };
  16923. // OffscreenCanvas does not have setAttribute, see #22811
  16924. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16925. // event listeners must be registered before WebGL context is created, see #12753
  16926. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16927. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16928. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16929. if ( _gl === null ) {
  16930. const contextName = 'webgl2';
  16931. _gl = getContext( contextName, contextAttributes );
  16932. if ( _gl === null ) {
  16933. if ( getContext( contextName ) ) {
  16934. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16935. } else {
  16936. throw new Error( 'Error creating WebGL context.' );
  16937. }
  16938. }
  16939. }
  16940. } catch ( error ) {
  16941. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16942. throw error;
  16943. }
  16944. let extensions, capabilities, state, info;
  16945. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16946. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16947. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16948. let utils, bindingStates, uniformsGroups;
  16949. function initGLContext() {
  16950. extensions = new WebGLExtensions( _gl );
  16951. extensions.init();
  16952. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16953. utils = new WebGLUtils( _gl, extensions );
  16954. state = new WebGLState( _gl );
  16955. info = new WebGLInfo( _gl );
  16956. properties = new WebGLProperties();
  16957. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16958. cubemaps = new WebGLCubeMaps( _this );
  16959. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16960. attributes = new WebGLAttributes( _gl );
  16961. bindingStates = new WebGLBindingStates( _gl, attributes );
  16962. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16963. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16964. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16965. clipping = new WebGLClipping( properties );
  16966. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16967. materials = new WebGLMaterials( _this, properties );
  16968. renderLists = new WebGLRenderLists();
  16969. renderStates = new WebGLRenderStates( extensions );
  16970. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16971. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16972. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16973. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  16974. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  16975. info.programs = programCache.programs;
  16976. _this.capabilities = capabilities;
  16977. _this.extensions = extensions;
  16978. _this.properties = properties;
  16979. _this.renderLists = renderLists;
  16980. _this.shadowMap = shadowMap;
  16981. _this.state = state;
  16982. _this.info = info;
  16983. }
  16984. initGLContext();
  16985. // xr
  16986. const xr = new WebXRManager( _this, _gl );
  16987. this.xr = xr;
  16988. // API
  16989. this.getContext = function () {
  16990. return _gl;
  16991. };
  16992. this.getContextAttributes = function () {
  16993. return _gl.getContextAttributes();
  16994. };
  16995. this.forceContextLoss = function () {
  16996. const extension = extensions.get( 'WEBGL_lose_context' );
  16997. if ( extension ) extension.loseContext();
  16998. };
  16999. this.forceContextRestore = function () {
  17000. const extension = extensions.get( 'WEBGL_lose_context' );
  17001. if ( extension ) extension.restoreContext();
  17002. };
  17003. this.getPixelRatio = function () {
  17004. return _pixelRatio;
  17005. };
  17006. this.setPixelRatio = function ( value ) {
  17007. if ( value === undefined ) return;
  17008. _pixelRatio = value;
  17009. this.setSize( _width, _height, false );
  17010. };
  17011. this.getSize = function ( target ) {
  17012. return target.set( _width, _height );
  17013. };
  17014. this.setSize = function ( width, height, updateStyle = true ) {
  17015. if ( xr.isPresenting ) {
  17016. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17017. return;
  17018. }
  17019. _width = width;
  17020. _height = height;
  17021. canvas.width = Math.floor( width * _pixelRatio );
  17022. canvas.height = Math.floor( height * _pixelRatio );
  17023. if ( updateStyle === true ) {
  17024. canvas.style.width = width + 'px';
  17025. canvas.style.height = height + 'px';
  17026. }
  17027. this.setViewport( 0, 0, width, height );
  17028. };
  17029. this.getDrawingBufferSize = function ( target ) {
  17030. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  17031. };
  17032. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17033. _width = width;
  17034. _height = height;
  17035. _pixelRatio = pixelRatio;
  17036. canvas.width = Math.floor( width * pixelRatio );
  17037. canvas.height = Math.floor( height * pixelRatio );
  17038. this.setViewport( 0, 0, width, height );
  17039. };
  17040. this.getCurrentViewport = function ( target ) {
  17041. return target.copy( _currentViewport );
  17042. };
  17043. this.getViewport = function ( target ) {
  17044. return target.copy( _viewport );
  17045. };
  17046. this.setViewport = function ( x, y, width, height ) {
  17047. if ( x.isVector4 ) {
  17048. _viewport.set( x.x, x.y, x.z, x.w );
  17049. } else {
  17050. _viewport.set( x, y, width, height );
  17051. }
  17052. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  17053. };
  17054. this.getScissor = function ( target ) {
  17055. return target.copy( _scissor );
  17056. };
  17057. this.setScissor = function ( x, y, width, height ) {
  17058. if ( x.isVector4 ) {
  17059. _scissor.set( x.x, x.y, x.z, x.w );
  17060. } else {
  17061. _scissor.set( x, y, width, height );
  17062. }
  17063. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  17064. };
  17065. this.getScissorTest = function () {
  17066. return _scissorTest;
  17067. };
  17068. this.setScissorTest = function ( boolean ) {
  17069. state.setScissorTest( _scissorTest = boolean );
  17070. };
  17071. this.setOpaqueSort = function ( method ) {
  17072. _opaqueSort = method;
  17073. };
  17074. this.setTransparentSort = function ( method ) {
  17075. _transparentSort = method;
  17076. };
  17077. // Clearing
  17078. this.getClearColor = function ( target ) {
  17079. return target.copy( background.getClearColor() );
  17080. };
  17081. this.setClearColor = function () {
  17082. background.setClearColor.apply( background, arguments );
  17083. };
  17084. this.getClearAlpha = function () {
  17085. return background.getClearAlpha();
  17086. };
  17087. this.setClearAlpha = function () {
  17088. background.setClearAlpha.apply( background, arguments );
  17089. };
  17090. this.clear = function ( color = true, depth = true, stencil = true ) {
  17091. let bits = 0;
  17092. if ( color ) {
  17093. // check if we're trying to clear an integer target
  17094. let isIntegerFormat = false;
  17095. if ( _currentRenderTarget !== null ) {
  17096. const targetFormat = _currentRenderTarget.texture.format;
  17097. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17098. targetFormat === RGIntegerFormat ||
  17099. targetFormat === RedIntegerFormat;
  17100. }
  17101. // use the appropriate clear functions to clear the target if it's a signed
  17102. // or unsigned integer target
  17103. if ( isIntegerFormat ) {
  17104. const targetType = _currentRenderTarget.texture.type;
  17105. const isUnsignedType = targetType === UnsignedByteType ||
  17106. targetType === UnsignedIntType ||
  17107. targetType === UnsignedShortType ||
  17108. targetType === UnsignedInt248Type ||
  17109. targetType === UnsignedShort4444Type ||
  17110. targetType === UnsignedShort5551Type;
  17111. const clearColor = background.getClearColor();
  17112. const a = background.getClearAlpha();
  17113. const r = clearColor.r;
  17114. const g = clearColor.g;
  17115. const b = clearColor.b;
  17116. if ( isUnsignedType ) {
  17117. uintClearColor[ 0 ] = r;
  17118. uintClearColor[ 1 ] = g;
  17119. uintClearColor[ 2 ] = b;
  17120. uintClearColor[ 3 ] = a;
  17121. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17122. } else {
  17123. intClearColor[ 0 ] = r;
  17124. intClearColor[ 1 ] = g;
  17125. intClearColor[ 2 ] = b;
  17126. intClearColor[ 3 ] = a;
  17127. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17128. }
  17129. } else {
  17130. bits |= _gl.COLOR_BUFFER_BIT;
  17131. }
  17132. }
  17133. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17134. if ( stencil ) {
  17135. bits |= _gl.STENCIL_BUFFER_BIT;
  17136. this.state.buffers.stencil.setMask( 0xffffffff );
  17137. }
  17138. _gl.clear( bits );
  17139. };
  17140. this.clearColor = function () {
  17141. this.clear( true, false, false );
  17142. };
  17143. this.clearDepth = function () {
  17144. this.clear( false, true, false );
  17145. };
  17146. this.clearStencil = function () {
  17147. this.clear( false, false, true );
  17148. };
  17149. //
  17150. this.dispose = function () {
  17151. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17152. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17153. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17154. renderLists.dispose();
  17155. renderStates.dispose();
  17156. properties.dispose();
  17157. cubemaps.dispose();
  17158. cubeuvmaps.dispose();
  17159. objects.dispose();
  17160. bindingStates.dispose();
  17161. uniformsGroups.dispose();
  17162. programCache.dispose();
  17163. xr.dispose();
  17164. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17165. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17166. animation.stop();
  17167. };
  17168. // Events
  17169. function onContextLost( event ) {
  17170. event.preventDefault();
  17171. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17172. _isContextLost = true;
  17173. }
  17174. function onContextRestore( /* event */ ) {
  17175. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17176. _isContextLost = false;
  17177. const infoAutoReset = info.autoReset;
  17178. const shadowMapEnabled = shadowMap.enabled;
  17179. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17180. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17181. const shadowMapType = shadowMap.type;
  17182. initGLContext();
  17183. info.autoReset = infoAutoReset;
  17184. shadowMap.enabled = shadowMapEnabled;
  17185. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17186. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17187. shadowMap.type = shadowMapType;
  17188. }
  17189. function onContextCreationError( event ) {
  17190. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17191. }
  17192. function onMaterialDispose( event ) {
  17193. const material = event.target;
  17194. material.removeEventListener( 'dispose', onMaterialDispose );
  17195. deallocateMaterial( material );
  17196. }
  17197. // Buffer deallocation
  17198. function deallocateMaterial( material ) {
  17199. releaseMaterialProgramReferences( material );
  17200. properties.remove( material );
  17201. }
  17202. function releaseMaterialProgramReferences( material ) {
  17203. const programs = properties.get( material ).programs;
  17204. if ( programs !== undefined ) {
  17205. programs.forEach( function ( program ) {
  17206. programCache.releaseProgram( program );
  17207. } );
  17208. if ( material.isShaderMaterial ) {
  17209. programCache.releaseShaderCache( material );
  17210. }
  17211. }
  17212. }
  17213. // Buffer rendering
  17214. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17215. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17216. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17217. const program = setProgram( camera, scene, geometry, material, object );
  17218. state.setMaterial( material, frontFaceCW );
  17219. //
  17220. let index = geometry.index;
  17221. let rangeFactor = 1;
  17222. if ( material.wireframe === true ) {
  17223. index = geometries.getWireframeAttribute( geometry );
  17224. if ( index === undefined ) return;
  17225. rangeFactor = 2;
  17226. }
  17227. //
  17228. const drawRange = geometry.drawRange;
  17229. const position = geometry.attributes.position;
  17230. let drawStart = drawRange.start * rangeFactor;
  17231. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17232. if ( group !== null ) {
  17233. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17234. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17235. }
  17236. if ( index !== null ) {
  17237. drawStart = Math.max( drawStart, 0 );
  17238. drawEnd = Math.min( drawEnd, index.count );
  17239. } else if ( position !== undefined && position !== null ) {
  17240. drawStart = Math.max( drawStart, 0 );
  17241. drawEnd = Math.min( drawEnd, position.count );
  17242. }
  17243. const drawCount = drawEnd - drawStart;
  17244. if ( drawCount < 0 || drawCount === Infinity ) return;
  17245. //
  17246. bindingStates.setup( object, material, program, geometry, index );
  17247. let attribute;
  17248. let renderer = bufferRenderer;
  17249. if ( index !== null ) {
  17250. attribute = attributes.get( index );
  17251. renderer = indexedBufferRenderer;
  17252. renderer.setIndex( attribute );
  17253. }
  17254. //
  17255. if ( object.isMesh ) {
  17256. if ( material.wireframe === true ) {
  17257. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17258. renderer.setMode( _gl.LINES );
  17259. } else {
  17260. renderer.setMode( _gl.TRIANGLES );
  17261. }
  17262. } else if ( object.isLine ) {
  17263. let lineWidth = material.linewidth;
  17264. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17265. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17266. if ( object.isLineSegments ) {
  17267. renderer.setMode( _gl.LINES );
  17268. } else if ( object.isLineLoop ) {
  17269. renderer.setMode( _gl.LINE_LOOP );
  17270. } else {
  17271. renderer.setMode( _gl.LINE_STRIP );
  17272. }
  17273. } else if ( object.isPoints ) {
  17274. renderer.setMode( _gl.POINTS );
  17275. } else if ( object.isSprite ) {
  17276. renderer.setMode( _gl.TRIANGLES );
  17277. }
  17278. if ( object.isBatchedMesh ) {
  17279. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  17280. } else if ( object.isInstancedMesh ) {
  17281. renderer.renderInstances( drawStart, drawCount, object.count );
  17282. } else if ( geometry.isInstancedBufferGeometry ) {
  17283. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17284. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17285. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17286. } else {
  17287. renderer.render( drawStart, drawCount );
  17288. }
  17289. };
  17290. // Compile
  17291. function prepareMaterial( material, scene, object ) {
  17292. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17293. material.side = BackSide;
  17294. material.needsUpdate = true;
  17295. getProgram( material, scene, object );
  17296. material.side = FrontSide;
  17297. material.needsUpdate = true;
  17298. getProgram( material, scene, object );
  17299. material.side = DoubleSide;
  17300. } else {
  17301. getProgram( material, scene, object );
  17302. }
  17303. }
  17304. this.compile = function ( scene, camera, targetScene = null ) {
  17305. if ( targetScene === null ) targetScene = scene;
  17306. currentRenderState = renderStates.get( targetScene );
  17307. currentRenderState.init();
  17308. renderStateStack.push( currentRenderState );
  17309. // gather lights from both the target scene and the new object that will be added to the scene.
  17310. targetScene.traverseVisible( function ( object ) {
  17311. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17312. currentRenderState.pushLight( object );
  17313. if ( object.castShadow ) {
  17314. currentRenderState.pushShadow( object );
  17315. }
  17316. }
  17317. } );
  17318. if ( scene !== targetScene ) {
  17319. scene.traverseVisible( function ( object ) {
  17320. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17321. currentRenderState.pushLight( object );
  17322. if ( object.castShadow ) {
  17323. currentRenderState.pushShadow( object );
  17324. }
  17325. }
  17326. } );
  17327. }
  17328. currentRenderState.setupLights( _this._useLegacyLights );
  17329. // Only initialize materials in the new scene, not the targetScene.
  17330. const materials = new Set();
  17331. scene.traverse( function ( object ) {
  17332. const material = object.material;
  17333. if ( material ) {
  17334. if ( Array.isArray( material ) ) {
  17335. for ( let i = 0; i < material.length; i ++ ) {
  17336. const material2 = material[ i ];
  17337. prepareMaterial( material2, targetScene, object );
  17338. materials.add( material2 );
  17339. }
  17340. } else {
  17341. prepareMaterial( material, targetScene, object );
  17342. materials.add( material );
  17343. }
  17344. }
  17345. } );
  17346. renderStateStack.pop();
  17347. currentRenderState = null;
  17348. return materials;
  17349. };
  17350. // compileAsync
  17351. this.compileAsync = function ( scene, camera, targetScene = null ) {
  17352. const materials = this.compile( scene, camera, targetScene );
  17353. // Wait for all the materials in the new object to indicate that they're
  17354. // ready to be used before resolving the promise.
  17355. return new Promise( ( resolve ) => {
  17356. function checkMaterialsReady() {
  17357. materials.forEach( function ( material ) {
  17358. const materialProperties = properties.get( material );
  17359. const program = materialProperties.currentProgram;
  17360. if ( program.isReady() ) {
  17361. // remove any programs that report they're ready to use from the list
  17362. materials.delete( material );
  17363. }
  17364. } );
  17365. // once the list of compiling materials is empty, call the callback
  17366. if ( materials.size === 0 ) {
  17367. resolve( scene );
  17368. return;
  17369. }
  17370. // if some materials are still not ready, wait a bit and check again
  17371. setTimeout( checkMaterialsReady, 10 );
  17372. }
  17373. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  17374. // If we can check the compilation status of the materials without
  17375. // blocking then do so right away.
  17376. checkMaterialsReady();
  17377. } else {
  17378. // Otherwise start by waiting a bit to give the materials we just
  17379. // initialized a chance to finish.
  17380. setTimeout( checkMaterialsReady, 10 );
  17381. }
  17382. } );
  17383. };
  17384. // Animation Loop
  17385. let onAnimationFrameCallback = null;
  17386. function onAnimationFrame( time ) {
  17387. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17388. }
  17389. function onXRSessionStart() {
  17390. animation.stop();
  17391. }
  17392. function onXRSessionEnd() {
  17393. animation.start();
  17394. }
  17395. const animation = new WebGLAnimation();
  17396. animation.setAnimationLoop( onAnimationFrame );
  17397. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17398. this.setAnimationLoop = function ( callback ) {
  17399. onAnimationFrameCallback = callback;
  17400. xr.setAnimationLoop( callback );
  17401. ( callback === null ) ? animation.stop() : animation.start();
  17402. };
  17403. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17404. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17405. // Rendering
  17406. this.render = function ( scene, camera ) {
  17407. if ( camera !== undefined && camera.isCamera !== true ) {
  17408. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17409. return;
  17410. }
  17411. if ( _isContextLost === true ) return;
  17412. // update scene graph
  17413. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17414. // update camera matrices and frustum
  17415. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17416. if ( xr.enabled === true && xr.isPresenting === true ) {
  17417. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17418. camera = xr.getCamera(); // use XR camera for rendering
  17419. }
  17420. //
  17421. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17422. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17423. currentRenderState.init();
  17424. renderStateStack.push( currentRenderState );
  17425. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17426. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17427. _localClippingEnabled = this.localClippingEnabled;
  17428. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17429. currentRenderList = renderLists.get( scene, renderListStack.length );
  17430. currentRenderList.init();
  17431. renderListStack.push( currentRenderList );
  17432. projectObject( scene, camera, 0, _this.sortObjects );
  17433. currentRenderList.finish();
  17434. if ( _this.sortObjects === true ) {
  17435. currentRenderList.sort( _opaqueSort, _transparentSort );
  17436. }
  17437. //
  17438. this.info.render.frame ++;
  17439. if ( _clippingEnabled === true ) clipping.beginShadows();
  17440. const shadowsArray = currentRenderState.state.shadowsArray;
  17441. shadowMap.render( shadowsArray, scene, camera );
  17442. if ( _clippingEnabled === true ) clipping.endShadows();
  17443. //
  17444. if ( this.info.autoReset === true ) this.info.reset();
  17445. //
  17446. if ( xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false ) {
  17447. background.render( currentRenderList, scene );
  17448. }
  17449. // render scene
  17450. currentRenderState.setupLights( _this._useLegacyLights );
  17451. if ( camera.isArrayCamera ) {
  17452. const cameras = camera.cameras;
  17453. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17454. const camera2 = cameras[ i ];
  17455. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17456. }
  17457. } else {
  17458. renderScene( currentRenderList, scene, camera );
  17459. }
  17460. //
  17461. if ( _currentRenderTarget !== null ) {
  17462. // resolve multisample renderbuffers to a single-sample texture if necessary
  17463. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17464. // Generate mipmap if we're using any kind of mipmap filtering
  17465. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17466. }
  17467. //
  17468. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17469. // _gl.finish();
  17470. bindingStates.resetDefaultState();
  17471. _currentMaterialId = - 1;
  17472. _currentCamera = null;
  17473. renderStateStack.pop();
  17474. if ( renderStateStack.length > 0 ) {
  17475. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17476. } else {
  17477. currentRenderState = null;
  17478. }
  17479. renderListStack.pop();
  17480. if ( renderListStack.length > 0 ) {
  17481. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17482. } else {
  17483. currentRenderList = null;
  17484. }
  17485. };
  17486. function projectObject( object, camera, groupOrder, sortObjects ) {
  17487. if ( object.visible === false ) return;
  17488. const visible = object.layers.test( camera.layers );
  17489. if ( visible ) {
  17490. if ( object.isGroup ) {
  17491. groupOrder = object.renderOrder;
  17492. } else if ( object.isLOD ) {
  17493. if ( object.autoUpdate === true ) object.update( camera );
  17494. } else if ( object.isLight ) {
  17495. currentRenderState.pushLight( object );
  17496. if ( object.castShadow ) {
  17497. currentRenderState.pushShadow( object );
  17498. }
  17499. } else if ( object.isSprite ) {
  17500. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17501. if ( sortObjects ) {
  17502. _vector3.setFromMatrixPosition( object.matrixWorld )
  17503. .applyMatrix4( _projScreenMatrix );
  17504. }
  17505. const geometry = objects.update( object );
  17506. const material = object.material;
  17507. if ( material.visible ) {
  17508. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17509. }
  17510. }
  17511. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17512. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17513. const geometry = objects.update( object );
  17514. const material = object.material;
  17515. if ( sortObjects ) {
  17516. if ( object.boundingSphere !== undefined ) {
  17517. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17518. _vector3.copy( object.boundingSphere.center );
  17519. } else {
  17520. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17521. _vector3.copy( geometry.boundingSphere.center );
  17522. }
  17523. _vector3
  17524. .applyMatrix4( object.matrixWorld )
  17525. .applyMatrix4( _projScreenMatrix );
  17526. }
  17527. if ( Array.isArray( material ) ) {
  17528. const groups = geometry.groups;
  17529. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17530. const group = groups[ i ];
  17531. const groupMaterial = material[ group.materialIndex ];
  17532. if ( groupMaterial && groupMaterial.visible ) {
  17533. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17534. }
  17535. }
  17536. } else if ( material.visible ) {
  17537. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17538. }
  17539. }
  17540. }
  17541. }
  17542. const children = object.children;
  17543. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17544. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17545. }
  17546. }
  17547. function renderScene( currentRenderList, scene, camera, viewport ) {
  17548. const opaqueObjects = currentRenderList.opaque;
  17549. const transmissiveObjects = currentRenderList.transmissive;
  17550. const transparentObjects = currentRenderList.transparent;
  17551. currentRenderState.setupLightsView( camera );
  17552. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17553. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17554. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17555. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17556. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17557. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17558. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17559. state.buffers.depth.setTest( true );
  17560. state.buffers.depth.setMask( true );
  17561. state.buffers.color.setMask( true );
  17562. state.setPolygonOffset( false );
  17563. }
  17564. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17565. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17566. if ( overrideMaterial !== null ) {
  17567. return;
  17568. }
  17569. if ( currentRenderState.state.transmissionRenderTarget === null ) {
  17570. currentRenderState.state.transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  17571. generateMipmaps: true,
  17572. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  17573. minFilter: LinearMipmapLinearFilter,
  17574. samples: 4,
  17575. stencilBuffer: stencil
  17576. } );
  17577. const renderTargetProperties = properties.get( currentRenderState.state.transmissionRenderTarget );
  17578. renderTargetProperties.__isTransmissionRenderTarget = true;
  17579. // debug
  17580. /*
  17581. const geometry = new PlaneGeometry();
  17582. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17583. const mesh = new Mesh( geometry, material );
  17584. scene.add( mesh );
  17585. */
  17586. }
  17587. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget;
  17588. _this.getDrawingBufferSize( _vector2 );
  17589. transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  17590. //
  17591. const currentRenderTarget = _this.getRenderTarget();
  17592. _this.setRenderTarget( transmissionRenderTarget );
  17593. _this.getClearColor( _currentClearColor );
  17594. _currentClearAlpha = _this.getClearAlpha();
  17595. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17596. _this.clear();
  17597. // Turn off the features which can affect the frag color for opaque objects pass.
  17598. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17599. const currentToneMapping = _this.toneMapping;
  17600. _this.toneMapping = NoToneMapping;
  17601. renderObjects( opaqueObjects, scene, camera );
  17602. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17603. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17604. let renderTargetNeedsUpdate = false;
  17605. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17606. const renderItem = transmissiveObjects[ i ];
  17607. const object = renderItem.object;
  17608. const geometry = renderItem.geometry;
  17609. const material = renderItem.material;
  17610. const group = renderItem.group;
  17611. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17612. const currentSide = material.side;
  17613. material.side = BackSide;
  17614. material.needsUpdate = true;
  17615. renderObject( object, scene, camera, geometry, material, group );
  17616. material.side = currentSide;
  17617. material.needsUpdate = true;
  17618. renderTargetNeedsUpdate = true;
  17619. }
  17620. }
  17621. if ( renderTargetNeedsUpdate === true ) {
  17622. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  17623. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  17624. }
  17625. _this.setRenderTarget( currentRenderTarget );
  17626. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17627. _this.toneMapping = currentToneMapping;
  17628. }
  17629. function renderObjects( renderList, scene, camera ) {
  17630. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17631. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17632. const renderItem = renderList[ i ];
  17633. const object = renderItem.object;
  17634. const geometry = renderItem.geometry;
  17635. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17636. const group = renderItem.group;
  17637. if ( object.layers.test( camera.layers ) ) {
  17638. renderObject( object, scene, camera, geometry, material, group );
  17639. }
  17640. }
  17641. }
  17642. function renderObject( object, scene, camera, geometry, material, group ) {
  17643. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17644. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17645. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17646. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17647. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17648. material.side = BackSide;
  17649. material.needsUpdate = true;
  17650. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17651. material.side = FrontSide;
  17652. material.needsUpdate = true;
  17653. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17654. material.side = DoubleSide;
  17655. } else {
  17656. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17657. }
  17658. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17659. }
  17660. function getProgram( material, scene, object ) {
  17661. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17662. const materialProperties = properties.get( material );
  17663. const lights = currentRenderState.state.lights;
  17664. const shadowsArray = currentRenderState.state.shadowsArray;
  17665. const lightsStateVersion = lights.state.version;
  17666. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17667. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17668. let programs = materialProperties.programs;
  17669. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17670. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17671. materialProperties.fog = scene.fog;
  17672. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17673. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  17674. if ( programs === undefined ) {
  17675. // new material
  17676. material.addEventListener( 'dispose', onMaterialDispose );
  17677. programs = new Map();
  17678. materialProperties.programs = programs;
  17679. }
  17680. let program = programs.get( programCacheKey );
  17681. if ( program !== undefined ) {
  17682. // early out if program and light state is identical
  17683. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17684. updateCommonMaterialProperties( material, parameters );
  17685. return program;
  17686. }
  17687. } else {
  17688. parameters.uniforms = programCache.getUniforms( material );
  17689. material.onBuild( object, parameters, _this );
  17690. material.onBeforeCompile( parameters, _this );
  17691. program = programCache.acquireProgram( parameters, programCacheKey );
  17692. programs.set( programCacheKey, program );
  17693. materialProperties.uniforms = parameters.uniforms;
  17694. }
  17695. const uniforms = materialProperties.uniforms;
  17696. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17697. uniforms.clippingPlanes = clipping.uniform;
  17698. }
  17699. updateCommonMaterialProperties( material, parameters );
  17700. // store the light setup it was created for
  17701. materialProperties.needsLights = materialNeedsLights( material );
  17702. materialProperties.lightsStateVersion = lightsStateVersion;
  17703. if ( materialProperties.needsLights ) {
  17704. // wire up the material to this renderer's lighting state
  17705. uniforms.ambientLightColor.value = lights.state.ambient;
  17706. uniforms.lightProbe.value = lights.state.probe;
  17707. uniforms.directionalLights.value = lights.state.directional;
  17708. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17709. uniforms.spotLights.value = lights.state.spot;
  17710. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17711. uniforms.rectAreaLights.value = lights.state.rectArea;
  17712. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17713. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17714. uniforms.pointLights.value = lights.state.point;
  17715. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17716. uniforms.hemisphereLights.value = lights.state.hemi;
  17717. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17718. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17719. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17720. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17721. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17722. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17723. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17724. // TODO (abelnation): add area lights shadow info to uniforms
  17725. }
  17726. materialProperties.currentProgram = program;
  17727. materialProperties.uniformsList = null;
  17728. return program;
  17729. }
  17730. function getUniformList( materialProperties ) {
  17731. if ( materialProperties.uniformsList === null ) {
  17732. const progUniforms = materialProperties.currentProgram.getUniforms();
  17733. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  17734. }
  17735. return materialProperties.uniformsList;
  17736. }
  17737. function updateCommonMaterialProperties( material, parameters ) {
  17738. const materialProperties = properties.get( material );
  17739. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17740. materialProperties.batching = parameters.batching;
  17741. materialProperties.instancing = parameters.instancing;
  17742. materialProperties.instancingColor = parameters.instancingColor;
  17743. materialProperties.instancingMorph = parameters.instancingMorph;
  17744. materialProperties.skinning = parameters.skinning;
  17745. materialProperties.morphTargets = parameters.morphTargets;
  17746. materialProperties.morphNormals = parameters.morphNormals;
  17747. materialProperties.morphColors = parameters.morphColors;
  17748. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17749. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17750. materialProperties.numIntersection = parameters.numClipIntersection;
  17751. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17752. materialProperties.vertexTangents = parameters.vertexTangents;
  17753. materialProperties.toneMapping = parameters.toneMapping;
  17754. }
  17755. function setProgram( camera, scene, geometry, material, object ) {
  17756. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17757. textures.resetTextureUnits();
  17758. const fog = scene.fog;
  17759. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17760. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17761. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17762. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17763. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  17764. const morphTargets = !! geometry.morphAttributes.position;
  17765. const morphNormals = !! geometry.morphAttributes.normal;
  17766. const morphColors = !! geometry.morphAttributes.color;
  17767. let toneMapping = NoToneMapping;
  17768. if ( material.toneMapped ) {
  17769. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  17770. toneMapping = _this.toneMapping;
  17771. }
  17772. }
  17773. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17774. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17775. const materialProperties = properties.get( material );
  17776. const lights = currentRenderState.state.lights;
  17777. if ( _clippingEnabled === true ) {
  17778. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17779. const useCache =
  17780. camera === _currentCamera &&
  17781. material.id === _currentMaterialId;
  17782. // we might want to call this function with some ClippingGroup
  17783. // object instead of the material, once it becomes feasible
  17784. // (#8465, #8379)
  17785. clipping.setState( material, camera, useCache );
  17786. }
  17787. }
  17788. //
  17789. let needsProgramChange = false;
  17790. if ( material.version === materialProperties.__version ) {
  17791. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17792. needsProgramChange = true;
  17793. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17794. needsProgramChange = true;
  17795. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  17796. needsProgramChange = true;
  17797. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  17798. needsProgramChange = true;
  17799. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17800. needsProgramChange = true;
  17801. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17802. needsProgramChange = true;
  17803. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17804. needsProgramChange = true;
  17805. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17806. needsProgramChange = true;
  17807. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  17808. needsProgramChange = true;
  17809. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  17810. needsProgramChange = true;
  17811. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  17812. needsProgramChange = true;
  17813. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  17814. needsProgramChange = true;
  17815. } else if ( materialProperties.envMap !== envMap ) {
  17816. needsProgramChange = true;
  17817. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17818. needsProgramChange = true;
  17819. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17820. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17821. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17822. needsProgramChange = true;
  17823. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17824. needsProgramChange = true;
  17825. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17826. needsProgramChange = true;
  17827. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17828. needsProgramChange = true;
  17829. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17830. needsProgramChange = true;
  17831. } else if ( materialProperties.morphColors !== morphColors ) {
  17832. needsProgramChange = true;
  17833. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17834. needsProgramChange = true;
  17835. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17836. needsProgramChange = true;
  17837. }
  17838. } else {
  17839. needsProgramChange = true;
  17840. materialProperties.__version = material.version;
  17841. }
  17842. //
  17843. let program = materialProperties.currentProgram;
  17844. if ( needsProgramChange === true ) {
  17845. program = getProgram( material, scene, object );
  17846. }
  17847. let refreshProgram = false;
  17848. let refreshMaterial = false;
  17849. let refreshLights = false;
  17850. const p_uniforms = program.getUniforms(),
  17851. m_uniforms = materialProperties.uniforms;
  17852. if ( state.useProgram( program.program ) ) {
  17853. refreshProgram = true;
  17854. refreshMaterial = true;
  17855. refreshLights = true;
  17856. }
  17857. if ( material.id !== _currentMaterialId ) {
  17858. _currentMaterialId = material.id;
  17859. refreshMaterial = true;
  17860. }
  17861. if ( refreshProgram || _currentCamera !== camera ) {
  17862. // common camera uniforms
  17863. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17864. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17865. const uCamPos = p_uniforms.map.cameraPosition;
  17866. if ( uCamPos !== undefined ) {
  17867. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17868. }
  17869. if ( capabilities.logarithmicDepthBuffer ) {
  17870. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17871. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17872. }
  17873. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  17874. if ( material.isMeshPhongMaterial ||
  17875. material.isMeshToonMaterial ||
  17876. material.isMeshLambertMaterial ||
  17877. material.isMeshBasicMaterial ||
  17878. material.isMeshStandardMaterial ||
  17879. material.isShaderMaterial ) {
  17880. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17881. }
  17882. if ( _currentCamera !== camera ) {
  17883. _currentCamera = camera;
  17884. // lighting uniforms depend on the camera so enforce an update
  17885. // now, in case this material supports lights - or later, when
  17886. // the next material that does gets activated:
  17887. refreshMaterial = true; // set to true on material change
  17888. refreshLights = true; // remains set until update done
  17889. }
  17890. }
  17891. // skinning and morph target uniforms must be set even if material didn't change
  17892. // auto-setting of texture unit for bone and morph texture must go before other textures
  17893. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17894. if ( object.isSkinnedMesh ) {
  17895. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17896. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17897. const skeleton = object.skeleton;
  17898. if ( skeleton ) {
  17899. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17900. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17901. }
  17902. }
  17903. if ( object.isBatchedMesh ) {
  17904. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  17905. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  17906. }
  17907. const morphAttributes = geometry.morphAttributes;
  17908. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  17909. morphtargets.update( object, geometry, program );
  17910. }
  17911. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17912. materialProperties.receiveShadow = object.receiveShadow;
  17913. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17914. }
  17915. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17916. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17917. m_uniforms.envMap.value = envMap;
  17918. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17919. }
  17920. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  17921. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  17922. }
  17923. if ( refreshMaterial ) {
  17924. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17925. if ( materialProperties.needsLights ) {
  17926. // the current material requires lighting info
  17927. // note: all lighting uniforms are always set correctly
  17928. // they simply reference the renderer's state for their
  17929. // values
  17930. //
  17931. // use the current material's .needsUpdate flags to set
  17932. // the GL state when required
  17933. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17934. }
  17935. // refresh uniforms common to several materials
  17936. if ( fog && material.fog === true ) {
  17937. materials.refreshFogUniforms( m_uniforms, fog );
  17938. }
  17939. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget );
  17940. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  17941. }
  17942. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17943. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  17944. material.uniformsNeedUpdate = false;
  17945. }
  17946. if ( material.isSpriteMaterial ) {
  17947. p_uniforms.setValue( _gl, 'center', object.center );
  17948. }
  17949. // common matrices
  17950. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17951. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17952. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17953. // UBOs
  17954. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17955. const groups = material.uniformsGroups;
  17956. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17957. const group = groups[ i ];
  17958. uniformsGroups.update( group, program );
  17959. uniformsGroups.bind( group, program );
  17960. }
  17961. }
  17962. return program;
  17963. }
  17964. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17965. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17966. uniforms.ambientLightColor.needsUpdate = value;
  17967. uniforms.lightProbe.needsUpdate = value;
  17968. uniforms.directionalLights.needsUpdate = value;
  17969. uniforms.directionalLightShadows.needsUpdate = value;
  17970. uniforms.pointLights.needsUpdate = value;
  17971. uniforms.pointLightShadows.needsUpdate = value;
  17972. uniforms.spotLights.needsUpdate = value;
  17973. uniforms.spotLightShadows.needsUpdate = value;
  17974. uniforms.rectAreaLights.needsUpdate = value;
  17975. uniforms.hemisphereLights.needsUpdate = value;
  17976. }
  17977. function materialNeedsLights( material ) {
  17978. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17979. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17980. ( material.isShaderMaterial && material.lights === true );
  17981. }
  17982. this.getActiveCubeFace = function () {
  17983. return _currentActiveCubeFace;
  17984. };
  17985. this.getActiveMipmapLevel = function () {
  17986. return _currentActiveMipmapLevel;
  17987. };
  17988. this.getRenderTarget = function () {
  17989. return _currentRenderTarget;
  17990. };
  17991. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17992. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17993. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17994. const renderTargetProperties = properties.get( renderTarget );
  17995. renderTargetProperties.__hasExternalTextures = true;
  17996. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17997. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17998. // The multisample_render_to_texture extension doesn't work properly if there
  17999. // are midframe flushes and an external depth buffer. Disable use of the extension.
  18000. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  18001. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  18002. renderTargetProperties.__useRenderToTexture = false;
  18003. }
  18004. }
  18005. };
  18006. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  18007. const renderTargetProperties = properties.get( renderTarget );
  18008. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  18009. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  18010. };
  18011. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  18012. _currentRenderTarget = renderTarget;
  18013. _currentActiveCubeFace = activeCubeFace;
  18014. _currentActiveMipmapLevel = activeMipmapLevel;
  18015. let useDefaultFramebuffer = true;
  18016. let framebuffer = null;
  18017. let isCube = false;
  18018. let isRenderTarget3D = false;
  18019. if ( renderTarget ) {
  18020. const renderTargetProperties = properties.get( renderTarget );
  18021. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  18022. // We need to make sure to rebind the framebuffer.
  18023. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  18024. useDefaultFramebuffer = false;
  18025. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  18026. textures.setupRenderTarget( renderTarget );
  18027. } else if ( renderTargetProperties.__hasExternalTextures ) {
  18028. // Color and depth texture must be rebound in order for the swapchain to update.
  18029. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  18030. }
  18031. const texture = renderTarget.texture;
  18032. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18033. isRenderTarget3D = true;
  18034. }
  18035. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18036. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18037. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  18038. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  18039. } else {
  18040. framebuffer = __webglFramebuffer[ activeCubeFace ];
  18041. }
  18042. isCube = true;
  18043. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  18044. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  18045. } else {
  18046. if ( Array.isArray( __webglFramebuffer ) ) {
  18047. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  18048. } else {
  18049. framebuffer = __webglFramebuffer;
  18050. }
  18051. }
  18052. _currentViewport.copy( renderTarget.viewport );
  18053. _currentScissor.copy( renderTarget.scissor );
  18054. _currentScissorTest = renderTarget.scissorTest;
  18055. } else {
  18056. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  18057. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  18058. _currentScissorTest = _scissorTest;
  18059. }
  18060. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18061. if ( framebufferBound && useDefaultFramebuffer ) {
  18062. state.drawBuffers( renderTarget, framebuffer );
  18063. }
  18064. state.viewport( _currentViewport );
  18065. state.scissor( _currentScissor );
  18066. state.setScissorTest( _currentScissorTest );
  18067. if ( isCube ) {
  18068. const textureProperties = properties.get( renderTarget.texture );
  18069. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  18070. } else if ( isRenderTarget3D ) {
  18071. const textureProperties = properties.get( renderTarget.texture );
  18072. const layer = activeCubeFace || 0;
  18073. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  18074. }
  18075. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  18076. };
  18077. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18078. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18079. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18080. return;
  18081. }
  18082. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18083. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18084. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18085. }
  18086. if ( framebuffer ) {
  18087. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18088. try {
  18089. const texture = renderTarget.texture;
  18090. const textureFormat = texture.format;
  18091. const textureType = texture.type;
  18092. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18093. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18094. return;
  18095. }
  18096. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  18097. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  18098. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  18099. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18100. return;
  18101. }
  18102. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18103. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18104. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18105. }
  18106. } finally {
  18107. // restore framebuffer of current render target if necessary
  18108. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18109. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18110. }
  18111. }
  18112. };
  18113. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  18114. const levelScale = Math.pow( 2, - level );
  18115. const width = Math.floor( texture.image.width * levelScale );
  18116. const height = Math.floor( texture.image.height * levelScale );
  18117. textures.setTexture2D( texture, 0 );
  18118. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  18119. state.unbindTexture();
  18120. };
  18121. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  18122. const width = srcTexture.image.width;
  18123. const height = srcTexture.image.height;
  18124. const glFormat = utils.convert( dstTexture.format );
  18125. const glType = utils.convert( dstTexture.type );
  18126. textures.setTexture2D( dstTexture, 0 );
  18127. // As another texture upload may have changed pixelStorei
  18128. // parameters, make sure they are correct for the dstTexture
  18129. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18130. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18131. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18132. if ( srcTexture.isDataTexture ) {
  18133. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  18134. } else {
  18135. if ( srcTexture.isCompressedTexture ) {
  18136. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  18137. } else {
  18138. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  18139. }
  18140. }
  18141. // Generate mipmaps only when copying level 0
  18142. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18143. state.unbindTexture();
  18144. };
  18145. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  18146. const width = Math.round( sourceBox.max.x - sourceBox.min.x );
  18147. const height = Math.round( sourceBox.max.y - sourceBox.min.y );
  18148. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  18149. const glFormat = utils.convert( dstTexture.format );
  18150. const glType = utils.convert( dstTexture.type );
  18151. let glTarget;
  18152. if ( dstTexture.isData3DTexture ) {
  18153. textures.setTexture3D( dstTexture, 0 );
  18154. glTarget = _gl.TEXTURE_3D;
  18155. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  18156. textures.setTexture2DArray( dstTexture, 0 );
  18157. glTarget = _gl.TEXTURE_2D_ARRAY;
  18158. } else {
  18159. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18160. return;
  18161. }
  18162. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18163. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18164. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18165. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18166. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18167. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18168. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18169. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18170. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18171. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18172. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18173. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  18174. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  18175. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  18176. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18177. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  18178. } else {
  18179. if ( dstTexture.isCompressedArrayTexture ) {
  18180. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  18181. } else {
  18182. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  18183. }
  18184. }
  18185. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  18186. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  18187. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  18188. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  18189. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  18190. // Generate mipmaps only when copying level 0
  18191. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18192. state.unbindTexture();
  18193. };
  18194. this.initTexture = function ( texture ) {
  18195. if ( texture.isCubeTexture ) {
  18196. textures.setTextureCube( texture, 0 );
  18197. } else if ( texture.isData3DTexture ) {
  18198. textures.setTexture3D( texture, 0 );
  18199. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18200. textures.setTexture2DArray( texture, 0 );
  18201. } else {
  18202. textures.setTexture2D( texture, 0 );
  18203. }
  18204. state.unbindTexture();
  18205. };
  18206. this.resetState = function () {
  18207. _currentActiveCubeFace = 0;
  18208. _currentActiveMipmapLevel = 0;
  18209. _currentRenderTarget = null;
  18210. state.reset();
  18211. bindingStates.reset();
  18212. };
  18213. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18214. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18215. }
  18216. }
  18217. get coordinateSystem() {
  18218. return WebGLCoordinateSystem;
  18219. }
  18220. get outputColorSpace() {
  18221. return this._outputColorSpace;
  18222. }
  18223. set outputColorSpace( colorSpace ) {
  18224. this._outputColorSpace = colorSpace;
  18225. const gl = this.getContext();
  18226. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18227. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18228. }
  18229. get useLegacyLights() { // @deprecated, r155
  18230. 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.' );
  18231. return this._useLegacyLights;
  18232. }
  18233. set useLegacyLights( value ) { // @deprecated, r155
  18234. 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.' );
  18235. this._useLegacyLights = value;
  18236. }
  18237. }
  18238. class FogExp2 {
  18239. constructor( color, density = 0.00025 ) {
  18240. this.isFogExp2 = true;
  18241. this.name = '';
  18242. this.color = new Color( color );
  18243. this.density = density;
  18244. }
  18245. clone() {
  18246. return new FogExp2( this.color, this.density );
  18247. }
  18248. toJSON( /* meta */ ) {
  18249. return {
  18250. type: 'FogExp2',
  18251. name: this.name,
  18252. color: this.color.getHex(),
  18253. density: this.density
  18254. };
  18255. }
  18256. }
  18257. class Fog {
  18258. constructor( color, near = 1, far = 1000 ) {
  18259. this.isFog = true;
  18260. this.name = '';
  18261. this.color = new Color( color );
  18262. this.near = near;
  18263. this.far = far;
  18264. }
  18265. clone() {
  18266. return new Fog( this.color, this.near, this.far );
  18267. }
  18268. toJSON( /* meta */ ) {
  18269. return {
  18270. type: 'Fog',
  18271. name: this.name,
  18272. color: this.color.getHex(),
  18273. near: this.near,
  18274. far: this.far
  18275. };
  18276. }
  18277. }
  18278. class Scene extends Object3D {
  18279. constructor() {
  18280. super();
  18281. this.isScene = true;
  18282. this.type = 'Scene';
  18283. this.background = null;
  18284. this.environment = null;
  18285. this.fog = null;
  18286. this.backgroundBlurriness = 0;
  18287. this.backgroundIntensity = 1;
  18288. this.backgroundRotation = new Euler();
  18289. this.environmentIntensity = 1;
  18290. this.environmentRotation = new Euler();
  18291. this.overrideMaterial = null;
  18292. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18293. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18294. }
  18295. }
  18296. copy( source, recursive ) {
  18297. super.copy( source, recursive );
  18298. if ( source.background !== null ) this.background = source.background.clone();
  18299. if ( source.environment !== null ) this.environment = source.environment.clone();
  18300. if ( source.fog !== null ) this.fog = source.fog.clone();
  18301. this.backgroundBlurriness = source.backgroundBlurriness;
  18302. this.backgroundIntensity = source.backgroundIntensity;
  18303. this.backgroundRotation.copy( source.backgroundRotation );
  18304. this.environmentIntensity = source.environmentIntensity;
  18305. this.environmentRotation.copy( source.environmentRotation );
  18306. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18307. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18308. return this;
  18309. }
  18310. toJSON( meta ) {
  18311. const data = super.toJSON( meta );
  18312. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18313. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18314. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18315. data.object.backgroundRotation = this.backgroundRotation.toArray();
  18316. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  18317. data.object.environmentRotation = this.environmentRotation.toArray();
  18318. return data;
  18319. }
  18320. }
  18321. class InterleavedBuffer {
  18322. constructor( array, stride ) {
  18323. this.isInterleavedBuffer = true;
  18324. this.array = array;
  18325. this.stride = stride;
  18326. this.count = array !== undefined ? array.length / stride : 0;
  18327. this.usage = StaticDrawUsage;
  18328. this._updateRange = { offset: 0, count: - 1 };
  18329. this.updateRanges = [];
  18330. this.version = 0;
  18331. this.uuid = generateUUID();
  18332. }
  18333. onUploadCallback() {}
  18334. set needsUpdate( value ) {
  18335. if ( value === true ) this.version ++;
  18336. }
  18337. get updateRange() {
  18338. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  18339. return this._updateRange;
  18340. }
  18341. setUsage( value ) {
  18342. this.usage = value;
  18343. return this;
  18344. }
  18345. addUpdateRange( start, count ) {
  18346. this.updateRanges.push( { start, count } );
  18347. }
  18348. clearUpdateRanges() {
  18349. this.updateRanges.length = 0;
  18350. }
  18351. copy( source ) {
  18352. this.array = new source.array.constructor( source.array );
  18353. this.count = source.count;
  18354. this.stride = source.stride;
  18355. this.usage = source.usage;
  18356. return this;
  18357. }
  18358. copyAt( index1, attribute, index2 ) {
  18359. index1 *= this.stride;
  18360. index2 *= attribute.stride;
  18361. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18362. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18363. }
  18364. return this;
  18365. }
  18366. set( value, offset = 0 ) {
  18367. this.array.set( value, offset );
  18368. return this;
  18369. }
  18370. clone( data ) {
  18371. if ( data.arrayBuffers === undefined ) {
  18372. data.arrayBuffers = {};
  18373. }
  18374. if ( this.array.buffer._uuid === undefined ) {
  18375. this.array.buffer._uuid = generateUUID();
  18376. }
  18377. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18378. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18379. }
  18380. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18381. const ib = new this.constructor( array, this.stride );
  18382. ib.setUsage( this.usage );
  18383. return ib;
  18384. }
  18385. onUpload( callback ) {
  18386. this.onUploadCallback = callback;
  18387. return this;
  18388. }
  18389. toJSON( data ) {
  18390. if ( data.arrayBuffers === undefined ) {
  18391. data.arrayBuffers = {};
  18392. }
  18393. // generate UUID for array buffer if necessary
  18394. if ( this.array.buffer._uuid === undefined ) {
  18395. this.array.buffer._uuid = generateUUID();
  18396. }
  18397. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18398. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18399. }
  18400. //
  18401. return {
  18402. uuid: this.uuid,
  18403. buffer: this.array.buffer._uuid,
  18404. type: this.array.constructor.name,
  18405. stride: this.stride
  18406. };
  18407. }
  18408. }
  18409. const _vector$6 = /*@__PURE__*/ new Vector3();
  18410. class InterleavedBufferAttribute {
  18411. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18412. this.isInterleavedBufferAttribute = true;
  18413. this.name = '';
  18414. this.data = interleavedBuffer;
  18415. this.itemSize = itemSize;
  18416. this.offset = offset;
  18417. this.normalized = normalized;
  18418. }
  18419. get count() {
  18420. return this.data.count;
  18421. }
  18422. get array() {
  18423. return this.data.array;
  18424. }
  18425. set needsUpdate( value ) {
  18426. this.data.needsUpdate = value;
  18427. }
  18428. applyMatrix4( m ) {
  18429. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18430. _vector$6.fromBufferAttribute( this, i );
  18431. _vector$6.applyMatrix4( m );
  18432. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18433. }
  18434. return this;
  18435. }
  18436. applyNormalMatrix( m ) {
  18437. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18438. _vector$6.fromBufferAttribute( this, i );
  18439. _vector$6.applyNormalMatrix( m );
  18440. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18441. }
  18442. return this;
  18443. }
  18444. transformDirection( m ) {
  18445. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18446. _vector$6.fromBufferAttribute( this, i );
  18447. _vector$6.transformDirection( m );
  18448. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18449. }
  18450. return this;
  18451. }
  18452. getComponent( index, component ) {
  18453. let value = this.array[ index * this.data.stride + this.offset + component ];
  18454. if ( this.normalized ) value = denormalize( value, this.array );
  18455. return value;
  18456. }
  18457. setComponent( index, component, value ) {
  18458. if ( this.normalized ) value = normalize( value, this.array );
  18459. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  18460. return this;
  18461. }
  18462. setX( index, x ) {
  18463. if ( this.normalized ) x = normalize( x, this.array );
  18464. this.data.array[ index * this.data.stride + this.offset ] = x;
  18465. return this;
  18466. }
  18467. setY( index, y ) {
  18468. if ( this.normalized ) y = normalize( y, this.array );
  18469. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18470. return this;
  18471. }
  18472. setZ( index, z ) {
  18473. if ( this.normalized ) z = normalize( z, this.array );
  18474. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18475. return this;
  18476. }
  18477. setW( index, w ) {
  18478. if ( this.normalized ) w = normalize( w, this.array );
  18479. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18480. return this;
  18481. }
  18482. getX( index ) {
  18483. let x = this.data.array[ index * this.data.stride + this.offset ];
  18484. if ( this.normalized ) x = denormalize( x, this.array );
  18485. return x;
  18486. }
  18487. getY( index ) {
  18488. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18489. if ( this.normalized ) y = denormalize( y, this.array );
  18490. return y;
  18491. }
  18492. getZ( index ) {
  18493. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18494. if ( this.normalized ) z = denormalize( z, this.array );
  18495. return z;
  18496. }
  18497. getW( index ) {
  18498. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18499. if ( this.normalized ) w = denormalize( w, this.array );
  18500. return w;
  18501. }
  18502. setXY( index, x, y ) {
  18503. index = index * this.data.stride + this.offset;
  18504. if ( this.normalized ) {
  18505. x = normalize( x, this.array );
  18506. y = normalize( y, this.array );
  18507. }
  18508. this.data.array[ index + 0 ] = x;
  18509. this.data.array[ index + 1 ] = y;
  18510. return this;
  18511. }
  18512. setXYZ( index, x, y, z ) {
  18513. index = index * this.data.stride + this.offset;
  18514. if ( this.normalized ) {
  18515. x = normalize( x, this.array );
  18516. y = normalize( y, this.array );
  18517. z = normalize( z, this.array );
  18518. }
  18519. this.data.array[ index + 0 ] = x;
  18520. this.data.array[ index + 1 ] = y;
  18521. this.data.array[ index + 2 ] = z;
  18522. return this;
  18523. }
  18524. setXYZW( index, x, y, z, w ) {
  18525. index = index * this.data.stride + this.offset;
  18526. if ( this.normalized ) {
  18527. x = normalize( x, this.array );
  18528. y = normalize( y, this.array );
  18529. z = normalize( z, this.array );
  18530. w = normalize( w, this.array );
  18531. }
  18532. this.data.array[ index + 0 ] = x;
  18533. this.data.array[ index + 1 ] = y;
  18534. this.data.array[ index + 2 ] = z;
  18535. this.data.array[ index + 3 ] = w;
  18536. return this;
  18537. }
  18538. clone( data ) {
  18539. if ( data === undefined ) {
  18540. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18541. const array = [];
  18542. for ( let i = 0; i < this.count; i ++ ) {
  18543. const index = i * this.data.stride + this.offset;
  18544. for ( let j = 0; j < this.itemSize; j ++ ) {
  18545. array.push( this.data.array[ index + j ] );
  18546. }
  18547. }
  18548. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18549. } else {
  18550. if ( data.interleavedBuffers === undefined ) {
  18551. data.interleavedBuffers = {};
  18552. }
  18553. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18554. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18555. }
  18556. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18557. }
  18558. }
  18559. toJSON( data ) {
  18560. if ( data === undefined ) {
  18561. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18562. const array = [];
  18563. for ( let i = 0; i < this.count; i ++ ) {
  18564. const index = i * this.data.stride + this.offset;
  18565. for ( let j = 0; j < this.itemSize; j ++ ) {
  18566. array.push( this.data.array[ index + j ] );
  18567. }
  18568. }
  18569. // de-interleave data and save it as an ordinary buffer attribute for now
  18570. return {
  18571. itemSize: this.itemSize,
  18572. type: this.array.constructor.name,
  18573. array: array,
  18574. normalized: this.normalized
  18575. };
  18576. } else {
  18577. // save as true interleaved attribute
  18578. if ( data.interleavedBuffers === undefined ) {
  18579. data.interleavedBuffers = {};
  18580. }
  18581. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18582. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18583. }
  18584. return {
  18585. isInterleavedBufferAttribute: true,
  18586. itemSize: this.itemSize,
  18587. data: this.data.uuid,
  18588. offset: this.offset,
  18589. normalized: this.normalized
  18590. };
  18591. }
  18592. }
  18593. }
  18594. class SpriteMaterial extends Material {
  18595. constructor( parameters ) {
  18596. super();
  18597. this.isSpriteMaterial = true;
  18598. this.type = 'SpriteMaterial';
  18599. this.color = new Color( 0xffffff );
  18600. this.map = null;
  18601. this.alphaMap = null;
  18602. this.rotation = 0;
  18603. this.sizeAttenuation = true;
  18604. this.transparent = true;
  18605. this.fog = true;
  18606. this.setValues( parameters );
  18607. }
  18608. copy( source ) {
  18609. super.copy( source );
  18610. this.color.copy( source.color );
  18611. this.map = source.map;
  18612. this.alphaMap = source.alphaMap;
  18613. this.rotation = source.rotation;
  18614. this.sizeAttenuation = source.sizeAttenuation;
  18615. this.fog = source.fog;
  18616. return this;
  18617. }
  18618. }
  18619. let _geometry;
  18620. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18621. const _worldScale = /*@__PURE__*/ new Vector3();
  18622. const _mvPosition = /*@__PURE__*/ new Vector3();
  18623. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18624. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18625. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18626. const _vA = /*@__PURE__*/ new Vector3();
  18627. const _vB = /*@__PURE__*/ new Vector3();
  18628. const _vC = /*@__PURE__*/ new Vector3();
  18629. const _uvA = /*@__PURE__*/ new Vector2();
  18630. const _uvB = /*@__PURE__*/ new Vector2();
  18631. const _uvC = /*@__PURE__*/ new Vector2();
  18632. class Sprite extends Object3D {
  18633. constructor( material = new SpriteMaterial() ) {
  18634. super();
  18635. this.isSprite = true;
  18636. this.type = 'Sprite';
  18637. if ( _geometry === undefined ) {
  18638. _geometry = new BufferGeometry();
  18639. const float32Array = new Float32Array( [
  18640. - 0.5, - 0.5, 0, 0, 0,
  18641. 0.5, - 0.5, 0, 1, 0,
  18642. 0.5, 0.5, 0, 1, 1,
  18643. - 0.5, 0.5, 0, 0, 1
  18644. ] );
  18645. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18646. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18647. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18648. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18649. }
  18650. this.geometry = _geometry;
  18651. this.material = material;
  18652. this.center = new Vector2( 0.5, 0.5 );
  18653. }
  18654. raycast( raycaster, intersects ) {
  18655. if ( raycaster.camera === null ) {
  18656. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18657. }
  18658. _worldScale.setFromMatrixScale( this.matrixWorld );
  18659. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18660. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18661. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18662. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18663. _worldScale.multiplyScalar( - _mvPosition.z );
  18664. }
  18665. const rotation = this.material.rotation;
  18666. let sin, cos;
  18667. if ( rotation !== 0 ) {
  18668. cos = Math.cos( rotation );
  18669. sin = Math.sin( rotation );
  18670. }
  18671. const center = this.center;
  18672. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18673. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18674. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18675. _uvA.set( 0, 0 );
  18676. _uvB.set( 1, 0 );
  18677. _uvC.set( 1, 1 );
  18678. // check first triangle
  18679. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18680. if ( intersect === null ) {
  18681. // check second triangle
  18682. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18683. _uvB.set( 0, 1 );
  18684. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18685. if ( intersect === null ) {
  18686. return;
  18687. }
  18688. }
  18689. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18690. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18691. intersects.push( {
  18692. distance: distance,
  18693. point: _intersectPoint.clone(),
  18694. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18695. face: null,
  18696. object: this
  18697. } );
  18698. }
  18699. copy( source, recursive ) {
  18700. super.copy( source, recursive );
  18701. if ( source.center !== undefined ) this.center.copy( source.center );
  18702. this.material = source.material;
  18703. return this;
  18704. }
  18705. }
  18706. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18707. // compute position in camera space
  18708. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18709. // to check if rotation is not zero
  18710. if ( sin !== undefined ) {
  18711. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18712. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18713. } else {
  18714. _rotatedPosition.copy( _alignedPosition );
  18715. }
  18716. vertexPosition.copy( mvPosition );
  18717. vertexPosition.x += _rotatedPosition.x;
  18718. vertexPosition.y += _rotatedPosition.y;
  18719. // transform to world space
  18720. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18721. }
  18722. const _v1$2 = /*@__PURE__*/ new Vector3();
  18723. const _v2$1 = /*@__PURE__*/ new Vector3();
  18724. class LOD extends Object3D {
  18725. constructor() {
  18726. super();
  18727. this._currentLevel = 0;
  18728. this.type = 'LOD';
  18729. Object.defineProperties( this, {
  18730. levels: {
  18731. enumerable: true,
  18732. value: []
  18733. },
  18734. isLOD: {
  18735. value: true,
  18736. }
  18737. } );
  18738. this.autoUpdate = true;
  18739. }
  18740. copy( source ) {
  18741. super.copy( source, false );
  18742. const levels = source.levels;
  18743. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18744. const level = levels[ i ];
  18745. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18746. }
  18747. this.autoUpdate = source.autoUpdate;
  18748. return this;
  18749. }
  18750. addLevel( object, distance = 0, hysteresis = 0 ) {
  18751. distance = Math.abs( distance );
  18752. const levels = this.levels;
  18753. let l;
  18754. for ( l = 0; l < levels.length; l ++ ) {
  18755. if ( distance < levels[ l ].distance ) {
  18756. break;
  18757. }
  18758. }
  18759. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18760. this.add( object );
  18761. return this;
  18762. }
  18763. getCurrentLevel() {
  18764. return this._currentLevel;
  18765. }
  18766. getObjectForDistance( distance ) {
  18767. const levels = this.levels;
  18768. if ( levels.length > 0 ) {
  18769. let i, l;
  18770. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18771. let levelDistance = levels[ i ].distance;
  18772. if ( levels[ i ].object.visible ) {
  18773. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18774. }
  18775. if ( distance < levelDistance ) {
  18776. break;
  18777. }
  18778. }
  18779. return levels[ i - 1 ].object;
  18780. }
  18781. return null;
  18782. }
  18783. raycast( raycaster, intersects ) {
  18784. const levels = this.levels;
  18785. if ( levels.length > 0 ) {
  18786. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18787. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18788. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18789. }
  18790. }
  18791. update( camera ) {
  18792. const levels = this.levels;
  18793. if ( levels.length > 1 ) {
  18794. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18795. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18796. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18797. levels[ 0 ].object.visible = true;
  18798. let i, l;
  18799. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18800. let levelDistance = levels[ i ].distance;
  18801. if ( levels[ i ].object.visible ) {
  18802. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18803. }
  18804. if ( distance >= levelDistance ) {
  18805. levels[ i - 1 ].object.visible = false;
  18806. levels[ i ].object.visible = true;
  18807. } else {
  18808. break;
  18809. }
  18810. }
  18811. this._currentLevel = i - 1;
  18812. for ( ; i < l; i ++ ) {
  18813. levels[ i ].object.visible = false;
  18814. }
  18815. }
  18816. }
  18817. toJSON( meta ) {
  18818. const data = super.toJSON( meta );
  18819. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18820. data.object.levels = [];
  18821. const levels = this.levels;
  18822. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18823. const level = levels[ i ];
  18824. data.object.levels.push( {
  18825. object: level.object.uuid,
  18826. distance: level.distance,
  18827. hysteresis: level.hysteresis
  18828. } );
  18829. }
  18830. return data;
  18831. }
  18832. }
  18833. const _basePosition = /*@__PURE__*/ new Vector3();
  18834. const _skinIndex = /*@__PURE__*/ new Vector4();
  18835. const _skinWeight = /*@__PURE__*/ new Vector4();
  18836. const _vector3 = /*@__PURE__*/ new Vector3();
  18837. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18838. const _vertex = /*@__PURE__*/ new Vector3();
  18839. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18840. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18841. const _ray$2 = /*@__PURE__*/ new Ray();
  18842. class SkinnedMesh extends Mesh {
  18843. constructor( geometry, material ) {
  18844. super( geometry, material );
  18845. this.isSkinnedMesh = true;
  18846. this.type = 'SkinnedMesh';
  18847. this.bindMode = AttachedBindMode;
  18848. this.bindMatrix = new Matrix4();
  18849. this.bindMatrixInverse = new Matrix4();
  18850. this.boundingBox = null;
  18851. this.boundingSphere = null;
  18852. }
  18853. computeBoundingBox() {
  18854. const geometry = this.geometry;
  18855. if ( this.boundingBox === null ) {
  18856. this.boundingBox = new Box3();
  18857. }
  18858. this.boundingBox.makeEmpty();
  18859. const positionAttribute = geometry.getAttribute( 'position' );
  18860. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18861. this.getVertexPosition( i, _vertex );
  18862. this.boundingBox.expandByPoint( _vertex );
  18863. }
  18864. }
  18865. computeBoundingSphere() {
  18866. const geometry = this.geometry;
  18867. if ( this.boundingSphere === null ) {
  18868. this.boundingSphere = new Sphere();
  18869. }
  18870. this.boundingSphere.makeEmpty();
  18871. const positionAttribute = geometry.getAttribute( 'position' );
  18872. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18873. this.getVertexPosition( i, _vertex );
  18874. this.boundingSphere.expandByPoint( _vertex );
  18875. }
  18876. }
  18877. copy( source, recursive ) {
  18878. super.copy( source, recursive );
  18879. this.bindMode = source.bindMode;
  18880. this.bindMatrix.copy( source.bindMatrix );
  18881. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18882. this.skeleton = source.skeleton;
  18883. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18884. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18885. return this;
  18886. }
  18887. raycast( raycaster, intersects ) {
  18888. const material = this.material;
  18889. const matrixWorld = this.matrixWorld;
  18890. if ( material === undefined ) return;
  18891. // test with bounding sphere in world space
  18892. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18893. _sphere$4.copy( this.boundingSphere );
  18894. _sphere$4.applyMatrix4( matrixWorld );
  18895. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  18896. // convert ray to local space of skinned mesh
  18897. _inverseMatrix$2.copy( matrixWorld ).invert();
  18898. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18899. // test with bounding box in local space
  18900. if ( this.boundingBox !== null ) {
  18901. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18902. }
  18903. // test for intersections with geometry
  18904. this._computeIntersections( raycaster, intersects, _ray$2 );
  18905. }
  18906. getVertexPosition( index, target ) {
  18907. super.getVertexPosition( index, target );
  18908. this.applyBoneTransform( index, target );
  18909. return target;
  18910. }
  18911. bind( skeleton, bindMatrix ) {
  18912. this.skeleton = skeleton;
  18913. if ( bindMatrix === undefined ) {
  18914. this.updateMatrixWorld( true );
  18915. this.skeleton.calculateInverses();
  18916. bindMatrix = this.matrixWorld;
  18917. }
  18918. this.bindMatrix.copy( bindMatrix );
  18919. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18920. }
  18921. pose() {
  18922. this.skeleton.pose();
  18923. }
  18924. normalizeSkinWeights() {
  18925. const vector = new Vector4();
  18926. const skinWeight = this.geometry.attributes.skinWeight;
  18927. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18928. vector.fromBufferAttribute( skinWeight, i );
  18929. const scale = 1.0 / vector.manhattanLength();
  18930. if ( scale !== Infinity ) {
  18931. vector.multiplyScalar( scale );
  18932. } else {
  18933. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18934. }
  18935. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18936. }
  18937. }
  18938. updateMatrixWorld( force ) {
  18939. super.updateMatrixWorld( force );
  18940. if ( this.bindMode === AttachedBindMode ) {
  18941. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18942. } else if ( this.bindMode === DetachedBindMode ) {
  18943. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18944. } else {
  18945. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18946. }
  18947. }
  18948. applyBoneTransform( index, vector ) {
  18949. const skeleton = this.skeleton;
  18950. const geometry = this.geometry;
  18951. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18952. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18953. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18954. vector.set( 0, 0, 0 );
  18955. for ( let i = 0; i < 4; i ++ ) {
  18956. const weight = _skinWeight.getComponent( i );
  18957. if ( weight !== 0 ) {
  18958. const boneIndex = _skinIndex.getComponent( i );
  18959. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18960. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18961. }
  18962. }
  18963. return vector.applyMatrix4( this.bindMatrixInverse );
  18964. }
  18965. }
  18966. class Bone extends Object3D {
  18967. constructor() {
  18968. super();
  18969. this.isBone = true;
  18970. this.type = 'Bone';
  18971. }
  18972. }
  18973. class DataTexture extends Texture {
  18974. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18975. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18976. this.isDataTexture = true;
  18977. this.image = { data: data, width: width, height: height };
  18978. this.generateMipmaps = false;
  18979. this.flipY = false;
  18980. this.unpackAlignment = 1;
  18981. }
  18982. }
  18983. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18984. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  18985. class Skeleton {
  18986. constructor( bones = [], boneInverses = [] ) {
  18987. this.uuid = generateUUID();
  18988. this.bones = bones.slice( 0 );
  18989. this.boneInverses = boneInverses;
  18990. this.boneMatrices = null;
  18991. this.boneTexture = null;
  18992. this.init();
  18993. }
  18994. init() {
  18995. const bones = this.bones;
  18996. const boneInverses = this.boneInverses;
  18997. this.boneMatrices = new Float32Array( bones.length * 16 );
  18998. // calculate inverse bone matrices if necessary
  18999. if ( boneInverses.length === 0 ) {
  19000. this.calculateInverses();
  19001. } else {
  19002. // handle special case
  19003. if ( bones.length !== boneInverses.length ) {
  19004. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19005. this.boneInverses = [];
  19006. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19007. this.boneInverses.push( new Matrix4() );
  19008. }
  19009. }
  19010. }
  19011. }
  19012. calculateInverses() {
  19013. this.boneInverses.length = 0;
  19014. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19015. const inverse = new Matrix4();
  19016. if ( this.bones[ i ] ) {
  19017. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19018. }
  19019. this.boneInverses.push( inverse );
  19020. }
  19021. }
  19022. pose() {
  19023. // recover the bind-time world matrices
  19024. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19025. const bone = this.bones[ i ];
  19026. if ( bone ) {
  19027. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19028. }
  19029. }
  19030. // compute the local matrices, positions, rotations and scales
  19031. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19032. const bone = this.bones[ i ];
  19033. if ( bone ) {
  19034. if ( bone.parent && bone.parent.isBone ) {
  19035. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19036. bone.matrix.multiply( bone.matrixWorld );
  19037. } else {
  19038. bone.matrix.copy( bone.matrixWorld );
  19039. }
  19040. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19041. }
  19042. }
  19043. }
  19044. update() {
  19045. const bones = this.bones;
  19046. const boneInverses = this.boneInverses;
  19047. const boneMatrices = this.boneMatrices;
  19048. const boneTexture = this.boneTexture;
  19049. // flatten bone matrices to array
  19050. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19051. // compute the offset between the current and the original transform
  19052. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  19053. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19054. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19055. }
  19056. if ( boneTexture !== null ) {
  19057. boneTexture.needsUpdate = true;
  19058. }
  19059. }
  19060. clone() {
  19061. return new Skeleton( this.bones, this.boneInverses );
  19062. }
  19063. computeBoneTexture() {
  19064. // layout (1 matrix = 4 pixels)
  19065. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19066. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19067. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19068. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19069. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19070. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19071. size = Math.ceil( size / 4 ) * 4;
  19072. size = Math.max( size, 4 );
  19073. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19074. boneMatrices.set( this.boneMatrices ); // copy current values
  19075. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19076. boneTexture.needsUpdate = true;
  19077. this.boneMatrices = boneMatrices;
  19078. this.boneTexture = boneTexture;
  19079. return this;
  19080. }
  19081. getBoneByName( name ) {
  19082. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19083. const bone = this.bones[ i ];
  19084. if ( bone.name === name ) {
  19085. return bone;
  19086. }
  19087. }
  19088. return undefined;
  19089. }
  19090. dispose( ) {
  19091. if ( this.boneTexture !== null ) {
  19092. this.boneTexture.dispose();
  19093. this.boneTexture = null;
  19094. }
  19095. }
  19096. fromJSON( json, bones ) {
  19097. this.uuid = json.uuid;
  19098. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19099. const uuid = json.bones[ i ];
  19100. let bone = bones[ uuid ];
  19101. if ( bone === undefined ) {
  19102. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  19103. bone = new Bone();
  19104. }
  19105. this.bones.push( bone );
  19106. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19107. }
  19108. this.init();
  19109. return this;
  19110. }
  19111. toJSON() {
  19112. const data = {
  19113. metadata: {
  19114. version: 4.6,
  19115. type: 'Skeleton',
  19116. generator: 'Skeleton.toJSON'
  19117. },
  19118. bones: [],
  19119. boneInverses: []
  19120. };
  19121. data.uuid = this.uuid;
  19122. const bones = this.bones;
  19123. const boneInverses = this.boneInverses;
  19124. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19125. const bone = bones[ i ];
  19126. data.bones.push( bone.uuid );
  19127. const boneInverse = boneInverses[ i ];
  19128. data.boneInverses.push( boneInverse.toArray() );
  19129. }
  19130. return data;
  19131. }
  19132. }
  19133. class InstancedBufferAttribute extends BufferAttribute {
  19134. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19135. super( array, itemSize, normalized );
  19136. this.isInstancedBufferAttribute = true;
  19137. this.meshPerAttribute = meshPerAttribute;
  19138. }
  19139. copy( source ) {
  19140. super.copy( source );
  19141. this.meshPerAttribute = source.meshPerAttribute;
  19142. return this;
  19143. }
  19144. toJSON() {
  19145. const data = super.toJSON();
  19146. data.meshPerAttribute = this.meshPerAttribute;
  19147. data.isInstancedBufferAttribute = true;
  19148. return data;
  19149. }
  19150. }
  19151. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19152. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19153. const _instanceIntersects = [];
  19154. const _box3 = /*@__PURE__*/ new Box3();
  19155. const _identity = /*@__PURE__*/ new Matrix4();
  19156. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19157. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19158. class InstancedMesh extends Mesh {
  19159. constructor( geometry, material, count ) {
  19160. super( geometry, material );
  19161. this.isInstancedMesh = true;
  19162. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19163. this.instanceColor = null;
  19164. this.morphTexture = null;
  19165. this.count = count;
  19166. this.boundingBox = null;
  19167. this.boundingSphere = null;
  19168. for ( let i = 0; i < count; i ++ ) {
  19169. this.setMatrixAt( i, _identity );
  19170. }
  19171. }
  19172. computeBoundingBox() {
  19173. const geometry = this.geometry;
  19174. const count = this.count;
  19175. if ( this.boundingBox === null ) {
  19176. this.boundingBox = new Box3();
  19177. }
  19178. if ( geometry.boundingBox === null ) {
  19179. geometry.computeBoundingBox();
  19180. }
  19181. this.boundingBox.makeEmpty();
  19182. for ( let i = 0; i < count; i ++ ) {
  19183. this.getMatrixAt( i, _instanceLocalMatrix );
  19184. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19185. this.boundingBox.union( _box3 );
  19186. }
  19187. }
  19188. computeBoundingSphere() {
  19189. const geometry = this.geometry;
  19190. const count = this.count;
  19191. if ( this.boundingSphere === null ) {
  19192. this.boundingSphere = new Sphere();
  19193. }
  19194. if ( geometry.boundingSphere === null ) {
  19195. geometry.computeBoundingSphere();
  19196. }
  19197. this.boundingSphere.makeEmpty();
  19198. for ( let i = 0; i < count; i ++ ) {
  19199. this.getMatrixAt( i, _instanceLocalMatrix );
  19200. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19201. this.boundingSphere.union( _sphere$3 );
  19202. }
  19203. }
  19204. copy( source, recursive ) {
  19205. super.copy( source, recursive );
  19206. this.instanceMatrix.copy( source.instanceMatrix );
  19207. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19208. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19209. this.count = source.count;
  19210. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19211. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19212. return this;
  19213. }
  19214. getColorAt( index, color ) {
  19215. color.fromArray( this.instanceColor.array, index * 3 );
  19216. }
  19217. getMatrixAt( index, matrix ) {
  19218. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19219. }
  19220. getMorphAt( index, object ) {
  19221. const objectInfluences = object.morphTargetInfluences;
  19222. const array = this.morphTexture.source.data.data;
  19223. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19224. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19225. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19226. objectInfluences[ i ] = array[ dataIndex + i ];
  19227. }
  19228. }
  19229. raycast( raycaster, intersects ) {
  19230. const matrixWorld = this.matrixWorld;
  19231. const raycastTimes = this.count;
  19232. _mesh$1.geometry = this.geometry;
  19233. _mesh$1.material = this.material;
  19234. if ( _mesh$1.material === undefined ) return;
  19235. // test with bounding sphere first
  19236. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19237. _sphere$3.copy( this.boundingSphere );
  19238. _sphere$3.applyMatrix4( matrixWorld );
  19239. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  19240. // now test each instance
  19241. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19242. // calculate the world matrix for each instance
  19243. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19244. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19245. // the mesh represents this single instance
  19246. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19247. _mesh$1.raycast( raycaster, _instanceIntersects );
  19248. // process the result of raycast
  19249. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19250. const intersect = _instanceIntersects[ i ];
  19251. intersect.instanceId = instanceId;
  19252. intersect.object = this;
  19253. intersects.push( intersect );
  19254. }
  19255. _instanceIntersects.length = 0;
  19256. }
  19257. }
  19258. setColorAt( index, color ) {
  19259. if ( this.instanceColor === null ) {
  19260. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19261. }
  19262. color.toArray( this.instanceColor.array, index * 3 );
  19263. }
  19264. setMatrixAt( index, matrix ) {
  19265. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19266. }
  19267. setMorphAt( index, object ) {
  19268. const objectInfluences = object.morphTargetInfluences;
  19269. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19270. if ( this.morphTexture === null ) {
  19271. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19272. }
  19273. const array = this.morphTexture.source.data.data;
  19274. let morphInfluencesSum = 0;
  19275. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19276. morphInfluencesSum += objectInfluences[ i ];
  19277. }
  19278. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19279. const dataIndex = len * index;
  19280. array[ dataIndex ] = morphBaseInfluence;
  19281. array.set( objectInfluences, dataIndex + 1 );
  19282. }
  19283. updateMorphTargets() {
  19284. }
  19285. dispose() {
  19286. this.dispatchEvent( { type: 'dispose' } );
  19287. if ( this.morphTexture !== null ) {
  19288. this.morphTexture.dispose();
  19289. this.morphTexture = null;
  19290. }
  19291. return this;
  19292. }
  19293. }
  19294. function sortOpaque( a, b ) {
  19295. return a.z - b.z;
  19296. }
  19297. function sortTransparent( a, b ) {
  19298. return b.z - a.z;
  19299. }
  19300. class MultiDrawRenderList {
  19301. constructor() {
  19302. this.index = 0;
  19303. this.pool = [];
  19304. this.list = [];
  19305. }
  19306. push( drawRange, z ) {
  19307. const pool = this.pool;
  19308. const list = this.list;
  19309. if ( this.index >= pool.length ) {
  19310. pool.push( {
  19311. start: - 1,
  19312. count: - 1,
  19313. z: - 1,
  19314. } );
  19315. }
  19316. const item = pool[ this.index ];
  19317. list.push( item );
  19318. this.index ++;
  19319. item.start = drawRange.start;
  19320. item.count = drawRange.count;
  19321. item.z = z;
  19322. }
  19323. reset() {
  19324. this.list.length = 0;
  19325. this.index = 0;
  19326. }
  19327. }
  19328. const ID_ATTR_NAME = 'batchId';
  19329. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19330. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  19331. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  19332. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19333. const _frustum = /*@__PURE__*/ new Frustum();
  19334. const _box$1 = /*@__PURE__*/ new Box3();
  19335. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19336. const _vector$5 = /*@__PURE__*/ new Vector3();
  19337. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19338. const _mesh = /*@__PURE__*/ new Mesh();
  19339. const _batchIntersects = [];
  19340. // @TODO: SkinnedMesh support?
  19341. // @TODO: geometry.groups support?
  19342. // @TODO: geometry.drawRange support?
  19343. // @TODO: geometry.morphAttributes support?
  19344. // @TODO: Support uniform parameter per geometry
  19345. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  19346. // copies data from attribute "src" into "target" starting at "targetOffset"
  19347. function copyAttributeData( src, target, targetOffset = 0 ) {
  19348. const itemSize = target.itemSize;
  19349. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19350. // use the component getters and setters if the array data cannot
  19351. // be copied directly
  19352. const vertexCount = src.count;
  19353. for ( let i = 0; i < vertexCount; i ++ ) {
  19354. for ( let c = 0; c < itemSize; c ++ ) {
  19355. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19356. }
  19357. }
  19358. } else {
  19359. // faster copy approach using typed array set function
  19360. target.array.set( src.array, targetOffset * itemSize );
  19361. }
  19362. target.needsUpdate = true;
  19363. }
  19364. class BatchedMesh extends Mesh {
  19365. get maxGeometryCount() {
  19366. return this._maxGeometryCount;
  19367. }
  19368. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19369. super( new BufferGeometry(), material );
  19370. this.isBatchedMesh = true;
  19371. this.perObjectFrustumCulled = true;
  19372. this.sortObjects = true;
  19373. this.boundingBox = null;
  19374. this.boundingSphere = null;
  19375. this.customSort = null;
  19376. this._drawRanges = [];
  19377. this._reservedRanges = [];
  19378. this._visibility = [];
  19379. this._active = [];
  19380. this._bounds = [];
  19381. this._maxGeometryCount = maxGeometryCount;
  19382. this._maxVertexCount = maxVertexCount;
  19383. this._maxIndexCount = maxIndexCount;
  19384. this._geometryInitialized = false;
  19385. this._geometryCount = 0;
  19386. this._multiDrawCounts = new Int32Array( maxGeometryCount );
  19387. this._multiDrawStarts = new Int32Array( maxGeometryCount );
  19388. this._multiDrawCount = 0;
  19389. this._visibilityChanged = true;
  19390. // Local matrix per geometry by using data texture
  19391. this._matricesTexture = null;
  19392. this._initMatricesTexture();
  19393. }
  19394. _initMatricesTexture() {
  19395. // layout (1 matrix = 4 pixels)
  19396. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19397. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19398. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19399. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19400. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19401. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  19402. size = Math.ceil( size / 4 ) * 4;
  19403. size = Math.max( size, 4 );
  19404. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19405. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19406. this._matricesTexture = matricesTexture;
  19407. }
  19408. _initializeGeometry( reference ) {
  19409. const geometry = this.geometry;
  19410. const maxVertexCount = this._maxVertexCount;
  19411. const maxGeometryCount = this._maxGeometryCount;
  19412. const maxIndexCount = this._maxIndexCount;
  19413. if ( this._geometryInitialized === false ) {
  19414. for ( const attributeName in reference.attributes ) {
  19415. const srcAttribute = reference.getAttribute( attributeName );
  19416. const { array, itemSize, normalized } = srcAttribute;
  19417. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19418. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  19419. geometry.setAttribute( attributeName, dstAttribute );
  19420. }
  19421. if ( reference.getIndex() !== null ) {
  19422. const indexArray = maxVertexCount > 65536
  19423. ? new Uint32Array( maxIndexCount )
  19424. : new Uint16Array( maxIndexCount );
  19425. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19426. }
  19427. const idArray = maxGeometryCount > 65536
  19428. ? new Uint32Array( maxVertexCount )
  19429. : new Uint16Array( maxVertexCount );
  19430. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  19431. this._geometryInitialized = true;
  19432. }
  19433. }
  19434. // Make sure the geometry is compatible with the existing combined geometry atributes
  19435. _validateGeometry( geometry ) {
  19436. // check that the geometry doesn't have a version of our reserved id attribute
  19437. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  19438. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  19439. }
  19440. // check to ensure the geometries are using consistent attributes and indices
  19441. const batchGeometry = this.geometry;
  19442. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19443. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  19444. }
  19445. for ( const attributeName in batchGeometry.attributes ) {
  19446. if ( attributeName === ID_ATTR_NAME ) {
  19447. continue;
  19448. }
  19449. if ( ! geometry.hasAttribute( attributeName ) ) {
  19450. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19451. }
  19452. const srcAttribute = geometry.getAttribute( attributeName );
  19453. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19454. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19455. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19456. }
  19457. }
  19458. }
  19459. setCustomSort( func ) {
  19460. this.customSort = func;
  19461. return this;
  19462. }
  19463. computeBoundingBox() {
  19464. if ( this.boundingBox === null ) {
  19465. this.boundingBox = new Box3();
  19466. }
  19467. const geometryCount = this._geometryCount;
  19468. const boundingBox = this.boundingBox;
  19469. const active = this._active;
  19470. boundingBox.makeEmpty();
  19471. for ( let i = 0; i < geometryCount; i ++ ) {
  19472. if ( active[ i ] === false ) continue;
  19473. this.getMatrixAt( i, _matrix$1 );
  19474. this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix$1 );
  19475. boundingBox.union( _box$1 );
  19476. }
  19477. }
  19478. computeBoundingSphere() {
  19479. if ( this.boundingSphere === null ) {
  19480. this.boundingSphere = new Sphere();
  19481. }
  19482. const geometryCount = this._geometryCount;
  19483. const boundingSphere = this.boundingSphere;
  19484. const active = this._active;
  19485. boundingSphere.makeEmpty();
  19486. for ( let i = 0; i < geometryCount; i ++ ) {
  19487. if ( active[ i ] === false ) continue;
  19488. this.getMatrixAt( i, _matrix$1 );
  19489. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  19490. boundingSphere.union( _sphere$2 );
  19491. }
  19492. }
  19493. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  19494. this._initializeGeometry( geometry );
  19495. this._validateGeometry( geometry );
  19496. // ensure we're not over geometry
  19497. if ( this._geometryCount >= this._maxGeometryCount ) {
  19498. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19499. }
  19500. // get the necessary range fo the geometry
  19501. const reservedRange = {
  19502. vertexStart: - 1,
  19503. vertexCount: - 1,
  19504. indexStart: - 1,
  19505. indexCount: - 1,
  19506. };
  19507. let lastRange = null;
  19508. const reservedRanges = this._reservedRanges;
  19509. const drawRanges = this._drawRanges;
  19510. const bounds = this._bounds;
  19511. if ( this._geometryCount !== 0 ) {
  19512. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  19513. }
  19514. if ( vertexCount === - 1 ) {
  19515. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  19516. } else {
  19517. reservedRange.vertexCount = vertexCount;
  19518. }
  19519. if ( lastRange === null ) {
  19520. reservedRange.vertexStart = 0;
  19521. } else {
  19522. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  19523. }
  19524. const index = geometry.getIndex();
  19525. const hasIndex = index !== null;
  19526. if ( hasIndex ) {
  19527. if ( indexCount === - 1 ) {
  19528. reservedRange.indexCount = index.count;
  19529. } else {
  19530. reservedRange.indexCount = indexCount;
  19531. }
  19532. if ( lastRange === null ) {
  19533. reservedRange.indexStart = 0;
  19534. } else {
  19535. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  19536. }
  19537. }
  19538. if (
  19539. reservedRange.indexStart !== - 1 &&
  19540. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  19541. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  19542. ) {
  19543. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19544. }
  19545. const visibility = this._visibility;
  19546. const active = this._active;
  19547. const matricesTexture = this._matricesTexture;
  19548. const matricesArray = this._matricesTexture.image.data;
  19549. // push new visibility states
  19550. visibility.push( true );
  19551. active.push( true );
  19552. // update id
  19553. const geometryId = this._geometryCount;
  19554. this._geometryCount ++;
  19555. // initialize matrix information
  19556. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  19557. matricesTexture.needsUpdate = true;
  19558. // add the reserved range and draw range objects
  19559. reservedRanges.push( reservedRange );
  19560. drawRanges.push( {
  19561. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  19562. count: - 1
  19563. } );
  19564. bounds.push( {
  19565. boxInitialized: false,
  19566. box: new Box3(),
  19567. sphereInitialized: false,
  19568. sphere: new Sphere()
  19569. } );
  19570. // set the id for the geometry
  19571. const idAttribute = this.geometry.getAttribute( ID_ATTR_NAME );
  19572. for ( let i = 0; i < reservedRange.vertexCount; i ++ ) {
  19573. idAttribute.setX( reservedRange.vertexStart + i, geometryId );
  19574. }
  19575. idAttribute.needsUpdate = true;
  19576. // update the geometry
  19577. this.setGeometryAt( geometryId, geometry );
  19578. return geometryId;
  19579. }
  19580. setGeometryAt( id, geometry ) {
  19581. if ( id >= this._geometryCount ) {
  19582. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19583. }
  19584. this._validateGeometry( geometry );
  19585. const batchGeometry = this.geometry;
  19586. const hasIndex = batchGeometry.getIndex() !== null;
  19587. const dstIndex = batchGeometry.getIndex();
  19588. const srcIndex = geometry.getIndex();
  19589. const reservedRange = this._reservedRanges[ id ];
  19590. if (
  19591. hasIndex &&
  19592. srcIndex.count > reservedRange.indexCount ||
  19593. geometry.attributes.position.count > reservedRange.vertexCount
  19594. ) {
  19595. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  19596. }
  19597. // copy geometry over
  19598. const vertexStart = reservedRange.vertexStart;
  19599. const vertexCount = reservedRange.vertexCount;
  19600. for ( const attributeName in batchGeometry.attributes ) {
  19601. if ( attributeName === ID_ATTR_NAME ) {
  19602. continue;
  19603. }
  19604. // copy attribute data
  19605. const srcAttribute = geometry.getAttribute( attributeName );
  19606. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19607. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19608. // fill the rest in with zeroes
  19609. const itemSize = srcAttribute.itemSize;
  19610. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  19611. const index = vertexStart + i;
  19612. for ( let c = 0; c < itemSize; c ++ ) {
  19613. dstAttribute.setComponent( index, c, 0 );
  19614. }
  19615. }
  19616. dstAttribute.needsUpdate = true;
  19617. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  19618. }
  19619. // copy index
  19620. if ( hasIndex ) {
  19621. const indexStart = reservedRange.indexStart;
  19622. // copy index data over
  19623. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19624. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19625. }
  19626. // fill the rest in with zeroes
  19627. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  19628. dstIndex.setX( indexStart + i, vertexStart );
  19629. }
  19630. dstIndex.needsUpdate = true;
  19631. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  19632. }
  19633. // store the bounding boxes
  19634. const bound = this._bounds[ id ];
  19635. if ( geometry.boundingBox !== null ) {
  19636. bound.box.copy( geometry.boundingBox );
  19637. bound.boxInitialized = true;
  19638. } else {
  19639. bound.boxInitialized = false;
  19640. }
  19641. if ( geometry.boundingSphere !== null ) {
  19642. bound.sphere.copy( geometry.boundingSphere );
  19643. bound.sphereInitialized = true;
  19644. } else {
  19645. bound.sphereInitialized = false;
  19646. }
  19647. // set drawRange count
  19648. const drawRange = this._drawRanges[ id ];
  19649. const posAttr = geometry.getAttribute( 'position' );
  19650. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  19651. this._visibilityChanged = true;
  19652. return id;
  19653. }
  19654. deleteGeometry( geometryId ) {
  19655. // Note: User needs to call optimize() afterward to pack the data.
  19656. const active = this._active;
  19657. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  19658. return this;
  19659. }
  19660. active[ geometryId ] = false;
  19661. this._visibilityChanged = true;
  19662. return this;
  19663. }
  19664. // get bounding box and compute it if it doesn't exist
  19665. getBoundingBoxAt( id, target ) {
  19666. const active = this._active;
  19667. if ( active[ id ] === false ) {
  19668. return null;
  19669. }
  19670. // compute bounding box
  19671. const bound = this._bounds[ id ];
  19672. const box = bound.box;
  19673. const geometry = this.geometry;
  19674. if ( bound.boxInitialized === false ) {
  19675. box.makeEmpty();
  19676. const index = geometry.index;
  19677. const position = geometry.attributes.position;
  19678. const drawRange = this._drawRanges[ id ];
  19679. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  19680. let iv = i;
  19681. if ( index ) {
  19682. iv = index.getX( iv );
  19683. }
  19684. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19685. }
  19686. bound.boxInitialized = true;
  19687. }
  19688. target.copy( box );
  19689. return target;
  19690. }
  19691. // get bounding sphere and compute it if it doesn't exist
  19692. getBoundingSphereAt( id, target ) {
  19693. const active = this._active;
  19694. if ( active[ id ] === false ) {
  19695. return null;
  19696. }
  19697. // compute bounding sphere
  19698. const bound = this._bounds[ id ];
  19699. const sphere = bound.sphere;
  19700. const geometry = this.geometry;
  19701. if ( bound.sphereInitialized === false ) {
  19702. sphere.makeEmpty();
  19703. this.getBoundingBoxAt( id, _box$1 );
  19704. _box$1.getCenter( sphere.center );
  19705. const index = geometry.index;
  19706. const position = geometry.attributes.position;
  19707. const drawRange = this._drawRanges[ id ];
  19708. let maxRadiusSq = 0;
  19709. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  19710. let iv = i;
  19711. if ( index ) {
  19712. iv = index.getX( iv );
  19713. }
  19714. _vector$5.fromBufferAttribute( position, iv );
  19715. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  19716. }
  19717. sphere.radius = Math.sqrt( maxRadiusSq );
  19718. bound.sphereInitialized = true;
  19719. }
  19720. target.copy( sphere );
  19721. return target;
  19722. }
  19723. setMatrixAt( geometryId, matrix ) {
  19724. // @TODO: Map geometryId to index of the arrays because
  19725. // optimize() can make geometryId mismatch the index
  19726. const active = this._active;
  19727. const matricesTexture = this._matricesTexture;
  19728. const matricesArray = this._matricesTexture.image.data;
  19729. const geometryCount = this._geometryCount;
  19730. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19731. return this;
  19732. }
  19733. matrix.toArray( matricesArray, geometryId * 16 );
  19734. matricesTexture.needsUpdate = true;
  19735. return this;
  19736. }
  19737. getMatrixAt( geometryId, matrix ) {
  19738. const active = this._active;
  19739. const matricesArray = this._matricesTexture.image.data;
  19740. const geometryCount = this._geometryCount;
  19741. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19742. return null;
  19743. }
  19744. return matrix.fromArray( matricesArray, geometryId * 16 );
  19745. }
  19746. setVisibleAt( geometryId, value ) {
  19747. const visibility = this._visibility;
  19748. const active = this._active;
  19749. const geometryCount = this._geometryCount;
  19750. // if the geometry is out of range, not active, or visibility state
  19751. // does not change then return early
  19752. if (
  19753. geometryId >= geometryCount ||
  19754. active[ geometryId ] === false ||
  19755. visibility[ geometryId ] === value
  19756. ) {
  19757. return this;
  19758. }
  19759. visibility[ geometryId ] = value;
  19760. this._visibilityChanged = true;
  19761. return this;
  19762. }
  19763. getVisibleAt( geometryId ) {
  19764. const visibility = this._visibility;
  19765. const active = this._active;
  19766. const geometryCount = this._geometryCount;
  19767. // return early if the geometry is out of range or not active
  19768. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  19769. return false;
  19770. }
  19771. return visibility[ geometryId ];
  19772. }
  19773. raycast( raycaster, intersects ) {
  19774. const visibility = this._visibility;
  19775. const active = this._active;
  19776. const drawRanges = this._drawRanges;
  19777. const geometryCount = this._geometryCount;
  19778. const matrixWorld = this.matrixWorld;
  19779. const batchGeometry = this.geometry;
  19780. // iterate over each geometry
  19781. _mesh.material = this.material;
  19782. _mesh.geometry.index = batchGeometry.index;
  19783. _mesh.geometry.attributes = batchGeometry.attributes;
  19784. if ( _mesh.geometry.boundingBox === null ) {
  19785. _mesh.geometry.boundingBox = new Box3();
  19786. }
  19787. if ( _mesh.geometry.boundingSphere === null ) {
  19788. _mesh.geometry.boundingSphere = new Sphere();
  19789. }
  19790. for ( let i = 0; i < geometryCount; i ++ ) {
  19791. if ( ! visibility[ i ] || ! active[ i ] ) {
  19792. continue;
  19793. }
  19794. const drawRange = drawRanges[ i ];
  19795. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  19796. // ge the intersects
  19797. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  19798. this.getBoundingBoxAt( i, _mesh.geometry.boundingBox );
  19799. this.getBoundingSphereAt( i, _mesh.geometry.boundingSphere );
  19800. _mesh.raycast( raycaster, _batchIntersects );
  19801. // add batch id to the intersects
  19802. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  19803. const intersect = _batchIntersects[ j ];
  19804. intersect.object = this;
  19805. intersect.batchId = i;
  19806. intersects.push( intersect );
  19807. }
  19808. _batchIntersects.length = 0;
  19809. }
  19810. _mesh.material = null;
  19811. _mesh.geometry.index = null;
  19812. _mesh.geometry.attributes = {};
  19813. _mesh.geometry.setDrawRange( 0, Infinity );
  19814. }
  19815. copy( source ) {
  19816. super.copy( source );
  19817. this.geometry = source.geometry.clone();
  19818. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  19819. this.sortObjects = source.sortObjects;
  19820. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  19821. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  19822. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  19823. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  19824. this._visibility = source._visibility.slice();
  19825. this._active = source._active.slice();
  19826. this._bounds = source._bounds.map( bound => ( {
  19827. boxInitialized: bound.boxInitialized,
  19828. box: bound.box.clone(),
  19829. sphereInitialized: bound.sphereInitialized,
  19830. sphere: bound.sphere.clone()
  19831. } ) );
  19832. this._maxGeometryCount = source._maxGeometryCount;
  19833. this._maxVertexCount = source._maxVertexCount;
  19834. this._maxIndexCount = source._maxIndexCount;
  19835. this._geometryInitialized = source._geometryInitialized;
  19836. this._geometryCount = source._geometryCount;
  19837. this._multiDrawCounts = source._multiDrawCounts.slice();
  19838. this._multiDrawStarts = source._multiDrawStarts.slice();
  19839. this._matricesTexture = source._matricesTexture.clone();
  19840. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  19841. return this;
  19842. }
  19843. dispose() {
  19844. // Assuming the geometry is not shared with other meshes
  19845. this.geometry.dispose();
  19846. this._matricesTexture.dispose();
  19847. this._matricesTexture = null;
  19848. return this;
  19849. }
  19850. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  19851. // if visibility has not changed and frustum culling and object sorting is not required
  19852. // then skip iterating over all items
  19853. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  19854. return;
  19855. }
  19856. // the indexed version of the multi draw function requires specifying the start
  19857. // offset in bytes.
  19858. const index = geometry.getIndex();
  19859. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  19860. const active = this._active;
  19861. const visibility = this._visibility;
  19862. const multiDrawStarts = this._multiDrawStarts;
  19863. const multiDrawCounts = this._multiDrawCounts;
  19864. const drawRanges = this._drawRanges;
  19865. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  19866. // prepare the frustum in the local frame
  19867. if ( perObjectFrustumCulled ) {
  19868. _projScreenMatrix$2
  19869. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  19870. .multiply( this.matrixWorld );
  19871. _frustum.setFromProjectionMatrix(
  19872. _projScreenMatrix$2,
  19873. renderer.coordinateSystem
  19874. );
  19875. }
  19876. let count = 0;
  19877. if ( this.sortObjects ) {
  19878. // get the camera position in the local frame
  19879. _invMatrixWorld.copy( this.matrixWorld ).invert();
  19880. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  19881. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  19882. if ( visibility[ i ] && active[ i ] ) {
  19883. // get the bounds in world space
  19884. this.getMatrixAt( i, _matrix$1 );
  19885. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  19886. // determine whether the batched geometry is within the frustum
  19887. let culled = false;
  19888. if ( perObjectFrustumCulled ) {
  19889. culled = ! _frustum.intersectsSphere( _sphere$2 );
  19890. }
  19891. if ( ! culled ) {
  19892. // get the distance from camera used for sorting
  19893. const z = _vector$5.distanceTo( _sphere$2.center );
  19894. _renderList.push( drawRanges[ i ], z );
  19895. }
  19896. }
  19897. }
  19898. // Sort the draw ranges and prep for rendering
  19899. const list = _renderList.list;
  19900. const customSort = this.customSort;
  19901. if ( customSort === null ) {
  19902. list.sort( material.transparent ? sortTransparent : sortOpaque );
  19903. } else {
  19904. customSort.call( this, list, camera );
  19905. }
  19906. for ( let i = 0, l = list.length; i < l; i ++ ) {
  19907. const item = list[ i ];
  19908. multiDrawStarts[ count ] = item.start * bytesPerElement;
  19909. multiDrawCounts[ count ] = item.count;
  19910. count ++;
  19911. }
  19912. _renderList.reset();
  19913. } else {
  19914. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  19915. if ( visibility[ i ] && active[ i ] ) {
  19916. // determine whether the batched geometry is within the frustum
  19917. let culled = false;
  19918. if ( perObjectFrustumCulled ) {
  19919. // get the bounds in world space
  19920. this.getMatrixAt( i, _matrix$1 );
  19921. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix$1 );
  19922. culled = ! _frustum.intersectsSphere( _sphere$2 );
  19923. }
  19924. if ( ! culled ) {
  19925. const range = drawRanges[ i ];
  19926. multiDrawStarts[ count ] = range.start * bytesPerElement;
  19927. multiDrawCounts[ count ] = range.count;
  19928. count ++;
  19929. }
  19930. }
  19931. }
  19932. }
  19933. this._multiDrawCount = count;
  19934. this._visibilityChanged = false;
  19935. }
  19936. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  19937. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  19938. }
  19939. }
  19940. class LineBasicMaterial extends Material {
  19941. constructor( parameters ) {
  19942. super();
  19943. this.isLineBasicMaterial = true;
  19944. this.type = 'LineBasicMaterial';
  19945. this.color = new Color( 0xffffff );
  19946. this.map = null;
  19947. this.linewidth = 1;
  19948. this.linecap = 'round';
  19949. this.linejoin = 'round';
  19950. this.fog = true;
  19951. this.setValues( parameters );
  19952. }
  19953. copy( source ) {
  19954. super.copy( source );
  19955. this.color.copy( source.color );
  19956. this.map = source.map;
  19957. this.linewidth = source.linewidth;
  19958. this.linecap = source.linecap;
  19959. this.linejoin = source.linejoin;
  19960. this.fog = source.fog;
  19961. return this;
  19962. }
  19963. }
  19964. const _start$1 = /*@__PURE__*/ new Vector3();
  19965. const _end$1 = /*@__PURE__*/ new Vector3();
  19966. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  19967. const _ray$1 = /*@__PURE__*/ new Ray();
  19968. const _sphere$1 = /*@__PURE__*/ new Sphere();
  19969. class Line extends Object3D {
  19970. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  19971. super();
  19972. this.isLine = true;
  19973. this.type = 'Line';
  19974. this.geometry = geometry;
  19975. this.material = material;
  19976. this.updateMorphTargets();
  19977. }
  19978. copy( source, recursive ) {
  19979. super.copy( source, recursive );
  19980. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  19981. this.geometry = source.geometry;
  19982. return this;
  19983. }
  19984. computeLineDistances() {
  19985. const geometry = this.geometry;
  19986. // we assume non-indexed geometry
  19987. if ( geometry.index === null ) {
  19988. const positionAttribute = geometry.attributes.position;
  19989. const lineDistances = [ 0 ];
  19990. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  19991. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  19992. _end$1.fromBufferAttribute( positionAttribute, i );
  19993. lineDistances[ i ] = lineDistances[ i - 1 ];
  19994. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  19995. }
  19996. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19997. } else {
  19998. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19999. }
  20000. return this;
  20001. }
  20002. raycast( raycaster, intersects ) {
  20003. const geometry = this.geometry;
  20004. const matrixWorld = this.matrixWorld;
  20005. const threshold = raycaster.params.Line.threshold;
  20006. const drawRange = geometry.drawRange;
  20007. // Checking boundingSphere distance to ray
  20008. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20009. _sphere$1.copy( geometry.boundingSphere );
  20010. _sphere$1.applyMatrix4( matrixWorld );
  20011. _sphere$1.radius += threshold;
  20012. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20013. //
  20014. _inverseMatrix$1.copy( matrixWorld ).invert();
  20015. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20016. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20017. const localThresholdSq = localThreshold * localThreshold;
  20018. const vStart = new Vector3();
  20019. const vEnd = new Vector3();
  20020. const interSegment = new Vector3();
  20021. const interRay = new Vector3();
  20022. const step = this.isLineSegments ? 2 : 1;
  20023. const index = geometry.index;
  20024. const attributes = geometry.attributes;
  20025. const positionAttribute = attributes.position;
  20026. if ( index !== null ) {
  20027. const start = Math.max( 0, drawRange.start );
  20028. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20029. for ( let i = start, l = end - 1; i < l; i += step ) {
  20030. const a = index.getX( i );
  20031. const b = index.getX( i + 1 );
  20032. vStart.fromBufferAttribute( positionAttribute, a );
  20033. vEnd.fromBufferAttribute( positionAttribute, b );
  20034. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20035. if ( distSq > localThresholdSq ) continue;
  20036. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20037. const distance = raycaster.ray.origin.distanceTo( interRay );
  20038. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20039. intersects.push( {
  20040. distance: distance,
  20041. // What do we want? intersection point on the ray or on the segment??
  20042. // point: raycaster.ray.at( distance ),
  20043. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20044. index: i,
  20045. face: null,
  20046. faceIndex: null,
  20047. object: this
  20048. } );
  20049. }
  20050. } else {
  20051. const start = Math.max( 0, drawRange.start );
  20052. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20053. for ( let i = start, l = end - 1; i < l; i += step ) {
  20054. vStart.fromBufferAttribute( positionAttribute, i );
  20055. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  20056. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20057. if ( distSq > localThresholdSq ) continue;
  20058. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20059. const distance = raycaster.ray.origin.distanceTo( interRay );
  20060. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20061. intersects.push( {
  20062. distance: distance,
  20063. // What do we want? intersection point on the ray or on the segment??
  20064. // point: raycaster.ray.at( distance ),
  20065. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20066. index: i,
  20067. face: null,
  20068. faceIndex: null,
  20069. object: this
  20070. } );
  20071. }
  20072. }
  20073. }
  20074. updateMorphTargets() {
  20075. const geometry = this.geometry;
  20076. const morphAttributes = geometry.morphAttributes;
  20077. const keys = Object.keys( morphAttributes );
  20078. if ( keys.length > 0 ) {
  20079. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20080. if ( morphAttribute !== undefined ) {
  20081. this.morphTargetInfluences = [];
  20082. this.morphTargetDictionary = {};
  20083. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20084. const name = morphAttribute[ m ].name || String( m );
  20085. this.morphTargetInfluences.push( 0 );
  20086. this.morphTargetDictionary[ name ] = m;
  20087. }
  20088. }
  20089. }
  20090. }
  20091. }
  20092. const _start = /*@__PURE__*/ new Vector3();
  20093. const _end = /*@__PURE__*/ new Vector3();
  20094. class LineSegments extends Line {
  20095. constructor( geometry, material ) {
  20096. super( geometry, material );
  20097. this.isLineSegments = true;
  20098. this.type = 'LineSegments';
  20099. }
  20100. computeLineDistances() {
  20101. const geometry = this.geometry;
  20102. // we assume non-indexed geometry
  20103. if ( geometry.index === null ) {
  20104. const positionAttribute = geometry.attributes.position;
  20105. const lineDistances = [];
  20106. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20107. _start.fromBufferAttribute( positionAttribute, i );
  20108. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20109. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20110. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20111. }
  20112. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20113. } else {
  20114. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20115. }
  20116. return this;
  20117. }
  20118. }
  20119. class LineLoop extends Line {
  20120. constructor( geometry, material ) {
  20121. super( geometry, material );
  20122. this.isLineLoop = true;
  20123. this.type = 'LineLoop';
  20124. }
  20125. }
  20126. class PointsMaterial extends Material {
  20127. constructor( parameters ) {
  20128. super();
  20129. this.isPointsMaterial = true;
  20130. this.type = 'PointsMaterial';
  20131. this.color = new Color( 0xffffff );
  20132. this.map = null;
  20133. this.alphaMap = null;
  20134. this.size = 1;
  20135. this.sizeAttenuation = true;
  20136. this.fog = true;
  20137. this.setValues( parameters );
  20138. }
  20139. copy( source ) {
  20140. super.copy( source );
  20141. this.color.copy( source.color );
  20142. this.map = source.map;
  20143. this.alphaMap = source.alphaMap;
  20144. this.size = source.size;
  20145. this.sizeAttenuation = source.sizeAttenuation;
  20146. this.fog = source.fog;
  20147. return this;
  20148. }
  20149. }
  20150. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20151. const _ray = /*@__PURE__*/ new Ray();
  20152. const _sphere = /*@__PURE__*/ new Sphere();
  20153. const _position$2 = /*@__PURE__*/ new Vector3();
  20154. class Points extends Object3D {
  20155. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20156. super();
  20157. this.isPoints = true;
  20158. this.type = 'Points';
  20159. this.geometry = geometry;
  20160. this.material = material;
  20161. this.updateMorphTargets();
  20162. }
  20163. copy( source, recursive ) {
  20164. super.copy( source, recursive );
  20165. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20166. this.geometry = source.geometry;
  20167. return this;
  20168. }
  20169. raycast( raycaster, intersects ) {
  20170. const geometry = this.geometry;
  20171. const matrixWorld = this.matrixWorld;
  20172. const threshold = raycaster.params.Points.threshold;
  20173. const drawRange = geometry.drawRange;
  20174. // Checking boundingSphere distance to ray
  20175. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20176. _sphere.copy( geometry.boundingSphere );
  20177. _sphere.applyMatrix4( matrixWorld );
  20178. _sphere.radius += threshold;
  20179. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20180. //
  20181. _inverseMatrix.copy( matrixWorld ).invert();
  20182. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20183. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20184. const localThresholdSq = localThreshold * localThreshold;
  20185. const index = geometry.index;
  20186. const attributes = geometry.attributes;
  20187. const positionAttribute = attributes.position;
  20188. if ( index !== null ) {
  20189. const start = Math.max( 0, drawRange.start );
  20190. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20191. for ( let i = start, il = end; i < il; i ++ ) {
  20192. const a = index.getX( i );
  20193. _position$2.fromBufferAttribute( positionAttribute, a );
  20194. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  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; i < l; i ++ ) {
  20200. _position$2.fromBufferAttribute( positionAttribute, i );
  20201. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20202. }
  20203. }
  20204. }
  20205. updateMorphTargets() {
  20206. const geometry = this.geometry;
  20207. const morphAttributes = geometry.morphAttributes;
  20208. const keys = Object.keys( morphAttributes );
  20209. if ( keys.length > 0 ) {
  20210. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20211. if ( morphAttribute !== undefined ) {
  20212. this.morphTargetInfluences = [];
  20213. this.morphTargetDictionary = {};
  20214. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20215. const name = morphAttribute[ m ].name || String( m );
  20216. this.morphTargetInfluences.push( 0 );
  20217. this.morphTargetDictionary[ name ] = m;
  20218. }
  20219. }
  20220. }
  20221. }
  20222. }
  20223. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20224. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20225. if ( rayPointDistanceSq < localThresholdSq ) {
  20226. const intersectPoint = new Vector3();
  20227. _ray.closestPointToPoint( point, intersectPoint );
  20228. intersectPoint.applyMatrix4( matrixWorld );
  20229. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20230. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20231. intersects.push( {
  20232. distance: distance,
  20233. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20234. point: intersectPoint,
  20235. index: index,
  20236. face: null,
  20237. object: object
  20238. } );
  20239. }
  20240. }
  20241. class VideoTexture extends Texture {
  20242. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20243. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20244. this.isVideoTexture = true;
  20245. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20246. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20247. this.generateMipmaps = false;
  20248. const scope = this;
  20249. function updateVideo() {
  20250. scope.needsUpdate = true;
  20251. video.requestVideoFrameCallback( updateVideo );
  20252. }
  20253. if ( 'requestVideoFrameCallback' in video ) {
  20254. video.requestVideoFrameCallback( updateVideo );
  20255. }
  20256. }
  20257. clone() {
  20258. return new this.constructor( this.image ).copy( this );
  20259. }
  20260. update() {
  20261. const video = this.image;
  20262. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20263. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20264. this.needsUpdate = true;
  20265. }
  20266. }
  20267. }
  20268. class FramebufferTexture extends Texture {
  20269. constructor( width, height ) {
  20270. super( { width, height } );
  20271. this.isFramebufferTexture = true;
  20272. this.magFilter = NearestFilter;
  20273. this.minFilter = NearestFilter;
  20274. this.generateMipmaps = false;
  20275. this.needsUpdate = true;
  20276. }
  20277. }
  20278. class CompressedTexture extends Texture {
  20279. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20280. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20281. this.isCompressedTexture = true;
  20282. this.image = { width: width, height: height };
  20283. this.mipmaps = mipmaps;
  20284. // no flipping for cube textures
  20285. // (also flipping doesn't work for compressed textures )
  20286. this.flipY = false;
  20287. // can't generate mipmaps for compressed textures
  20288. // mips must be embedded in DDS files
  20289. this.generateMipmaps = false;
  20290. }
  20291. }
  20292. class CompressedArrayTexture extends CompressedTexture {
  20293. constructor( mipmaps, width, height, depth, format, type ) {
  20294. super( mipmaps, width, height, format, type );
  20295. this.isCompressedArrayTexture = true;
  20296. this.image.depth = depth;
  20297. this.wrapR = ClampToEdgeWrapping;
  20298. }
  20299. }
  20300. class CompressedCubeTexture extends CompressedTexture {
  20301. constructor( images, format, type ) {
  20302. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  20303. this.isCompressedCubeTexture = true;
  20304. this.isCubeTexture = true;
  20305. this.image = images;
  20306. }
  20307. }
  20308. class CanvasTexture extends Texture {
  20309. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20310. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20311. this.isCanvasTexture = true;
  20312. this.needsUpdate = true;
  20313. }
  20314. }
  20315. /**
  20316. * Extensible curve object.
  20317. *
  20318. * Some common of curve methods:
  20319. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20320. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20321. * .getPoints(), .getSpacedPoints()
  20322. * .getLength()
  20323. * .updateArcLengths()
  20324. *
  20325. * This following curves inherit from THREE.Curve:
  20326. *
  20327. * -- 2D curves --
  20328. * THREE.ArcCurve
  20329. * THREE.CubicBezierCurve
  20330. * THREE.EllipseCurve
  20331. * THREE.LineCurve
  20332. * THREE.QuadraticBezierCurve
  20333. * THREE.SplineCurve
  20334. *
  20335. * -- 3D curves --
  20336. * THREE.CatmullRomCurve3
  20337. * THREE.CubicBezierCurve3
  20338. * THREE.LineCurve3
  20339. * THREE.QuadraticBezierCurve3
  20340. *
  20341. * A series of curves can be represented as a THREE.CurvePath.
  20342. *
  20343. **/
  20344. class Curve {
  20345. constructor() {
  20346. this.type = 'Curve';
  20347. this.arcLengthDivisions = 200;
  20348. }
  20349. // Virtual base class method to overwrite and implement in subclasses
  20350. // - t [0 .. 1]
  20351. getPoint( /* t, optionalTarget */ ) {
  20352. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20353. return null;
  20354. }
  20355. // Get point at relative position in curve according to arc length
  20356. // - u [0 .. 1]
  20357. getPointAt( u, optionalTarget ) {
  20358. const t = this.getUtoTmapping( u );
  20359. return this.getPoint( t, optionalTarget );
  20360. }
  20361. // Get sequence of points using getPoint( t )
  20362. getPoints( divisions = 5 ) {
  20363. const points = [];
  20364. for ( let d = 0; d <= divisions; d ++ ) {
  20365. points.push( this.getPoint( d / divisions ) );
  20366. }
  20367. return points;
  20368. }
  20369. // Get sequence of points using getPointAt( u )
  20370. getSpacedPoints( divisions = 5 ) {
  20371. const points = [];
  20372. for ( let d = 0; d <= divisions; d ++ ) {
  20373. points.push( this.getPointAt( d / divisions ) );
  20374. }
  20375. return points;
  20376. }
  20377. // Get total curve arc length
  20378. getLength() {
  20379. const lengths = this.getLengths();
  20380. return lengths[ lengths.length - 1 ];
  20381. }
  20382. // Get list of cumulative segment lengths
  20383. getLengths( divisions = this.arcLengthDivisions ) {
  20384. if ( this.cacheArcLengths &&
  20385. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20386. ! this.needsUpdate ) {
  20387. return this.cacheArcLengths;
  20388. }
  20389. this.needsUpdate = false;
  20390. const cache = [];
  20391. let current, last = this.getPoint( 0 );
  20392. let sum = 0;
  20393. cache.push( 0 );
  20394. for ( let p = 1; p <= divisions; p ++ ) {
  20395. current = this.getPoint( p / divisions );
  20396. sum += current.distanceTo( last );
  20397. cache.push( sum );
  20398. last = current;
  20399. }
  20400. this.cacheArcLengths = cache;
  20401. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20402. }
  20403. updateArcLengths() {
  20404. this.needsUpdate = true;
  20405. this.getLengths();
  20406. }
  20407. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20408. getUtoTmapping( u, distance ) {
  20409. const arcLengths = this.getLengths();
  20410. let i = 0;
  20411. const il = arcLengths.length;
  20412. let targetArcLength; // The targeted u distance value to get
  20413. if ( distance ) {
  20414. targetArcLength = distance;
  20415. } else {
  20416. targetArcLength = u * arcLengths[ il - 1 ];
  20417. }
  20418. // binary search for the index with largest value smaller than target u distance
  20419. let low = 0, high = il - 1, comparison;
  20420. while ( low <= high ) {
  20421. 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
  20422. comparison = arcLengths[ i ] - targetArcLength;
  20423. if ( comparison < 0 ) {
  20424. low = i + 1;
  20425. } else if ( comparison > 0 ) {
  20426. high = i - 1;
  20427. } else {
  20428. high = i;
  20429. break;
  20430. // DONE
  20431. }
  20432. }
  20433. i = high;
  20434. if ( arcLengths[ i ] === targetArcLength ) {
  20435. return i / ( il - 1 );
  20436. }
  20437. // we could get finer grain at lengths, or use simple interpolation between two points
  20438. const lengthBefore = arcLengths[ i ];
  20439. const lengthAfter = arcLengths[ i + 1 ];
  20440. const segmentLength = lengthAfter - lengthBefore;
  20441. // determine where we are between the 'before' and 'after' points
  20442. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20443. // add that fractional amount to t
  20444. const t = ( i + segmentFraction ) / ( il - 1 );
  20445. return t;
  20446. }
  20447. // Returns a unit vector tangent at t
  20448. // In case any sub curve does not implement its tangent derivation,
  20449. // 2 points a small delta apart will be used to find its gradient
  20450. // which seems to give a reasonable approximation
  20451. getTangent( t, optionalTarget ) {
  20452. const delta = 0.0001;
  20453. let t1 = t - delta;
  20454. let t2 = t + delta;
  20455. // Capping in case of danger
  20456. if ( t1 < 0 ) t1 = 0;
  20457. if ( t2 > 1 ) t2 = 1;
  20458. const pt1 = this.getPoint( t1 );
  20459. const pt2 = this.getPoint( t2 );
  20460. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  20461. tangent.copy( pt2 ).sub( pt1 ).normalize();
  20462. return tangent;
  20463. }
  20464. getTangentAt( u, optionalTarget ) {
  20465. const t = this.getUtoTmapping( u );
  20466. return this.getTangent( t, optionalTarget );
  20467. }
  20468. computeFrenetFrames( segments, closed ) {
  20469. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20470. const normal = new Vector3();
  20471. const tangents = [];
  20472. const normals = [];
  20473. const binormals = [];
  20474. const vec = new Vector3();
  20475. const mat = new Matrix4();
  20476. // compute the tangent vectors for each segment on the curve
  20477. for ( let i = 0; i <= segments; i ++ ) {
  20478. const u = i / segments;
  20479. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  20480. }
  20481. // select an initial normal vector perpendicular to the first tangent vector,
  20482. // and in the direction of the minimum tangent xyz component
  20483. normals[ 0 ] = new Vector3();
  20484. binormals[ 0 ] = new Vector3();
  20485. let min = Number.MAX_VALUE;
  20486. const tx = Math.abs( tangents[ 0 ].x );
  20487. const ty = Math.abs( tangents[ 0 ].y );
  20488. const tz = Math.abs( tangents[ 0 ].z );
  20489. if ( tx <= min ) {
  20490. min = tx;
  20491. normal.set( 1, 0, 0 );
  20492. }
  20493. if ( ty <= min ) {
  20494. min = ty;
  20495. normal.set( 0, 1, 0 );
  20496. }
  20497. if ( tz <= min ) {
  20498. normal.set( 0, 0, 1 );
  20499. }
  20500. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20501. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20502. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20503. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20504. for ( let i = 1; i <= segments; i ++ ) {
  20505. normals[ i ] = normals[ i - 1 ].clone();
  20506. binormals[ i ] = binormals[ i - 1 ].clone();
  20507. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20508. if ( vec.length() > Number.EPSILON ) {
  20509. vec.normalize();
  20510. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20511. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20512. }
  20513. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20514. }
  20515. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20516. if ( closed === true ) {
  20517. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20518. theta /= segments;
  20519. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20520. theta = - theta;
  20521. }
  20522. for ( let i = 1; i <= segments; i ++ ) {
  20523. // twist a little...
  20524. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20525. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20526. }
  20527. }
  20528. return {
  20529. tangents: tangents,
  20530. normals: normals,
  20531. binormals: binormals
  20532. };
  20533. }
  20534. clone() {
  20535. return new this.constructor().copy( this );
  20536. }
  20537. copy( source ) {
  20538. this.arcLengthDivisions = source.arcLengthDivisions;
  20539. return this;
  20540. }
  20541. toJSON() {
  20542. const data = {
  20543. metadata: {
  20544. version: 4.6,
  20545. type: 'Curve',
  20546. generator: 'Curve.toJSON'
  20547. }
  20548. };
  20549. data.arcLengthDivisions = this.arcLengthDivisions;
  20550. data.type = this.type;
  20551. return data;
  20552. }
  20553. fromJSON( json ) {
  20554. this.arcLengthDivisions = json.arcLengthDivisions;
  20555. return this;
  20556. }
  20557. }
  20558. class EllipseCurve extends Curve {
  20559. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  20560. super();
  20561. this.isEllipseCurve = true;
  20562. this.type = 'EllipseCurve';
  20563. this.aX = aX;
  20564. this.aY = aY;
  20565. this.xRadius = xRadius;
  20566. this.yRadius = yRadius;
  20567. this.aStartAngle = aStartAngle;
  20568. this.aEndAngle = aEndAngle;
  20569. this.aClockwise = aClockwise;
  20570. this.aRotation = aRotation;
  20571. }
  20572. getPoint( t, optionalTarget = new Vector2() ) {
  20573. const point = optionalTarget;
  20574. const twoPi = Math.PI * 2;
  20575. let deltaAngle = this.aEndAngle - this.aStartAngle;
  20576. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20577. // ensures that deltaAngle is 0 .. 2 PI
  20578. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20579. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20580. if ( deltaAngle < Number.EPSILON ) {
  20581. if ( samePoints ) {
  20582. deltaAngle = 0;
  20583. } else {
  20584. deltaAngle = twoPi;
  20585. }
  20586. }
  20587. if ( this.aClockwise === true && ! samePoints ) {
  20588. if ( deltaAngle === twoPi ) {
  20589. deltaAngle = - twoPi;
  20590. } else {
  20591. deltaAngle = deltaAngle - twoPi;
  20592. }
  20593. }
  20594. const angle = this.aStartAngle + t * deltaAngle;
  20595. let x = this.aX + this.xRadius * Math.cos( angle );
  20596. let y = this.aY + this.yRadius * Math.sin( angle );
  20597. if ( this.aRotation !== 0 ) {
  20598. const cos = Math.cos( this.aRotation );
  20599. const sin = Math.sin( this.aRotation );
  20600. const tx = x - this.aX;
  20601. const ty = y - this.aY;
  20602. // Rotate the point about the center of the ellipse.
  20603. x = tx * cos - ty * sin + this.aX;
  20604. y = tx * sin + ty * cos + this.aY;
  20605. }
  20606. return point.set( x, y );
  20607. }
  20608. copy( source ) {
  20609. super.copy( source );
  20610. this.aX = source.aX;
  20611. this.aY = source.aY;
  20612. this.xRadius = source.xRadius;
  20613. this.yRadius = source.yRadius;
  20614. this.aStartAngle = source.aStartAngle;
  20615. this.aEndAngle = source.aEndAngle;
  20616. this.aClockwise = source.aClockwise;
  20617. this.aRotation = source.aRotation;
  20618. return this;
  20619. }
  20620. toJSON() {
  20621. const data = super.toJSON();
  20622. data.aX = this.aX;
  20623. data.aY = this.aY;
  20624. data.xRadius = this.xRadius;
  20625. data.yRadius = this.yRadius;
  20626. data.aStartAngle = this.aStartAngle;
  20627. data.aEndAngle = this.aEndAngle;
  20628. data.aClockwise = this.aClockwise;
  20629. data.aRotation = this.aRotation;
  20630. return data;
  20631. }
  20632. fromJSON( json ) {
  20633. super.fromJSON( json );
  20634. this.aX = json.aX;
  20635. this.aY = json.aY;
  20636. this.xRadius = json.xRadius;
  20637. this.yRadius = json.yRadius;
  20638. this.aStartAngle = json.aStartAngle;
  20639. this.aEndAngle = json.aEndAngle;
  20640. this.aClockwise = json.aClockwise;
  20641. this.aRotation = json.aRotation;
  20642. return this;
  20643. }
  20644. }
  20645. class ArcCurve extends EllipseCurve {
  20646. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20647. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20648. this.isArcCurve = true;
  20649. this.type = 'ArcCurve';
  20650. }
  20651. }
  20652. /**
  20653. * Centripetal CatmullRom Curve - which is useful for avoiding
  20654. * cusps and self-intersections in non-uniform catmull rom curves.
  20655. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  20656. *
  20657. * curve.type accepts centripetal(default), chordal and catmullrom
  20658. * curve.tension is used for catmullrom which defaults to 0.5
  20659. */
  20660. /*
  20661. Based on an optimized c++ solution in
  20662. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  20663. - http://ideone.com/NoEbVM
  20664. This CubicPoly class could be used for reusing some variables and calculations,
  20665. but for three.js curve use, it could be possible inlined and flatten into a single function call
  20666. which can be placed in CurveUtils.
  20667. */
  20668. function CubicPoly() {
  20669. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  20670. /*
  20671. * Compute coefficients for a cubic polynomial
  20672. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  20673. * such that
  20674. * p(0) = x0, p(1) = x1
  20675. * and
  20676. * p'(0) = t0, p'(1) = t1.
  20677. */
  20678. function init( x0, x1, t0, t1 ) {
  20679. c0 = x0;
  20680. c1 = t0;
  20681. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  20682. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  20683. }
  20684. return {
  20685. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  20686. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  20687. },
  20688. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  20689. // compute tangents when parameterized in [t1,t2]
  20690. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  20691. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  20692. // rescale tangents for parametrization in [0,1]
  20693. t1 *= dt1;
  20694. t2 *= dt1;
  20695. init( x1, x2, t1, t2 );
  20696. },
  20697. calc: function ( t ) {
  20698. const t2 = t * t;
  20699. const t3 = t2 * t;
  20700. return c0 + c1 * t + c2 * t2 + c3 * t3;
  20701. }
  20702. };
  20703. }
  20704. //
  20705. const tmp = /*@__PURE__*/ new Vector3();
  20706. const px = /*@__PURE__*/ new CubicPoly();
  20707. const py = /*@__PURE__*/ new CubicPoly();
  20708. const pz = /*@__PURE__*/ new CubicPoly();
  20709. class CatmullRomCurve3 extends Curve {
  20710. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  20711. super();
  20712. this.isCatmullRomCurve3 = true;
  20713. this.type = 'CatmullRomCurve3';
  20714. this.points = points;
  20715. this.closed = closed;
  20716. this.curveType = curveType;
  20717. this.tension = tension;
  20718. }
  20719. getPoint( t, optionalTarget = new Vector3() ) {
  20720. const point = optionalTarget;
  20721. const points = this.points;
  20722. const l = points.length;
  20723. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  20724. let intPoint = Math.floor( p );
  20725. let weight = p - intPoint;
  20726. if ( this.closed ) {
  20727. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  20728. } else if ( weight === 0 && intPoint === l - 1 ) {
  20729. intPoint = l - 2;
  20730. weight = 1;
  20731. }
  20732. let p0, p3; // 4 points (p1 & p2 defined below)
  20733. if ( this.closed || intPoint > 0 ) {
  20734. p0 = points[ ( intPoint - 1 ) % l ];
  20735. } else {
  20736. // extrapolate first point
  20737. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  20738. p0 = tmp;
  20739. }
  20740. const p1 = points[ intPoint % l ];
  20741. const p2 = points[ ( intPoint + 1 ) % l ];
  20742. if ( this.closed || intPoint + 2 < l ) {
  20743. p3 = points[ ( intPoint + 2 ) % l ];
  20744. } else {
  20745. // extrapolate last point
  20746. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  20747. p3 = tmp;
  20748. }
  20749. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  20750. // init Centripetal / Chordal Catmull-Rom
  20751. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  20752. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  20753. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  20754. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  20755. // safety check for repeated points
  20756. if ( dt1 < 1e-4 ) dt1 = 1.0;
  20757. if ( dt0 < 1e-4 ) dt0 = dt1;
  20758. if ( dt2 < 1e-4 ) dt2 = dt1;
  20759. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  20760. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  20761. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  20762. } else if ( this.curveType === 'catmullrom' ) {
  20763. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  20764. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  20765. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  20766. }
  20767. point.set(
  20768. px.calc( weight ),
  20769. py.calc( weight ),
  20770. pz.calc( weight )
  20771. );
  20772. return point;
  20773. }
  20774. copy( source ) {
  20775. super.copy( source );
  20776. this.points = [];
  20777. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  20778. const point = source.points[ i ];
  20779. this.points.push( point.clone() );
  20780. }
  20781. this.closed = source.closed;
  20782. this.curveType = source.curveType;
  20783. this.tension = source.tension;
  20784. return this;
  20785. }
  20786. toJSON() {
  20787. const data = super.toJSON();
  20788. data.points = [];
  20789. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20790. const point = this.points[ i ];
  20791. data.points.push( point.toArray() );
  20792. }
  20793. data.closed = this.closed;
  20794. data.curveType = this.curveType;
  20795. data.tension = this.tension;
  20796. return data;
  20797. }
  20798. fromJSON( json ) {
  20799. super.fromJSON( json );
  20800. this.points = [];
  20801. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20802. const point = json.points[ i ];
  20803. this.points.push( new Vector3().fromArray( point ) );
  20804. }
  20805. this.closed = json.closed;
  20806. this.curveType = json.curveType;
  20807. this.tension = json.tension;
  20808. return this;
  20809. }
  20810. }
  20811. /**
  20812. * Bezier Curves formulas obtained from
  20813. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  20814. */
  20815. function CatmullRom( t, p0, p1, p2, p3 ) {
  20816. const v0 = ( p2 - p0 ) * 0.5;
  20817. const v1 = ( p3 - p1 ) * 0.5;
  20818. const t2 = t * t;
  20819. const t3 = t * t2;
  20820. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20821. }
  20822. //
  20823. function QuadraticBezierP0( t, p ) {
  20824. const k = 1 - t;
  20825. return k * k * p;
  20826. }
  20827. function QuadraticBezierP1( t, p ) {
  20828. return 2 * ( 1 - t ) * t * p;
  20829. }
  20830. function QuadraticBezierP2( t, p ) {
  20831. return t * t * p;
  20832. }
  20833. function QuadraticBezier( t, p0, p1, p2 ) {
  20834. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20835. QuadraticBezierP2( t, p2 );
  20836. }
  20837. //
  20838. function CubicBezierP0( t, p ) {
  20839. const k = 1 - t;
  20840. return k * k * k * p;
  20841. }
  20842. function CubicBezierP1( t, p ) {
  20843. const k = 1 - t;
  20844. return 3 * k * k * t * p;
  20845. }
  20846. function CubicBezierP2( t, p ) {
  20847. return 3 * ( 1 - t ) * t * t * p;
  20848. }
  20849. function CubicBezierP3( t, p ) {
  20850. return t * t * t * p;
  20851. }
  20852. function CubicBezier( t, p0, p1, p2, p3 ) {
  20853. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20854. CubicBezierP3( t, p3 );
  20855. }
  20856. class CubicBezierCurve extends Curve {
  20857. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  20858. super();
  20859. this.isCubicBezierCurve = true;
  20860. this.type = 'CubicBezierCurve';
  20861. this.v0 = v0;
  20862. this.v1 = v1;
  20863. this.v2 = v2;
  20864. this.v3 = v3;
  20865. }
  20866. getPoint( t, optionalTarget = new Vector2() ) {
  20867. const point = optionalTarget;
  20868. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20869. point.set(
  20870. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20871. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  20872. );
  20873. return point;
  20874. }
  20875. copy( source ) {
  20876. super.copy( source );
  20877. this.v0.copy( source.v0 );
  20878. this.v1.copy( source.v1 );
  20879. this.v2.copy( source.v2 );
  20880. this.v3.copy( source.v3 );
  20881. return this;
  20882. }
  20883. toJSON() {
  20884. const data = super.toJSON();
  20885. data.v0 = this.v0.toArray();
  20886. data.v1 = this.v1.toArray();
  20887. data.v2 = this.v2.toArray();
  20888. data.v3 = this.v3.toArray();
  20889. return data;
  20890. }
  20891. fromJSON( json ) {
  20892. super.fromJSON( json );
  20893. this.v0.fromArray( json.v0 );
  20894. this.v1.fromArray( json.v1 );
  20895. this.v2.fromArray( json.v2 );
  20896. this.v3.fromArray( json.v3 );
  20897. return this;
  20898. }
  20899. }
  20900. class CubicBezierCurve3 extends Curve {
  20901. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  20902. super();
  20903. this.isCubicBezierCurve3 = true;
  20904. this.type = 'CubicBezierCurve3';
  20905. this.v0 = v0;
  20906. this.v1 = v1;
  20907. this.v2 = v2;
  20908. this.v3 = v3;
  20909. }
  20910. getPoint( t, optionalTarget = new Vector3() ) {
  20911. const point = optionalTarget;
  20912. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20913. point.set(
  20914. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20915. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  20916. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  20917. );
  20918. return point;
  20919. }
  20920. copy( source ) {
  20921. super.copy( source );
  20922. this.v0.copy( source.v0 );
  20923. this.v1.copy( source.v1 );
  20924. this.v2.copy( source.v2 );
  20925. this.v3.copy( source.v3 );
  20926. return this;
  20927. }
  20928. toJSON() {
  20929. const data = super.toJSON();
  20930. data.v0 = this.v0.toArray();
  20931. data.v1 = this.v1.toArray();
  20932. data.v2 = this.v2.toArray();
  20933. data.v3 = this.v3.toArray();
  20934. return data;
  20935. }
  20936. fromJSON( json ) {
  20937. super.fromJSON( json );
  20938. this.v0.fromArray( json.v0 );
  20939. this.v1.fromArray( json.v1 );
  20940. this.v2.fromArray( json.v2 );
  20941. this.v3.fromArray( json.v3 );
  20942. return this;
  20943. }
  20944. }
  20945. class LineCurve extends Curve {
  20946. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  20947. super();
  20948. this.isLineCurve = true;
  20949. this.type = 'LineCurve';
  20950. this.v1 = v1;
  20951. this.v2 = v2;
  20952. }
  20953. getPoint( t, optionalTarget = new Vector2() ) {
  20954. const point = optionalTarget;
  20955. if ( t === 1 ) {
  20956. point.copy( this.v2 );
  20957. } else {
  20958. point.copy( this.v2 ).sub( this.v1 );
  20959. point.multiplyScalar( t ).add( this.v1 );
  20960. }
  20961. return point;
  20962. }
  20963. // Line curve is linear, so we can overwrite default getPointAt
  20964. getPointAt( u, optionalTarget ) {
  20965. return this.getPoint( u, optionalTarget );
  20966. }
  20967. getTangent( t, optionalTarget = new Vector2() ) {
  20968. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20969. }
  20970. getTangentAt( u, optionalTarget ) {
  20971. return this.getTangent( u, optionalTarget );
  20972. }
  20973. copy( source ) {
  20974. super.copy( source );
  20975. this.v1.copy( source.v1 );
  20976. this.v2.copy( source.v2 );
  20977. return this;
  20978. }
  20979. toJSON() {
  20980. const data = super.toJSON();
  20981. data.v1 = this.v1.toArray();
  20982. data.v2 = this.v2.toArray();
  20983. return data;
  20984. }
  20985. fromJSON( json ) {
  20986. super.fromJSON( json );
  20987. this.v1.fromArray( json.v1 );
  20988. this.v2.fromArray( json.v2 );
  20989. return this;
  20990. }
  20991. }
  20992. class LineCurve3 extends Curve {
  20993. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  20994. super();
  20995. this.isLineCurve3 = true;
  20996. this.type = 'LineCurve3';
  20997. this.v1 = v1;
  20998. this.v2 = v2;
  20999. }
  21000. getPoint( t, optionalTarget = new Vector3() ) {
  21001. const point = optionalTarget;
  21002. if ( t === 1 ) {
  21003. point.copy( this.v2 );
  21004. } else {
  21005. point.copy( this.v2 ).sub( this.v1 );
  21006. point.multiplyScalar( t ).add( this.v1 );
  21007. }
  21008. return point;
  21009. }
  21010. // Line curve is linear, so we can overwrite default getPointAt
  21011. getPointAt( u, optionalTarget ) {
  21012. return this.getPoint( u, optionalTarget );
  21013. }
  21014. getTangent( t, optionalTarget = new Vector3() ) {
  21015. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21016. }
  21017. getTangentAt( u, optionalTarget ) {
  21018. return this.getTangent( u, optionalTarget );
  21019. }
  21020. copy( source ) {
  21021. super.copy( source );
  21022. this.v1.copy( source.v1 );
  21023. this.v2.copy( source.v2 );
  21024. return this;
  21025. }
  21026. toJSON() {
  21027. const data = super.toJSON();
  21028. data.v1 = this.v1.toArray();
  21029. data.v2 = this.v2.toArray();
  21030. return data;
  21031. }
  21032. fromJSON( json ) {
  21033. super.fromJSON( json );
  21034. this.v1.fromArray( json.v1 );
  21035. this.v2.fromArray( json.v2 );
  21036. return this;
  21037. }
  21038. }
  21039. class QuadraticBezierCurve extends Curve {
  21040. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21041. super();
  21042. this.isQuadraticBezierCurve = true;
  21043. this.type = 'QuadraticBezierCurve';
  21044. this.v0 = v0;
  21045. this.v1 = v1;
  21046. this.v2 = v2;
  21047. }
  21048. getPoint( t, optionalTarget = new Vector2() ) {
  21049. const point = optionalTarget;
  21050. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21051. point.set(
  21052. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21053. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21054. );
  21055. return point;
  21056. }
  21057. copy( source ) {
  21058. super.copy( source );
  21059. this.v0.copy( source.v0 );
  21060. this.v1.copy( source.v1 );
  21061. this.v2.copy( source.v2 );
  21062. return this;
  21063. }
  21064. toJSON() {
  21065. const data = super.toJSON();
  21066. data.v0 = this.v0.toArray();
  21067. data.v1 = this.v1.toArray();
  21068. data.v2 = this.v2.toArray();
  21069. return data;
  21070. }
  21071. fromJSON( json ) {
  21072. super.fromJSON( json );
  21073. this.v0.fromArray( json.v0 );
  21074. this.v1.fromArray( json.v1 );
  21075. this.v2.fromArray( json.v2 );
  21076. return this;
  21077. }
  21078. }
  21079. class QuadraticBezierCurve3 extends Curve {
  21080. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21081. super();
  21082. this.isQuadraticBezierCurve3 = true;
  21083. this.type = 'QuadraticBezierCurve3';
  21084. this.v0 = v0;
  21085. this.v1 = v1;
  21086. this.v2 = v2;
  21087. }
  21088. getPoint( t, optionalTarget = new Vector3() ) {
  21089. const point = optionalTarget;
  21090. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21091. point.set(
  21092. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21093. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21094. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21095. );
  21096. return point;
  21097. }
  21098. copy( source ) {
  21099. super.copy( source );
  21100. this.v0.copy( source.v0 );
  21101. this.v1.copy( source.v1 );
  21102. this.v2.copy( source.v2 );
  21103. return this;
  21104. }
  21105. toJSON() {
  21106. const data = super.toJSON();
  21107. data.v0 = this.v0.toArray();
  21108. data.v1 = this.v1.toArray();
  21109. data.v2 = this.v2.toArray();
  21110. return data;
  21111. }
  21112. fromJSON( json ) {
  21113. super.fromJSON( json );
  21114. this.v0.fromArray( json.v0 );
  21115. this.v1.fromArray( json.v1 );
  21116. this.v2.fromArray( json.v2 );
  21117. return this;
  21118. }
  21119. }
  21120. class SplineCurve extends Curve {
  21121. constructor( points = [] ) {
  21122. super();
  21123. this.isSplineCurve = true;
  21124. this.type = 'SplineCurve';
  21125. this.points = points;
  21126. }
  21127. getPoint( t, optionalTarget = new Vector2() ) {
  21128. const point = optionalTarget;
  21129. const points = this.points;
  21130. const p = ( points.length - 1 ) * t;
  21131. const intPoint = Math.floor( p );
  21132. const weight = p - intPoint;
  21133. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21134. const p1 = points[ intPoint ];
  21135. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21136. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21137. point.set(
  21138. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21139. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21140. );
  21141. return point;
  21142. }
  21143. copy( source ) {
  21144. super.copy( source );
  21145. this.points = [];
  21146. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21147. const point = source.points[ i ];
  21148. this.points.push( point.clone() );
  21149. }
  21150. return this;
  21151. }
  21152. toJSON() {
  21153. const data = super.toJSON();
  21154. data.points = [];
  21155. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21156. const point = this.points[ i ];
  21157. data.points.push( point.toArray() );
  21158. }
  21159. return data;
  21160. }
  21161. fromJSON( json ) {
  21162. super.fromJSON( json );
  21163. this.points = [];
  21164. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21165. const point = json.points[ i ];
  21166. this.points.push( new Vector2().fromArray( point ) );
  21167. }
  21168. return this;
  21169. }
  21170. }
  21171. var Curves = /*#__PURE__*/Object.freeze({
  21172. __proto__: null,
  21173. ArcCurve: ArcCurve,
  21174. CatmullRomCurve3: CatmullRomCurve3,
  21175. CubicBezierCurve: CubicBezierCurve,
  21176. CubicBezierCurve3: CubicBezierCurve3,
  21177. EllipseCurve: EllipseCurve,
  21178. LineCurve: LineCurve,
  21179. LineCurve3: LineCurve3,
  21180. QuadraticBezierCurve: QuadraticBezierCurve,
  21181. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21182. SplineCurve: SplineCurve
  21183. });
  21184. /**************************************************************
  21185. * Curved Path - a curve path is simply a array of connected
  21186. * curves, but retains the api of a curve
  21187. **************************************************************/
  21188. class CurvePath extends Curve {
  21189. constructor() {
  21190. super();
  21191. this.type = 'CurvePath';
  21192. this.curves = [];
  21193. this.autoClose = false; // Automatically closes the path
  21194. }
  21195. add( curve ) {
  21196. this.curves.push( curve );
  21197. }
  21198. closePath() {
  21199. // Add a line curve if start and end of lines are not connected
  21200. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21201. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21202. if ( ! startPoint.equals( endPoint ) ) {
  21203. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  21204. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  21205. }
  21206. return this;
  21207. }
  21208. // To get accurate point with reference to
  21209. // entire path distance at time t,
  21210. // following has to be done:
  21211. // 1. Length of each sub path have to be known
  21212. // 2. Locate and identify type of curve
  21213. // 3. Get t for the curve
  21214. // 4. Return curve.getPointAt(t')
  21215. getPoint( t, optionalTarget ) {
  21216. const d = t * this.getLength();
  21217. const curveLengths = this.getCurveLengths();
  21218. let i = 0;
  21219. // To think about boundaries points.
  21220. while ( i < curveLengths.length ) {
  21221. if ( curveLengths[ i ] >= d ) {
  21222. const diff = curveLengths[ i ] - d;
  21223. const curve = this.curves[ i ];
  21224. const segmentLength = curve.getLength();
  21225. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21226. return curve.getPointAt( u, optionalTarget );
  21227. }
  21228. i ++;
  21229. }
  21230. return null;
  21231. // loop where sum != 0, sum > d , sum+1 <d
  21232. }
  21233. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21234. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21235. // getPoint() depends on getLength
  21236. getLength() {
  21237. const lens = this.getCurveLengths();
  21238. return lens[ lens.length - 1 ];
  21239. }
  21240. // cacheLengths must be recalculated.
  21241. updateArcLengths() {
  21242. this.needsUpdate = true;
  21243. this.cacheLengths = null;
  21244. this.getCurveLengths();
  21245. }
  21246. // Compute lengths and cache them
  21247. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21248. getCurveLengths() {
  21249. // We use cache values if curves and cache array are same length
  21250. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21251. return this.cacheLengths;
  21252. }
  21253. // Get length of sub-curve
  21254. // Push sums into cached array
  21255. const lengths = [];
  21256. let sums = 0;
  21257. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21258. sums += this.curves[ i ].getLength();
  21259. lengths.push( sums );
  21260. }
  21261. this.cacheLengths = lengths;
  21262. return lengths;
  21263. }
  21264. getSpacedPoints( divisions = 40 ) {
  21265. const points = [];
  21266. for ( let i = 0; i <= divisions; i ++ ) {
  21267. points.push( this.getPoint( i / divisions ) );
  21268. }
  21269. if ( this.autoClose ) {
  21270. points.push( points[ 0 ] );
  21271. }
  21272. return points;
  21273. }
  21274. getPoints( divisions = 12 ) {
  21275. const points = [];
  21276. let last;
  21277. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21278. const curve = curves[ i ];
  21279. const resolution = curve.isEllipseCurve ? divisions * 2
  21280. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  21281. : curve.isSplineCurve ? divisions * curve.points.length
  21282. : divisions;
  21283. const pts = curve.getPoints( resolution );
  21284. for ( let j = 0; j < pts.length; j ++ ) {
  21285. const point = pts[ j ];
  21286. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21287. points.push( point );
  21288. last = point;
  21289. }
  21290. }
  21291. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21292. points.push( points[ 0 ] );
  21293. }
  21294. return points;
  21295. }
  21296. copy( source ) {
  21297. super.copy( source );
  21298. this.curves = [];
  21299. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21300. const curve = source.curves[ i ];
  21301. this.curves.push( curve.clone() );
  21302. }
  21303. this.autoClose = source.autoClose;
  21304. return this;
  21305. }
  21306. toJSON() {
  21307. const data = super.toJSON();
  21308. data.autoClose = this.autoClose;
  21309. data.curves = [];
  21310. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21311. const curve = this.curves[ i ];
  21312. data.curves.push( curve.toJSON() );
  21313. }
  21314. return data;
  21315. }
  21316. fromJSON( json ) {
  21317. super.fromJSON( json );
  21318. this.autoClose = json.autoClose;
  21319. this.curves = [];
  21320. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21321. const curve = json.curves[ i ];
  21322. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21323. }
  21324. return this;
  21325. }
  21326. }
  21327. class Path extends CurvePath {
  21328. constructor( points ) {
  21329. super();
  21330. this.type = 'Path';
  21331. this.currentPoint = new Vector2();
  21332. if ( points ) {
  21333. this.setFromPoints( points );
  21334. }
  21335. }
  21336. setFromPoints( points ) {
  21337. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21338. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21339. this.lineTo( points[ i ].x, points[ i ].y );
  21340. }
  21341. return this;
  21342. }
  21343. moveTo( x, y ) {
  21344. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21345. return this;
  21346. }
  21347. lineTo( x, y ) {
  21348. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21349. this.curves.push( curve );
  21350. this.currentPoint.set( x, y );
  21351. return this;
  21352. }
  21353. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21354. const curve = new QuadraticBezierCurve(
  21355. this.currentPoint.clone(),
  21356. new Vector2( aCPx, aCPy ),
  21357. new Vector2( aX, aY )
  21358. );
  21359. this.curves.push( curve );
  21360. this.currentPoint.set( aX, aY );
  21361. return this;
  21362. }
  21363. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21364. const curve = new CubicBezierCurve(
  21365. this.currentPoint.clone(),
  21366. new Vector2( aCP1x, aCP1y ),
  21367. new Vector2( aCP2x, aCP2y ),
  21368. new Vector2( aX, aY )
  21369. );
  21370. this.curves.push( curve );
  21371. this.currentPoint.set( aX, aY );
  21372. return this;
  21373. }
  21374. splineThru( pts /*Array of Vector*/ ) {
  21375. const npts = [ this.currentPoint.clone() ].concat( pts );
  21376. const curve = new SplineCurve( npts );
  21377. this.curves.push( curve );
  21378. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21379. return this;
  21380. }
  21381. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21382. const x0 = this.currentPoint.x;
  21383. const y0 = this.currentPoint.y;
  21384. this.absarc( aX + x0, aY + y0, aRadius,
  21385. aStartAngle, aEndAngle, aClockwise );
  21386. return this;
  21387. }
  21388. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21389. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21390. return this;
  21391. }
  21392. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21393. const x0 = this.currentPoint.x;
  21394. const y0 = this.currentPoint.y;
  21395. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21396. return this;
  21397. }
  21398. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21399. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21400. if ( this.curves.length > 0 ) {
  21401. // if a previous curve is present, attempt to join
  21402. const firstPoint = curve.getPoint( 0 );
  21403. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21404. this.lineTo( firstPoint.x, firstPoint.y );
  21405. }
  21406. }
  21407. this.curves.push( curve );
  21408. const lastPoint = curve.getPoint( 1 );
  21409. this.currentPoint.copy( lastPoint );
  21410. return this;
  21411. }
  21412. copy( source ) {
  21413. super.copy( source );
  21414. this.currentPoint.copy( source.currentPoint );
  21415. return this;
  21416. }
  21417. toJSON() {
  21418. const data = super.toJSON();
  21419. data.currentPoint = this.currentPoint.toArray();
  21420. return data;
  21421. }
  21422. fromJSON( json ) {
  21423. super.fromJSON( json );
  21424. this.currentPoint.fromArray( json.currentPoint );
  21425. return this;
  21426. }
  21427. }
  21428. class LatheGeometry extends BufferGeometry {
  21429. 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 ) {
  21430. super();
  21431. this.type = 'LatheGeometry';
  21432. this.parameters = {
  21433. points: points,
  21434. segments: segments,
  21435. phiStart: phiStart,
  21436. phiLength: phiLength
  21437. };
  21438. segments = Math.floor( segments );
  21439. // clamp phiLength so it's in range of [ 0, 2PI ]
  21440. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21441. // buffers
  21442. const indices = [];
  21443. const vertices = [];
  21444. const uvs = [];
  21445. const initNormals = [];
  21446. const normals = [];
  21447. // helper variables
  21448. const inverseSegments = 1.0 / segments;
  21449. const vertex = new Vector3();
  21450. const uv = new Vector2();
  21451. const normal = new Vector3();
  21452. const curNormal = new Vector3();
  21453. const prevNormal = new Vector3();
  21454. let dx = 0;
  21455. let dy = 0;
  21456. // pre-compute normals for initial "meridian"
  21457. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21458. switch ( j ) {
  21459. case 0: // special handling for 1st vertex on path
  21460. dx = points[ j + 1 ].x - points[ j ].x;
  21461. dy = points[ j + 1 ].y - points[ j ].y;
  21462. normal.x = dy * 1.0;
  21463. normal.y = - dx;
  21464. normal.z = dy * 0.0;
  21465. prevNormal.copy( normal );
  21466. normal.normalize();
  21467. initNormals.push( normal.x, normal.y, normal.z );
  21468. break;
  21469. case ( points.length - 1 ): // special handling for last Vertex on path
  21470. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  21471. break;
  21472. default: // default handling for all vertices in between
  21473. dx = points[ j + 1 ].x - points[ j ].x;
  21474. dy = points[ j + 1 ].y - points[ j ].y;
  21475. normal.x = dy * 1.0;
  21476. normal.y = - dx;
  21477. normal.z = dy * 0.0;
  21478. curNormal.copy( normal );
  21479. normal.x += prevNormal.x;
  21480. normal.y += prevNormal.y;
  21481. normal.z += prevNormal.z;
  21482. normal.normalize();
  21483. initNormals.push( normal.x, normal.y, normal.z );
  21484. prevNormal.copy( curNormal );
  21485. }
  21486. }
  21487. // generate vertices, uvs and normals
  21488. for ( let i = 0; i <= segments; i ++ ) {
  21489. const phi = phiStart + i * inverseSegments * phiLength;
  21490. const sin = Math.sin( phi );
  21491. const cos = Math.cos( phi );
  21492. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21493. // vertex
  21494. vertex.x = points[ j ].x * sin;
  21495. vertex.y = points[ j ].y;
  21496. vertex.z = points[ j ].x * cos;
  21497. vertices.push( vertex.x, vertex.y, vertex.z );
  21498. // uv
  21499. uv.x = i / segments;
  21500. uv.y = j / ( points.length - 1 );
  21501. uvs.push( uv.x, uv.y );
  21502. // normal
  21503. const x = initNormals[ 3 * j + 0 ] * sin;
  21504. const y = initNormals[ 3 * j + 1 ];
  21505. const z = initNormals[ 3 * j + 0 ] * cos;
  21506. normals.push( x, y, z );
  21507. }
  21508. }
  21509. // indices
  21510. for ( let i = 0; i < segments; i ++ ) {
  21511. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  21512. const base = j + i * points.length;
  21513. const a = base;
  21514. const b = base + points.length;
  21515. const c = base + points.length + 1;
  21516. const d = base + 1;
  21517. // faces
  21518. indices.push( a, b, d );
  21519. indices.push( c, d, b );
  21520. }
  21521. }
  21522. // build geometry
  21523. this.setIndex( indices );
  21524. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21525. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21526. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21527. }
  21528. copy( source ) {
  21529. super.copy( source );
  21530. this.parameters = Object.assign( {}, source.parameters );
  21531. return this;
  21532. }
  21533. static fromJSON( data ) {
  21534. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  21535. }
  21536. }
  21537. class CapsuleGeometry extends LatheGeometry {
  21538. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  21539. const path = new Path();
  21540. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  21541. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  21542. super( path.getPoints( capSegments ), radialSegments );
  21543. this.type = 'CapsuleGeometry';
  21544. this.parameters = {
  21545. radius: radius,
  21546. length: length,
  21547. capSegments: capSegments,
  21548. radialSegments: radialSegments,
  21549. };
  21550. }
  21551. static fromJSON( data ) {
  21552. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  21553. }
  21554. }
  21555. class CircleGeometry extends BufferGeometry {
  21556. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21557. super();
  21558. this.type = 'CircleGeometry';
  21559. this.parameters = {
  21560. radius: radius,
  21561. segments: segments,
  21562. thetaStart: thetaStart,
  21563. thetaLength: thetaLength
  21564. };
  21565. segments = Math.max( 3, segments );
  21566. // buffers
  21567. const indices = [];
  21568. const vertices = [];
  21569. const normals = [];
  21570. const uvs = [];
  21571. // helper variables
  21572. const vertex = new Vector3();
  21573. const uv = new Vector2();
  21574. // center point
  21575. vertices.push( 0, 0, 0 );
  21576. normals.push( 0, 0, 1 );
  21577. uvs.push( 0.5, 0.5 );
  21578. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21579. const segment = thetaStart + s / segments * thetaLength;
  21580. // vertex
  21581. vertex.x = radius * Math.cos( segment );
  21582. vertex.y = radius * Math.sin( segment );
  21583. vertices.push( vertex.x, vertex.y, vertex.z );
  21584. // normal
  21585. normals.push( 0, 0, 1 );
  21586. // uvs
  21587. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21588. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21589. uvs.push( uv.x, uv.y );
  21590. }
  21591. // indices
  21592. for ( let i = 1; i <= segments; i ++ ) {
  21593. indices.push( i, i + 1, 0 );
  21594. }
  21595. // build geometry
  21596. this.setIndex( indices );
  21597. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21598. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21599. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21600. }
  21601. copy( source ) {
  21602. super.copy( source );
  21603. this.parameters = Object.assign( {}, source.parameters );
  21604. return this;
  21605. }
  21606. static fromJSON( data ) {
  21607. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21608. }
  21609. }
  21610. class CylinderGeometry extends BufferGeometry {
  21611. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21612. super();
  21613. this.type = 'CylinderGeometry';
  21614. this.parameters = {
  21615. radiusTop: radiusTop,
  21616. radiusBottom: radiusBottom,
  21617. height: height,
  21618. radialSegments: radialSegments,
  21619. heightSegments: heightSegments,
  21620. openEnded: openEnded,
  21621. thetaStart: thetaStart,
  21622. thetaLength: thetaLength
  21623. };
  21624. const scope = this;
  21625. radialSegments = Math.floor( radialSegments );
  21626. heightSegments = Math.floor( heightSegments );
  21627. // buffers
  21628. const indices = [];
  21629. const vertices = [];
  21630. const normals = [];
  21631. const uvs = [];
  21632. // helper variables
  21633. let index = 0;
  21634. const indexArray = [];
  21635. const halfHeight = height / 2;
  21636. let groupStart = 0;
  21637. // generate geometry
  21638. generateTorso();
  21639. if ( openEnded === false ) {
  21640. if ( radiusTop > 0 ) generateCap( true );
  21641. if ( radiusBottom > 0 ) generateCap( false );
  21642. }
  21643. // build geometry
  21644. this.setIndex( indices );
  21645. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21646. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21647. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21648. function generateTorso() {
  21649. const normal = new Vector3();
  21650. const vertex = new Vector3();
  21651. let groupCount = 0;
  21652. // this will be used to calculate the normal
  21653. const slope = ( radiusBottom - radiusTop ) / height;
  21654. // generate vertices, normals and uvs
  21655. for ( let y = 0; y <= heightSegments; y ++ ) {
  21656. const indexRow = [];
  21657. const v = y / heightSegments;
  21658. // calculate the radius of the current row
  21659. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21660. for ( let x = 0; x <= radialSegments; x ++ ) {
  21661. const u = x / radialSegments;
  21662. const theta = u * thetaLength + thetaStart;
  21663. const sinTheta = Math.sin( theta );
  21664. const cosTheta = Math.cos( theta );
  21665. // vertex
  21666. vertex.x = radius * sinTheta;
  21667. vertex.y = - v * height + halfHeight;
  21668. vertex.z = radius * cosTheta;
  21669. vertices.push( vertex.x, vertex.y, vertex.z );
  21670. // normal
  21671. normal.set( sinTheta, slope, cosTheta ).normalize();
  21672. normals.push( normal.x, normal.y, normal.z );
  21673. // uv
  21674. uvs.push( u, 1 - v );
  21675. // save index of vertex in respective row
  21676. indexRow.push( index ++ );
  21677. }
  21678. // now save vertices of the row in our index array
  21679. indexArray.push( indexRow );
  21680. }
  21681. // generate indices
  21682. for ( let x = 0; x < radialSegments; x ++ ) {
  21683. for ( let y = 0; y < heightSegments; y ++ ) {
  21684. // we use the index array to access the correct indices
  21685. const a = indexArray[ y ][ x ];
  21686. const b = indexArray[ y + 1 ][ x ];
  21687. const c = indexArray[ y + 1 ][ x + 1 ];
  21688. const d = indexArray[ y ][ x + 1 ];
  21689. // faces
  21690. indices.push( a, b, d );
  21691. indices.push( b, c, d );
  21692. // update group counter
  21693. groupCount += 6;
  21694. }
  21695. }
  21696. // add a group to the geometry. this will ensure multi material support
  21697. scope.addGroup( groupStart, groupCount, 0 );
  21698. // calculate new start value for groups
  21699. groupStart += groupCount;
  21700. }
  21701. function generateCap( top ) {
  21702. // save the index of the first center vertex
  21703. const centerIndexStart = index;
  21704. const uv = new Vector2();
  21705. const vertex = new Vector3();
  21706. let groupCount = 0;
  21707. const radius = ( top === true ) ? radiusTop : radiusBottom;
  21708. const sign = ( top === true ) ? 1 : - 1;
  21709. // first we generate the center vertex data of the cap.
  21710. // because the geometry needs one set of uvs per face,
  21711. // we must generate a center vertex per face/segment
  21712. for ( let x = 1; x <= radialSegments; x ++ ) {
  21713. // vertex
  21714. vertices.push( 0, halfHeight * sign, 0 );
  21715. // normal
  21716. normals.push( 0, sign, 0 );
  21717. // uv
  21718. uvs.push( 0.5, 0.5 );
  21719. // increase index
  21720. index ++;
  21721. }
  21722. // save the index of the last center vertex
  21723. const centerIndexEnd = index;
  21724. // now we generate the surrounding vertices, normals and uvs
  21725. for ( let x = 0; x <= radialSegments; x ++ ) {
  21726. const u = x / radialSegments;
  21727. const theta = u * thetaLength + thetaStart;
  21728. const cosTheta = Math.cos( theta );
  21729. const sinTheta = Math.sin( theta );
  21730. // vertex
  21731. vertex.x = radius * sinTheta;
  21732. vertex.y = halfHeight * sign;
  21733. vertex.z = radius * cosTheta;
  21734. vertices.push( vertex.x, vertex.y, vertex.z );
  21735. // normal
  21736. normals.push( 0, sign, 0 );
  21737. // uv
  21738. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21739. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21740. uvs.push( uv.x, uv.y );
  21741. // increase index
  21742. index ++;
  21743. }
  21744. // generate indices
  21745. for ( let x = 0; x < radialSegments; x ++ ) {
  21746. const c = centerIndexStart + x;
  21747. const i = centerIndexEnd + x;
  21748. if ( top === true ) {
  21749. // face top
  21750. indices.push( i, i + 1, c );
  21751. } else {
  21752. // face bottom
  21753. indices.push( i + 1, i, c );
  21754. }
  21755. groupCount += 3;
  21756. }
  21757. // add a group to the geometry. this will ensure multi material support
  21758. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21759. // calculate new start value for groups
  21760. groupStart += groupCount;
  21761. }
  21762. }
  21763. copy( source ) {
  21764. super.copy( source );
  21765. this.parameters = Object.assign( {}, source.parameters );
  21766. return this;
  21767. }
  21768. static fromJSON( data ) {
  21769. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21770. }
  21771. }
  21772. class ConeGeometry extends CylinderGeometry {
  21773. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21774. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21775. this.type = 'ConeGeometry';
  21776. this.parameters = {
  21777. radius: radius,
  21778. height: height,
  21779. radialSegments: radialSegments,
  21780. heightSegments: heightSegments,
  21781. openEnded: openEnded,
  21782. thetaStart: thetaStart,
  21783. thetaLength: thetaLength
  21784. };
  21785. }
  21786. static fromJSON( data ) {
  21787. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21788. }
  21789. }
  21790. class PolyhedronGeometry extends BufferGeometry {
  21791. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  21792. super();
  21793. this.type = 'PolyhedronGeometry';
  21794. this.parameters = {
  21795. vertices: vertices,
  21796. indices: indices,
  21797. radius: radius,
  21798. detail: detail
  21799. };
  21800. // default buffer data
  21801. const vertexBuffer = [];
  21802. const uvBuffer = [];
  21803. // the subdivision creates the vertex buffer data
  21804. subdivide( detail );
  21805. // all vertices should lie on a conceptual sphere with a given radius
  21806. applyRadius( radius );
  21807. // finally, create the uv data
  21808. generateUVs();
  21809. // build non-indexed geometry
  21810. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  21811. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  21812. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  21813. if ( detail === 0 ) {
  21814. this.computeVertexNormals(); // flat normals
  21815. } else {
  21816. this.normalizeNormals(); // smooth normals
  21817. }
  21818. // helper functions
  21819. function subdivide( detail ) {
  21820. const a = new Vector3();
  21821. const b = new Vector3();
  21822. const c = new Vector3();
  21823. // iterate over all faces and apply a subdivision with the given detail value
  21824. for ( let i = 0; i < indices.length; i += 3 ) {
  21825. // get the vertices of the face
  21826. getVertexByIndex( indices[ i + 0 ], a );
  21827. getVertexByIndex( indices[ i + 1 ], b );
  21828. getVertexByIndex( indices[ i + 2 ], c );
  21829. // perform subdivision
  21830. subdivideFace( a, b, c, detail );
  21831. }
  21832. }
  21833. function subdivideFace( a, b, c, detail ) {
  21834. const cols = detail + 1;
  21835. // we use this multidimensional array as a data structure for creating the subdivision
  21836. const v = [];
  21837. // construct all of the vertices for this subdivision
  21838. for ( let i = 0; i <= cols; i ++ ) {
  21839. v[ i ] = [];
  21840. const aj = a.clone().lerp( c, i / cols );
  21841. const bj = b.clone().lerp( c, i / cols );
  21842. const rows = cols - i;
  21843. for ( let j = 0; j <= rows; j ++ ) {
  21844. if ( j === 0 && i === cols ) {
  21845. v[ i ][ j ] = aj;
  21846. } else {
  21847. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  21848. }
  21849. }
  21850. }
  21851. // construct all of the faces
  21852. for ( let i = 0; i < cols; i ++ ) {
  21853. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  21854. const k = Math.floor( j / 2 );
  21855. if ( j % 2 === 0 ) {
  21856. pushVertex( v[ i ][ k + 1 ] );
  21857. pushVertex( v[ i + 1 ][ k ] );
  21858. pushVertex( v[ i ][ k ] );
  21859. } else {
  21860. pushVertex( v[ i ][ k + 1 ] );
  21861. pushVertex( v[ i + 1 ][ k + 1 ] );
  21862. pushVertex( v[ i + 1 ][ k ] );
  21863. }
  21864. }
  21865. }
  21866. }
  21867. function applyRadius( radius ) {
  21868. const vertex = new Vector3();
  21869. // iterate over the entire buffer and apply the radius to each vertex
  21870. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  21871. vertex.x = vertexBuffer[ i + 0 ];
  21872. vertex.y = vertexBuffer[ i + 1 ];
  21873. vertex.z = vertexBuffer[ i + 2 ];
  21874. vertex.normalize().multiplyScalar( radius );
  21875. vertexBuffer[ i + 0 ] = vertex.x;
  21876. vertexBuffer[ i + 1 ] = vertex.y;
  21877. vertexBuffer[ i + 2 ] = vertex.z;
  21878. }
  21879. }
  21880. function generateUVs() {
  21881. const vertex = new Vector3();
  21882. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  21883. vertex.x = vertexBuffer[ i + 0 ];
  21884. vertex.y = vertexBuffer[ i + 1 ];
  21885. vertex.z = vertexBuffer[ i + 2 ];
  21886. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  21887. const v = inclination( vertex ) / Math.PI + 0.5;
  21888. uvBuffer.push( u, 1 - v );
  21889. }
  21890. correctUVs();
  21891. correctSeam();
  21892. }
  21893. function correctSeam() {
  21894. // handle case when face straddles the seam, see #3269
  21895. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  21896. // uv data of a single face
  21897. const x0 = uvBuffer[ i + 0 ];
  21898. const x1 = uvBuffer[ i + 2 ];
  21899. const x2 = uvBuffer[ i + 4 ];
  21900. const max = Math.max( x0, x1, x2 );
  21901. const min = Math.min( x0, x1, x2 );
  21902. // 0.9 is somewhat arbitrary
  21903. if ( max > 0.9 && min < 0.1 ) {
  21904. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  21905. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  21906. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  21907. }
  21908. }
  21909. }
  21910. function pushVertex( vertex ) {
  21911. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  21912. }
  21913. function getVertexByIndex( index, vertex ) {
  21914. const stride = index * 3;
  21915. vertex.x = vertices[ stride + 0 ];
  21916. vertex.y = vertices[ stride + 1 ];
  21917. vertex.z = vertices[ stride + 2 ];
  21918. }
  21919. function correctUVs() {
  21920. const a = new Vector3();
  21921. const b = new Vector3();
  21922. const c = new Vector3();
  21923. const centroid = new Vector3();
  21924. const uvA = new Vector2();
  21925. const uvB = new Vector2();
  21926. const uvC = new Vector2();
  21927. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  21928. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  21929. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  21930. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  21931. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  21932. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  21933. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  21934. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  21935. const azi = azimuth( centroid );
  21936. correctUV( uvA, j + 0, a, azi );
  21937. correctUV( uvB, j + 2, b, azi );
  21938. correctUV( uvC, j + 4, c, azi );
  21939. }
  21940. }
  21941. function correctUV( uv, stride, vector, azimuth ) {
  21942. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21943. uvBuffer[ stride ] = uv.x - 1;
  21944. }
  21945. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21946. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21947. }
  21948. }
  21949. // Angle around the Y axis, counter-clockwise when looking from above.
  21950. function azimuth( vector ) {
  21951. return Math.atan2( vector.z, - vector.x );
  21952. }
  21953. // Angle above the XZ plane.
  21954. function inclination( vector ) {
  21955. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21956. }
  21957. }
  21958. copy( source ) {
  21959. super.copy( source );
  21960. this.parameters = Object.assign( {}, source.parameters );
  21961. return this;
  21962. }
  21963. static fromJSON( data ) {
  21964. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  21965. }
  21966. }
  21967. class DodecahedronGeometry extends PolyhedronGeometry {
  21968. constructor( radius = 1, detail = 0 ) {
  21969. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21970. const r = 1 / t;
  21971. const vertices = [
  21972. // (±1, ±1, ±1)
  21973. - 1, - 1, - 1, - 1, - 1, 1,
  21974. - 1, 1, - 1, - 1, 1, 1,
  21975. 1, - 1, - 1, 1, - 1, 1,
  21976. 1, 1, - 1, 1, 1, 1,
  21977. // (0, ±1/φ, ±φ)
  21978. 0, - r, - t, 0, - r, t,
  21979. 0, r, - t, 0, r, t,
  21980. // (±1/φ, ±φ, 0)
  21981. - r, - t, 0, - r, t, 0,
  21982. r, - t, 0, r, t, 0,
  21983. // (±φ, 0, ±1/φ)
  21984. - t, 0, - r, t, 0, - r,
  21985. - t, 0, r, t, 0, r
  21986. ];
  21987. const indices = [
  21988. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21989. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  21990. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  21991. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  21992. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  21993. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  21994. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  21995. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  21996. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  21997. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  21998. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  21999. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22000. ];
  22001. super( vertices, indices, radius, detail );
  22002. this.type = 'DodecahedronGeometry';
  22003. this.parameters = {
  22004. radius: radius,
  22005. detail: detail
  22006. };
  22007. }
  22008. static fromJSON( data ) {
  22009. return new DodecahedronGeometry( data.radius, data.detail );
  22010. }
  22011. }
  22012. const _v0 = /*@__PURE__*/ new Vector3();
  22013. const _v1$1 = /*@__PURE__*/ new Vector3();
  22014. const _normal = /*@__PURE__*/ new Vector3();
  22015. const _triangle = /*@__PURE__*/ new Triangle();
  22016. class EdgesGeometry extends BufferGeometry {
  22017. constructor( geometry = null, thresholdAngle = 1 ) {
  22018. super();
  22019. this.type = 'EdgesGeometry';
  22020. this.parameters = {
  22021. geometry: geometry,
  22022. thresholdAngle: thresholdAngle
  22023. };
  22024. if ( geometry !== null ) {
  22025. const precisionPoints = 4;
  22026. const precision = Math.pow( 10, precisionPoints );
  22027. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22028. const indexAttr = geometry.getIndex();
  22029. const positionAttr = geometry.getAttribute( 'position' );
  22030. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22031. const indexArr = [ 0, 0, 0 ];
  22032. const vertKeys = [ 'a', 'b', 'c' ];
  22033. const hashes = new Array( 3 );
  22034. const edgeData = {};
  22035. const vertices = [];
  22036. for ( let i = 0; i < indexCount; i += 3 ) {
  22037. if ( indexAttr ) {
  22038. indexArr[ 0 ] = indexAttr.getX( i );
  22039. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22040. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22041. } else {
  22042. indexArr[ 0 ] = i;
  22043. indexArr[ 1 ] = i + 1;
  22044. indexArr[ 2 ] = i + 2;
  22045. }
  22046. const { a, b, c } = _triangle;
  22047. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22048. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22049. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22050. _triangle.getNormal( _normal );
  22051. // create hashes for the edge from the vertices
  22052. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22053. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22054. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22055. // skip degenerate triangles
  22056. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22057. continue;
  22058. }
  22059. // iterate over every edge
  22060. for ( let j = 0; j < 3; j ++ ) {
  22061. // get the first and next vertex making up the edge
  22062. const jNext = ( j + 1 ) % 3;
  22063. const vecHash0 = hashes[ j ];
  22064. const vecHash1 = hashes[ jNext ];
  22065. const v0 = _triangle[ vertKeys[ j ] ];
  22066. const v1 = _triangle[ vertKeys[ jNext ] ];
  22067. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22068. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22069. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22070. // if we found a sibling edge add it into the vertex array if
  22071. // it meets the angle threshold and delete the edge from the map.
  22072. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22073. vertices.push( v0.x, v0.y, v0.z );
  22074. vertices.push( v1.x, v1.y, v1.z );
  22075. }
  22076. edgeData[ reverseHash ] = null;
  22077. } else if ( ! ( hash in edgeData ) ) {
  22078. // if we've already got an edge here then skip adding a new one
  22079. edgeData[ hash ] = {
  22080. index0: indexArr[ j ],
  22081. index1: indexArr[ jNext ],
  22082. normal: _normal.clone(),
  22083. };
  22084. }
  22085. }
  22086. }
  22087. // iterate over all remaining, unmatched edges and add them to the vertex array
  22088. for ( const key in edgeData ) {
  22089. if ( edgeData[ key ] ) {
  22090. const { index0, index1 } = edgeData[ key ];
  22091. _v0.fromBufferAttribute( positionAttr, index0 );
  22092. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22093. vertices.push( _v0.x, _v0.y, _v0.z );
  22094. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22095. }
  22096. }
  22097. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22098. }
  22099. }
  22100. copy( source ) {
  22101. super.copy( source );
  22102. this.parameters = Object.assign( {}, source.parameters );
  22103. return this;
  22104. }
  22105. }
  22106. class Shape extends Path {
  22107. constructor( points ) {
  22108. super( points );
  22109. this.uuid = generateUUID();
  22110. this.type = 'Shape';
  22111. this.holes = [];
  22112. }
  22113. getPointsHoles( divisions ) {
  22114. const holesPts = [];
  22115. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22116. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22117. }
  22118. return holesPts;
  22119. }
  22120. // get points of shape and holes (keypoints based on segments parameter)
  22121. extractPoints( divisions ) {
  22122. return {
  22123. shape: this.getPoints( divisions ),
  22124. holes: this.getPointsHoles( divisions )
  22125. };
  22126. }
  22127. copy( source ) {
  22128. super.copy( source );
  22129. this.holes = [];
  22130. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22131. const hole = source.holes[ i ];
  22132. this.holes.push( hole.clone() );
  22133. }
  22134. return this;
  22135. }
  22136. toJSON() {
  22137. const data = super.toJSON();
  22138. data.uuid = this.uuid;
  22139. data.holes = [];
  22140. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22141. const hole = this.holes[ i ];
  22142. data.holes.push( hole.toJSON() );
  22143. }
  22144. return data;
  22145. }
  22146. fromJSON( json ) {
  22147. super.fromJSON( json );
  22148. this.uuid = json.uuid;
  22149. this.holes = [];
  22150. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22151. const hole = json.holes[ i ];
  22152. this.holes.push( new Path().fromJSON( hole ) );
  22153. }
  22154. return this;
  22155. }
  22156. }
  22157. /**
  22158. * Port from https://github.com/mapbox/earcut (v2.2.4)
  22159. */
  22160. const Earcut = {
  22161. triangulate: function ( data, holeIndices, dim = 2 ) {
  22162. const hasHoles = holeIndices && holeIndices.length;
  22163. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  22164. let outerNode = linkedList( data, 0, outerLen, dim, true );
  22165. const triangles = [];
  22166. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  22167. let minX, minY, maxX, maxY, x, y, invSize;
  22168. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  22169. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22170. if ( data.length > 80 * dim ) {
  22171. minX = maxX = data[ 0 ];
  22172. minY = maxY = data[ 1 ];
  22173. for ( let i = dim; i < outerLen; i += dim ) {
  22174. x = data[ i ];
  22175. y = data[ i + 1 ];
  22176. if ( x < minX ) minX = x;
  22177. if ( y < minY ) minY = y;
  22178. if ( x > maxX ) maxX = x;
  22179. if ( y > maxY ) maxY = y;
  22180. }
  22181. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22182. invSize = Math.max( maxX - minX, maxY - minY );
  22183. invSize = invSize !== 0 ? 32767 / invSize : 0;
  22184. }
  22185. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  22186. return triangles;
  22187. }
  22188. };
  22189. // create a circular doubly linked list from polygon points in the specified winding order
  22190. function linkedList( data, start, end, dim, clockwise ) {
  22191. let i, last;
  22192. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22193. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22194. } else {
  22195. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22196. }
  22197. if ( last && equals( last, last.next ) ) {
  22198. removeNode( last );
  22199. last = last.next;
  22200. }
  22201. return last;
  22202. }
  22203. // eliminate colinear or duplicate points
  22204. function filterPoints( start, end ) {
  22205. if ( ! start ) return start;
  22206. if ( ! end ) end = start;
  22207. let p = start,
  22208. again;
  22209. do {
  22210. again = false;
  22211. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22212. removeNode( p );
  22213. p = end = p.prev;
  22214. if ( p === p.next ) break;
  22215. again = true;
  22216. } else {
  22217. p = p.next;
  22218. }
  22219. } while ( again || p !== end );
  22220. return end;
  22221. }
  22222. // main ear slicing loop which triangulates a polygon (given as a linked list)
  22223. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  22224. if ( ! ear ) return;
  22225. // interlink polygon nodes in z-order
  22226. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  22227. let stop = ear,
  22228. prev, next;
  22229. // iterate through ears, slicing them one by one
  22230. while ( ear.prev !== ear.next ) {
  22231. prev = ear.prev;
  22232. next = ear.next;
  22233. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  22234. // cut off the triangle
  22235. triangles.push( prev.i / dim | 0 );
  22236. triangles.push( ear.i / dim | 0 );
  22237. triangles.push( next.i / dim | 0 );
  22238. removeNode( ear );
  22239. // skipping the next vertex leads to less sliver triangles
  22240. ear = next.next;
  22241. stop = next.next;
  22242. continue;
  22243. }
  22244. ear = next;
  22245. // if we looped through the whole remaining polygon and can't find any more ears
  22246. if ( ear === stop ) {
  22247. // try filtering points and slicing again
  22248. if ( ! pass ) {
  22249. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  22250. // if this didn't work, try curing all small self-intersections locally
  22251. } else if ( pass === 1 ) {
  22252. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  22253. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  22254. // as a last resort, try splitting the remaining polygon into two
  22255. } else if ( pass === 2 ) {
  22256. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  22257. }
  22258. break;
  22259. }
  22260. }
  22261. }
  22262. // check whether a polygon node forms a valid ear with adjacent nodes
  22263. function isEar( ear ) {
  22264. const a = ear.prev,
  22265. b = ear,
  22266. c = ear.next;
  22267. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22268. // now make sure we don't have other points inside the potential ear
  22269. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22270. // triangle bbox; min & max are calculated like this for speed
  22271. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22272. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22273. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22274. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22275. let p = c.next;
  22276. while ( p !== a ) {
  22277. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  22278. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  22279. area( p.prev, p, p.next ) >= 0 ) return false;
  22280. p = p.next;
  22281. }
  22282. return true;
  22283. }
  22284. function isEarHashed( ear, minX, minY, invSize ) {
  22285. const a = ear.prev,
  22286. b = ear,
  22287. c = ear.next;
  22288. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22289. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22290. // triangle bbox; min & max are calculated like this for speed
  22291. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22292. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22293. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22294. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22295. // z-order range for the current triangle bbox;
  22296. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  22297. maxZ = zOrder( x1, y1, minX, minY, invSize );
  22298. let p = ear.prevZ,
  22299. n = ear.nextZ;
  22300. // look for points inside the triangle in both directions
  22301. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  22302. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22303. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22304. p = p.prevZ;
  22305. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22306. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22307. n = n.nextZ;
  22308. }
  22309. // look for remaining points in decreasing z-order
  22310. while ( p && p.z >= minZ ) {
  22311. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22312. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22313. p = p.prevZ;
  22314. }
  22315. // look for remaining points in increasing z-order
  22316. while ( n && n.z <= maxZ ) {
  22317. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22318. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22319. n = n.nextZ;
  22320. }
  22321. return true;
  22322. }
  22323. // go through all polygon nodes and cure small local self-intersections
  22324. function cureLocalIntersections( start, triangles, dim ) {
  22325. let p = start;
  22326. do {
  22327. const a = p.prev,
  22328. b = p.next.next;
  22329. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  22330. triangles.push( a.i / dim | 0 );
  22331. triangles.push( p.i / dim | 0 );
  22332. triangles.push( b.i / dim | 0 );
  22333. // remove two nodes involved
  22334. removeNode( p );
  22335. removeNode( p.next );
  22336. p = start = b;
  22337. }
  22338. p = p.next;
  22339. } while ( p !== start );
  22340. return filterPoints( p );
  22341. }
  22342. // try splitting polygon into two and triangulate them independently
  22343. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  22344. // look for a valid diagonal that divides the polygon into two
  22345. let a = start;
  22346. do {
  22347. let b = a.next.next;
  22348. while ( b !== a.prev ) {
  22349. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  22350. // split the polygon in two by the diagonal
  22351. let c = splitPolygon( a, b );
  22352. // filter colinear points around the cuts
  22353. a = filterPoints( a, a.next );
  22354. c = filterPoints( c, c.next );
  22355. // run earcut on each half
  22356. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  22357. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  22358. return;
  22359. }
  22360. b = b.next;
  22361. }
  22362. a = a.next;
  22363. } while ( a !== start );
  22364. }
  22365. // link every hole into the outer loop, producing a single-ring polygon without holes
  22366. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  22367. const queue = [];
  22368. let i, len, start, end, list;
  22369. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  22370. start = holeIndices[ i ] * dim;
  22371. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  22372. list = linkedList( data, start, end, dim, false );
  22373. if ( list === list.next ) list.steiner = true;
  22374. queue.push( getLeftmost( list ) );
  22375. }
  22376. queue.sort( compareX );
  22377. // process holes from left to right
  22378. for ( i = 0; i < queue.length; i ++ ) {
  22379. outerNode = eliminateHole( queue[ i ], outerNode );
  22380. }
  22381. return outerNode;
  22382. }
  22383. function compareX( a, b ) {
  22384. return a.x - b.x;
  22385. }
  22386. // find a bridge between vertices that connects hole with an outer ring and link it
  22387. function eliminateHole( hole, outerNode ) {
  22388. const bridge = findHoleBridge( hole, outerNode );
  22389. if ( ! bridge ) {
  22390. return outerNode;
  22391. }
  22392. const bridgeReverse = splitPolygon( bridge, hole );
  22393. // filter collinear points around the cuts
  22394. filterPoints( bridgeReverse, bridgeReverse.next );
  22395. return filterPoints( bridge, bridge.next );
  22396. }
  22397. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  22398. function findHoleBridge( hole, outerNode ) {
  22399. let p = outerNode,
  22400. qx = - Infinity,
  22401. m;
  22402. const hx = hole.x, hy = hole.y;
  22403. // find a segment intersected by a ray from the hole's leftmost point to the left;
  22404. // segment's endpoint with lesser x will be potential connection point
  22405. do {
  22406. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  22407. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  22408. if ( x <= hx && x > qx ) {
  22409. qx = x;
  22410. m = p.x < p.next.x ? p : p.next;
  22411. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  22412. }
  22413. }
  22414. p = p.next;
  22415. } while ( p !== outerNode );
  22416. if ( ! m ) return null;
  22417. // look for points inside the triangle of hole point, segment intersection and endpoint;
  22418. // if there are no points found, we have a valid connection;
  22419. // otherwise choose the point of the minimum angle with the ray as connection point
  22420. const stop = m,
  22421. mx = m.x,
  22422. my = m.y;
  22423. let tanMin = Infinity, tan;
  22424. p = m;
  22425. do {
  22426. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  22427. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  22428. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  22429. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  22430. m = p;
  22431. tanMin = tan;
  22432. }
  22433. }
  22434. p = p.next;
  22435. } while ( p !== stop );
  22436. return m;
  22437. }
  22438. // whether sector in vertex m contains sector in vertex p in the same coordinates
  22439. function sectorContainsSector( m, p ) {
  22440. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  22441. }
  22442. // interlink polygon nodes in z-order
  22443. function indexCurve( start, minX, minY, invSize ) {
  22444. let p = start;
  22445. do {
  22446. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  22447. p.prevZ = p.prev;
  22448. p.nextZ = p.next;
  22449. p = p.next;
  22450. } while ( p !== start );
  22451. p.prevZ.nextZ = null;
  22452. p.prevZ = null;
  22453. sortLinked( p );
  22454. }
  22455. // Simon Tatham's linked list merge sort algorithm
  22456. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  22457. function sortLinked( list ) {
  22458. let i, p, q, e, tail, numMerges, pSize, qSize,
  22459. inSize = 1;
  22460. do {
  22461. p = list;
  22462. list = null;
  22463. tail = null;
  22464. numMerges = 0;
  22465. while ( p ) {
  22466. numMerges ++;
  22467. q = p;
  22468. pSize = 0;
  22469. for ( i = 0; i < inSize; i ++ ) {
  22470. pSize ++;
  22471. q = q.nextZ;
  22472. if ( ! q ) break;
  22473. }
  22474. qSize = inSize;
  22475. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  22476. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  22477. e = p;
  22478. p = p.nextZ;
  22479. pSize --;
  22480. } else {
  22481. e = q;
  22482. q = q.nextZ;
  22483. qSize --;
  22484. }
  22485. if ( tail ) tail.nextZ = e;
  22486. else list = e;
  22487. e.prevZ = tail;
  22488. tail = e;
  22489. }
  22490. p = q;
  22491. }
  22492. tail.nextZ = null;
  22493. inSize *= 2;
  22494. } while ( numMerges > 1 );
  22495. return list;
  22496. }
  22497. // z-order of a point given coords and inverse of the longer side of data bbox
  22498. function zOrder( x, y, minX, minY, invSize ) {
  22499. // coords are transformed into non-negative 15-bit integer range
  22500. x = ( x - minX ) * invSize | 0;
  22501. y = ( y - minY ) * invSize | 0;
  22502. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  22503. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  22504. x = ( x | ( x << 2 ) ) & 0x33333333;
  22505. x = ( x | ( x << 1 ) ) & 0x55555555;
  22506. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  22507. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  22508. y = ( y | ( y << 2 ) ) & 0x33333333;
  22509. y = ( y | ( y << 1 ) ) & 0x55555555;
  22510. return x | ( y << 1 );
  22511. }
  22512. // find the leftmost node of a polygon ring
  22513. function getLeftmost( start ) {
  22514. let p = start,
  22515. leftmost = start;
  22516. do {
  22517. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  22518. p = p.next;
  22519. } while ( p !== start );
  22520. return leftmost;
  22521. }
  22522. // check if a point lies within a convex triangle
  22523. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  22524. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  22525. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  22526. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  22527. }
  22528. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  22529. function isValidDiagonal( a, b ) {
  22530. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  22531. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  22532. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  22533. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  22534. }
  22535. // signed area of a triangle
  22536. function area( p, q, r ) {
  22537. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  22538. }
  22539. // check if two points are equal
  22540. function equals( p1, p2 ) {
  22541. return p1.x === p2.x && p1.y === p2.y;
  22542. }
  22543. // check if two segments intersect
  22544. function intersects( p1, q1, p2, q2 ) {
  22545. const o1 = sign( area( p1, q1, p2 ) );
  22546. const o2 = sign( area( p1, q1, q2 ) );
  22547. const o3 = sign( area( p2, q2, p1 ) );
  22548. const o4 = sign( area( p2, q2, q1 ) );
  22549. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  22550. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  22551. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  22552. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  22553. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  22554. return false;
  22555. }
  22556. // for collinear points p, q, r, check if point q lies on segment pr
  22557. function onSegment( p, q, r ) {
  22558. 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 );
  22559. }
  22560. function sign( num ) {
  22561. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  22562. }
  22563. // check if a polygon diagonal intersects any polygon segments
  22564. function intersectsPolygon( a, b ) {
  22565. let p = a;
  22566. do {
  22567. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  22568. intersects( p, p.next, a, b ) ) return true;
  22569. p = p.next;
  22570. } while ( p !== a );
  22571. return false;
  22572. }
  22573. // check if a polygon diagonal is locally inside the polygon
  22574. function locallyInside( a, b ) {
  22575. return area( a.prev, a, a.next ) < 0 ?
  22576. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  22577. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  22578. }
  22579. // check if the middle point of a polygon diagonal is inside the polygon
  22580. function middleInside( a, b ) {
  22581. let p = a,
  22582. inside = false;
  22583. const px = ( a.x + b.x ) / 2,
  22584. py = ( a.y + b.y ) / 2;
  22585. do {
  22586. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  22587. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  22588. inside = ! inside;
  22589. p = p.next;
  22590. } while ( p !== a );
  22591. return inside;
  22592. }
  22593. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  22594. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  22595. function splitPolygon( a, b ) {
  22596. const a2 = new Node( a.i, a.x, a.y ),
  22597. b2 = new Node( b.i, b.x, b.y ),
  22598. an = a.next,
  22599. bp = b.prev;
  22600. a.next = b;
  22601. b.prev = a;
  22602. a2.next = an;
  22603. an.prev = a2;
  22604. b2.next = a2;
  22605. a2.prev = b2;
  22606. bp.next = b2;
  22607. b2.prev = bp;
  22608. return b2;
  22609. }
  22610. // create a node and optionally link it with previous one (in a circular doubly linked list)
  22611. function insertNode( i, x, y, last ) {
  22612. const p = new Node( i, x, y );
  22613. if ( ! last ) {
  22614. p.prev = p;
  22615. p.next = p;
  22616. } else {
  22617. p.next = last.next;
  22618. p.prev = last;
  22619. last.next.prev = p;
  22620. last.next = p;
  22621. }
  22622. return p;
  22623. }
  22624. function removeNode( p ) {
  22625. p.next.prev = p.prev;
  22626. p.prev.next = p.next;
  22627. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  22628. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  22629. }
  22630. function Node( i, x, y ) {
  22631. // vertex index in coordinates array
  22632. this.i = i;
  22633. // vertex coordinates
  22634. this.x = x;
  22635. this.y = y;
  22636. // previous and next vertex nodes in a polygon ring
  22637. this.prev = null;
  22638. this.next = null;
  22639. // z-order curve value
  22640. this.z = 0;
  22641. // previous and next nodes in z-order
  22642. this.prevZ = null;
  22643. this.nextZ = null;
  22644. // indicates whether this is a steiner point
  22645. this.steiner = false;
  22646. }
  22647. function signedArea( data, start, end, dim ) {
  22648. let sum = 0;
  22649. for ( let i = start, j = end - dim; i < end; i += dim ) {
  22650. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  22651. j = i;
  22652. }
  22653. return sum;
  22654. }
  22655. class ShapeUtils {
  22656. // calculate area of the contour polygon
  22657. static area( contour ) {
  22658. const n = contour.length;
  22659. let a = 0.0;
  22660. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  22661. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  22662. }
  22663. return a * 0.5;
  22664. }
  22665. static isClockWise( pts ) {
  22666. return ShapeUtils.area( pts ) < 0;
  22667. }
  22668. static triangulateShape( contour, holes ) {
  22669. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  22670. const holeIndices = []; // array of hole indices
  22671. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  22672. removeDupEndPts( contour );
  22673. addContour( vertices, contour );
  22674. //
  22675. let holeIndex = contour.length;
  22676. holes.forEach( removeDupEndPts );
  22677. for ( let i = 0; i < holes.length; i ++ ) {
  22678. holeIndices.push( holeIndex );
  22679. holeIndex += holes[ i ].length;
  22680. addContour( vertices, holes[ i ] );
  22681. }
  22682. //
  22683. const triangles = Earcut.triangulate( vertices, holeIndices );
  22684. //
  22685. for ( let i = 0; i < triangles.length; i += 3 ) {
  22686. faces.push( triangles.slice( i, i + 3 ) );
  22687. }
  22688. return faces;
  22689. }
  22690. }
  22691. function removeDupEndPts( points ) {
  22692. const l = points.length;
  22693. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  22694. points.pop();
  22695. }
  22696. }
  22697. function addContour( vertices, contour ) {
  22698. for ( let i = 0; i < contour.length; i ++ ) {
  22699. vertices.push( contour[ i ].x );
  22700. vertices.push( contour[ i ].y );
  22701. }
  22702. }
  22703. /**
  22704. * Creates extruded geometry from a path shape.
  22705. *
  22706. * parameters = {
  22707. *
  22708. * curveSegments: <int>, // number of points on the curves
  22709. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  22710. * depth: <float>, // Depth to extrude the shape
  22711. *
  22712. * bevelEnabled: <bool>, // turn on bevel
  22713. * bevelThickness: <float>, // how deep into the original shape bevel goes
  22714. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  22715. * bevelOffset: <float>, // how far from shape outline does bevel start
  22716. * bevelSegments: <int>, // number of bevel layers
  22717. *
  22718. * extrudePath: <THREE.Curve> // curve to extrude shape along
  22719. *
  22720. * UVGenerator: <Object> // object that provides UV generator functions
  22721. *
  22722. * }
  22723. */
  22724. class ExtrudeGeometry extends BufferGeometry {
  22725. 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 = {} ) {
  22726. super();
  22727. this.type = 'ExtrudeGeometry';
  22728. this.parameters = {
  22729. shapes: shapes,
  22730. options: options
  22731. };
  22732. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  22733. const scope = this;
  22734. const verticesArray = [];
  22735. const uvArray = [];
  22736. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22737. const shape = shapes[ i ];
  22738. addShape( shape );
  22739. }
  22740. // build geometry
  22741. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  22742. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  22743. this.computeVertexNormals();
  22744. // functions
  22745. function addShape( shape ) {
  22746. const placeholder = [];
  22747. // options
  22748. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22749. const steps = options.steps !== undefined ? options.steps : 1;
  22750. const depth = options.depth !== undefined ? options.depth : 1;
  22751. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  22752. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  22753. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  22754. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  22755. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  22756. const extrudePath = options.extrudePath;
  22757. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  22758. //
  22759. let extrudePts, extrudeByPath = false;
  22760. let splineTube, binormal, normal, position2;
  22761. if ( extrudePath ) {
  22762. extrudePts = extrudePath.getSpacedPoints( steps );
  22763. extrudeByPath = true;
  22764. bevelEnabled = false; // bevels not supported for path extrusion
  22765. // SETUP TNB variables
  22766. // TODO1 - have a .isClosed in spline?
  22767. splineTube = extrudePath.computeFrenetFrames( steps, false );
  22768. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  22769. binormal = new Vector3();
  22770. normal = new Vector3();
  22771. position2 = new Vector3();
  22772. }
  22773. // Safeguards if bevels are not enabled
  22774. if ( ! bevelEnabled ) {
  22775. bevelSegments = 0;
  22776. bevelThickness = 0;
  22777. bevelSize = 0;
  22778. bevelOffset = 0;
  22779. }
  22780. // Variables initialization
  22781. const shapePoints = shape.extractPoints( curveSegments );
  22782. let vertices = shapePoints.shape;
  22783. const holes = shapePoints.holes;
  22784. const reverse = ! ShapeUtils.isClockWise( vertices );
  22785. if ( reverse ) {
  22786. vertices = vertices.reverse();
  22787. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  22788. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22789. const ahole = holes[ h ];
  22790. if ( ShapeUtils.isClockWise( ahole ) ) {
  22791. holes[ h ] = ahole.reverse();
  22792. }
  22793. }
  22794. }
  22795. const faces = ShapeUtils.triangulateShape( vertices, holes );
  22796. /* Vertices */
  22797. const contour = vertices; // vertices has all points but contour has only points of circumference
  22798. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22799. const ahole = holes[ h ];
  22800. vertices = vertices.concat( ahole );
  22801. }
  22802. function scalePt2( pt, vec, size ) {
  22803. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  22804. return pt.clone().addScaledVector( vec, size );
  22805. }
  22806. const vlen = vertices.length, flen = faces.length;
  22807. // Find directions for point movement
  22808. function getBevelVec( inPt, inPrev, inNext ) {
  22809. // computes for inPt the corresponding point inPt' on a new contour
  22810. // shifted by 1 unit (length of normalized vector) to the left
  22811. // if we walk along contour clockwise, this new contour is outside the old one
  22812. //
  22813. // inPt' is the intersection of the two lines parallel to the two
  22814. // adjacent edges of inPt at a distance of 1 unit on the left side.
  22815. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  22816. // good reading for geometry algorithms (here: line-line intersection)
  22817. // http://geomalgorithms.com/a05-_intersect-1.html
  22818. const v_prev_x = inPt.x - inPrev.x,
  22819. v_prev_y = inPt.y - inPrev.y;
  22820. const v_next_x = inNext.x - inPt.x,
  22821. v_next_y = inNext.y - inPt.y;
  22822. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  22823. // check for collinear edges
  22824. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22825. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  22826. // not collinear
  22827. // length of vectors for normalizing
  22828. const v_prev_len = Math.sqrt( v_prev_lensq );
  22829. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  22830. // shift adjacent points by unit vectors to the left
  22831. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  22832. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  22833. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  22834. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  22835. // scaling factor for v_prev to intersection point
  22836. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  22837. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  22838. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22839. // vector from inPt to intersection point
  22840. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  22841. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  22842. // Don't normalize!, otherwise sharp corners become ugly
  22843. // but prevent crazy spikes
  22844. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  22845. if ( v_trans_lensq <= 2 ) {
  22846. return new Vector2( v_trans_x, v_trans_y );
  22847. } else {
  22848. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  22849. }
  22850. } else {
  22851. // handle special case of collinear edges
  22852. let direction_eq = false; // assumes: opposite
  22853. if ( v_prev_x > Number.EPSILON ) {
  22854. if ( v_next_x > Number.EPSILON ) {
  22855. direction_eq = true;
  22856. }
  22857. } else {
  22858. if ( v_prev_x < - Number.EPSILON ) {
  22859. if ( v_next_x < - Number.EPSILON ) {
  22860. direction_eq = true;
  22861. }
  22862. } else {
  22863. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  22864. direction_eq = true;
  22865. }
  22866. }
  22867. }
  22868. if ( direction_eq ) {
  22869. // console.log("Warning: lines are a straight sequence");
  22870. v_trans_x = - v_prev_y;
  22871. v_trans_y = v_prev_x;
  22872. shrink_by = Math.sqrt( v_prev_lensq );
  22873. } else {
  22874. // console.log("Warning: lines are a straight spike");
  22875. v_trans_x = v_prev_x;
  22876. v_trans_y = v_prev_y;
  22877. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  22878. }
  22879. }
  22880. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  22881. }
  22882. const contourMovements = [];
  22883. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22884. if ( j === il ) j = 0;
  22885. if ( k === il ) k = 0;
  22886. // (j)---(i)---(k)
  22887. // console.log('i,j,k', i, j , k)
  22888. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  22889. }
  22890. const holesMovements = [];
  22891. let oneHoleMovements, verticesMovements = contourMovements.concat();
  22892. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22893. const ahole = holes[ h ];
  22894. oneHoleMovements = [];
  22895. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22896. if ( j === il ) j = 0;
  22897. if ( k === il ) k = 0;
  22898. // (j)---(i)---(k)
  22899. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  22900. }
  22901. holesMovements.push( oneHoleMovements );
  22902. verticesMovements = verticesMovements.concat( oneHoleMovements );
  22903. }
  22904. // Loop bevelSegments, 1 for the front, 1 for the back
  22905. for ( let b = 0; b < bevelSegments; b ++ ) {
  22906. //for ( b = bevelSegments; b > 0; b -- ) {
  22907. const t = b / bevelSegments;
  22908. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22909. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22910. // contract shape
  22911. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22912. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22913. v( vert.x, vert.y, - z );
  22914. }
  22915. // expand holes
  22916. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22917. const ahole = holes[ h ];
  22918. oneHoleMovements = holesMovements[ h ];
  22919. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22920. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22921. v( vert.x, vert.y, - z );
  22922. }
  22923. }
  22924. }
  22925. const bs = bevelSize + bevelOffset;
  22926. // Back facing vertices
  22927. for ( let i = 0; i < vlen; i ++ ) {
  22928. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22929. if ( ! extrudeByPath ) {
  22930. v( vert.x, vert.y, 0 );
  22931. } else {
  22932. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22933. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22934. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22935. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22936. v( position2.x, position2.y, position2.z );
  22937. }
  22938. }
  22939. // Add stepped vertices...
  22940. // Including front facing vertices
  22941. for ( let s = 1; s <= steps; s ++ ) {
  22942. for ( let i = 0; i < vlen; i ++ ) {
  22943. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22944. if ( ! extrudeByPath ) {
  22945. v( vert.x, vert.y, depth / steps * s );
  22946. } else {
  22947. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22948. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22949. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22950. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22951. v( position2.x, position2.y, position2.z );
  22952. }
  22953. }
  22954. }
  22955. // Add bevel segments planes
  22956. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22957. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  22958. const t = b / bevelSegments;
  22959. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22960. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22961. // contract shape
  22962. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22963. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22964. v( vert.x, vert.y, depth + z );
  22965. }
  22966. // expand holes
  22967. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22968. const ahole = holes[ h ];
  22969. oneHoleMovements = holesMovements[ h ];
  22970. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22971. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22972. if ( ! extrudeByPath ) {
  22973. v( vert.x, vert.y, depth + z );
  22974. } else {
  22975. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22976. }
  22977. }
  22978. }
  22979. }
  22980. /* Faces */
  22981. // Top and bottom faces
  22982. buildLidFaces();
  22983. // Sides faces
  22984. buildSideFaces();
  22985. ///// Internal functions
  22986. function buildLidFaces() {
  22987. const start = verticesArray.length / 3;
  22988. if ( bevelEnabled ) {
  22989. let layer = 0; // steps + 1
  22990. let offset = vlen * layer;
  22991. // Bottom faces
  22992. for ( let i = 0; i < flen; i ++ ) {
  22993. const face = faces[ i ];
  22994. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22995. }
  22996. layer = steps + bevelSegments * 2;
  22997. offset = vlen * layer;
  22998. // Top faces
  22999. for ( let i = 0; i < flen; i ++ ) {
  23000. const face = faces[ i ];
  23001. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23002. }
  23003. } else {
  23004. // Bottom faces
  23005. for ( let i = 0; i < flen; i ++ ) {
  23006. const face = faces[ i ];
  23007. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23008. }
  23009. // Top faces
  23010. for ( let i = 0; i < flen; i ++ ) {
  23011. const face = faces[ i ];
  23012. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23013. }
  23014. }
  23015. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23016. }
  23017. // Create faces for the z-sides of the shape
  23018. function buildSideFaces() {
  23019. const start = verticesArray.length / 3;
  23020. let layeroffset = 0;
  23021. sidewalls( contour, layeroffset );
  23022. layeroffset += contour.length;
  23023. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23024. const ahole = holes[ h ];
  23025. sidewalls( ahole, layeroffset );
  23026. //, true
  23027. layeroffset += ahole.length;
  23028. }
  23029. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23030. }
  23031. function sidewalls( contour, layeroffset ) {
  23032. let i = contour.length;
  23033. while ( -- i >= 0 ) {
  23034. const j = i;
  23035. let k = i - 1;
  23036. if ( k < 0 ) k = contour.length - 1;
  23037. //console.log('b', i,j, i-1, k,vertices.length);
  23038. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  23039. const slen1 = vlen * s;
  23040. const slen2 = vlen * ( s + 1 );
  23041. const a = layeroffset + j + slen1,
  23042. b = layeroffset + k + slen1,
  23043. c = layeroffset + k + slen2,
  23044. d = layeroffset + j + slen2;
  23045. f4( a, b, c, d );
  23046. }
  23047. }
  23048. }
  23049. function v( x, y, z ) {
  23050. placeholder.push( x );
  23051. placeholder.push( y );
  23052. placeholder.push( z );
  23053. }
  23054. function f3( a, b, c ) {
  23055. addVertex( a );
  23056. addVertex( b );
  23057. addVertex( c );
  23058. const nextIndex = verticesArray.length / 3;
  23059. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23060. addUV( uvs[ 0 ] );
  23061. addUV( uvs[ 1 ] );
  23062. addUV( uvs[ 2 ] );
  23063. }
  23064. function f4( a, b, c, d ) {
  23065. addVertex( a );
  23066. addVertex( b );
  23067. addVertex( d );
  23068. addVertex( b );
  23069. addVertex( c );
  23070. addVertex( d );
  23071. const nextIndex = verticesArray.length / 3;
  23072. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23073. addUV( uvs[ 0 ] );
  23074. addUV( uvs[ 1 ] );
  23075. addUV( uvs[ 3 ] );
  23076. addUV( uvs[ 1 ] );
  23077. addUV( uvs[ 2 ] );
  23078. addUV( uvs[ 3 ] );
  23079. }
  23080. function addVertex( index ) {
  23081. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23082. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23083. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23084. }
  23085. function addUV( vector2 ) {
  23086. uvArray.push( vector2.x );
  23087. uvArray.push( vector2.y );
  23088. }
  23089. }
  23090. }
  23091. copy( source ) {
  23092. super.copy( source );
  23093. this.parameters = Object.assign( {}, source.parameters );
  23094. return this;
  23095. }
  23096. toJSON() {
  23097. const data = super.toJSON();
  23098. const shapes = this.parameters.shapes;
  23099. const options = this.parameters.options;
  23100. return toJSON$1( shapes, options, data );
  23101. }
  23102. static fromJSON( data, shapes ) {
  23103. const geometryShapes = [];
  23104. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23105. const shape = shapes[ data.shapes[ j ] ];
  23106. geometryShapes.push( shape );
  23107. }
  23108. const extrudePath = data.options.extrudePath;
  23109. if ( extrudePath !== undefined ) {
  23110. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23111. }
  23112. return new ExtrudeGeometry( geometryShapes, data.options );
  23113. }
  23114. }
  23115. const WorldUVGenerator = {
  23116. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23117. const a_x = vertices[ indexA * 3 ];
  23118. const a_y = vertices[ indexA * 3 + 1 ];
  23119. const b_x = vertices[ indexB * 3 ];
  23120. const b_y = vertices[ indexB * 3 + 1 ];
  23121. const c_x = vertices[ indexC * 3 ];
  23122. const c_y = vertices[ indexC * 3 + 1 ];
  23123. return [
  23124. new Vector2( a_x, a_y ),
  23125. new Vector2( b_x, b_y ),
  23126. new Vector2( c_x, c_y )
  23127. ];
  23128. },
  23129. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23130. const a_x = vertices[ indexA * 3 ];
  23131. const a_y = vertices[ indexA * 3 + 1 ];
  23132. const a_z = vertices[ indexA * 3 + 2 ];
  23133. const b_x = vertices[ indexB * 3 ];
  23134. const b_y = vertices[ indexB * 3 + 1 ];
  23135. const b_z = vertices[ indexB * 3 + 2 ];
  23136. const c_x = vertices[ indexC * 3 ];
  23137. const c_y = vertices[ indexC * 3 + 1 ];
  23138. const c_z = vertices[ indexC * 3 + 2 ];
  23139. const d_x = vertices[ indexD * 3 ];
  23140. const d_y = vertices[ indexD * 3 + 1 ];
  23141. const d_z = vertices[ indexD * 3 + 2 ];
  23142. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  23143. return [
  23144. new Vector2( a_x, 1 - a_z ),
  23145. new Vector2( b_x, 1 - b_z ),
  23146. new Vector2( c_x, 1 - c_z ),
  23147. new Vector2( d_x, 1 - d_z )
  23148. ];
  23149. } else {
  23150. return [
  23151. new Vector2( a_y, 1 - a_z ),
  23152. new Vector2( b_y, 1 - b_z ),
  23153. new Vector2( c_y, 1 - c_z ),
  23154. new Vector2( d_y, 1 - d_z )
  23155. ];
  23156. }
  23157. }
  23158. };
  23159. function toJSON$1( shapes, options, data ) {
  23160. data.shapes = [];
  23161. if ( Array.isArray( shapes ) ) {
  23162. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23163. const shape = shapes[ i ];
  23164. data.shapes.push( shape.uuid );
  23165. }
  23166. } else {
  23167. data.shapes.push( shapes.uuid );
  23168. }
  23169. data.options = Object.assign( {}, options );
  23170. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  23171. return data;
  23172. }
  23173. class IcosahedronGeometry extends PolyhedronGeometry {
  23174. constructor( radius = 1, detail = 0 ) {
  23175. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23176. const vertices = [
  23177. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23178. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23179. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23180. ];
  23181. const indices = [
  23182. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23183. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23184. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23185. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23186. ];
  23187. super( vertices, indices, radius, detail );
  23188. this.type = 'IcosahedronGeometry';
  23189. this.parameters = {
  23190. radius: radius,
  23191. detail: detail
  23192. };
  23193. }
  23194. static fromJSON( data ) {
  23195. return new IcosahedronGeometry( data.radius, data.detail );
  23196. }
  23197. }
  23198. class OctahedronGeometry extends PolyhedronGeometry {
  23199. constructor( radius = 1, detail = 0 ) {
  23200. const vertices = [
  23201. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23202. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23203. ];
  23204. const indices = [
  23205. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23206. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23207. 1, 3, 4, 1, 4, 2
  23208. ];
  23209. super( vertices, indices, radius, detail );
  23210. this.type = 'OctahedronGeometry';
  23211. this.parameters = {
  23212. radius: radius,
  23213. detail: detail
  23214. };
  23215. }
  23216. static fromJSON( data ) {
  23217. return new OctahedronGeometry( data.radius, data.detail );
  23218. }
  23219. }
  23220. class RingGeometry extends BufferGeometry {
  23221. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23222. super();
  23223. this.type = 'RingGeometry';
  23224. this.parameters = {
  23225. innerRadius: innerRadius,
  23226. outerRadius: outerRadius,
  23227. thetaSegments: thetaSegments,
  23228. phiSegments: phiSegments,
  23229. thetaStart: thetaStart,
  23230. thetaLength: thetaLength
  23231. };
  23232. thetaSegments = Math.max( 3, thetaSegments );
  23233. phiSegments = Math.max( 1, phiSegments );
  23234. // buffers
  23235. const indices = [];
  23236. const vertices = [];
  23237. const normals = [];
  23238. const uvs = [];
  23239. // some helper variables
  23240. let radius = innerRadius;
  23241. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23242. const vertex = new Vector3();
  23243. const uv = new Vector2();
  23244. // generate vertices, normals and uvs
  23245. for ( let j = 0; j <= phiSegments; j ++ ) {
  23246. for ( let i = 0; i <= thetaSegments; i ++ ) {
  23247. // values are generate from the inside of the ring to the outside
  23248. const segment = thetaStart + i / thetaSegments * thetaLength;
  23249. // vertex
  23250. vertex.x = radius * Math.cos( segment );
  23251. vertex.y = radius * Math.sin( segment );
  23252. vertices.push( vertex.x, vertex.y, vertex.z );
  23253. // normal
  23254. normals.push( 0, 0, 1 );
  23255. // uv
  23256. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23257. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23258. uvs.push( uv.x, uv.y );
  23259. }
  23260. // increase the radius for next row of vertices
  23261. radius += radiusStep;
  23262. }
  23263. // indices
  23264. for ( let j = 0; j < phiSegments; j ++ ) {
  23265. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  23266. for ( let i = 0; i < thetaSegments; i ++ ) {
  23267. const segment = i + thetaSegmentLevel;
  23268. const a = segment;
  23269. const b = segment + thetaSegments + 1;
  23270. const c = segment + thetaSegments + 2;
  23271. const d = segment + 1;
  23272. // faces
  23273. indices.push( a, b, d );
  23274. indices.push( b, c, d );
  23275. }
  23276. }
  23277. // build geometry
  23278. this.setIndex( indices );
  23279. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23280. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23281. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23282. }
  23283. copy( source ) {
  23284. super.copy( source );
  23285. this.parameters = Object.assign( {}, source.parameters );
  23286. return this;
  23287. }
  23288. static fromJSON( data ) {
  23289. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  23290. }
  23291. }
  23292. class ShapeGeometry extends BufferGeometry {
  23293. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  23294. super();
  23295. this.type = 'ShapeGeometry';
  23296. this.parameters = {
  23297. shapes: shapes,
  23298. curveSegments: curveSegments
  23299. };
  23300. // buffers
  23301. const indices = [];
  23302. const vertices = [];
  23303. const normals = [];
  23304. const uvs = [];
  23305. // helper variables
  23306. let groupStart = 0;
  23307. let groupCount = 0;
  23308. // allow single and array values for "shapes" parameter
  23309. if ( Array.isArray( shapes ) === false ) {
  23310. addShape( shapes );
  23311. } else {
  23312. for ( let i = 0; i < shapes.length; i ++ ) {
  23313. addShape( shapes[ i ] );
  23314. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23315. groupStart += groupCount;
  23316. groupCount = 0;
  23317. }
  23318. }
  23319. // build geometry
  23320. this.setIndex( indices );
  23321. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23322. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23323. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23324. // helper functions
  23325. function addShape( shape ) {
  23326. const indexOffset = vertices.length / 3;
  23327. const points = shape.extractPoints( curveSegments );
  23328. let shapeVertices = points.shape;
  23329. const shapeHoles = points.holes;
  23330. // check direction of vertices
  23331. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23332. shapeVertices = shapeVertices.reverse();
  23333. }
  23334. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23335. const shapeHole = shapeHoles[ i ];
  23336. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23337. shapeHoles[ i ] = shapeHole.reverse();
  23338. }
  23339. }
  23340. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23341. // join vertices of inner and outer paths to a single array
  23342. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23343. const shapeHole = shapeHoles[ i ];
  23344. shapeVertices = shapeVertices.concat( shapeHole );
  23345. }
  23346. // vertices, normals, uvs
  23347. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23348. const vertex = shapeVertices[ i ];
  23349. vertices.push( vertex.x, vertex.y, 0 );
  23350. normals.push( 0, 0, 1 );
  23351. uvs.push( vertex.x, vertex.y ); // world uvs
  23352. }
  23353. // indices
  23354. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  23355. const face = faces[ i ];
  23356. const a = face[ 0 ] + indexOffset;
  23357. const b = face[ 1 ] + indexOffset;
  23358. const c = face[ 2 ] + indexOffset;
  23359. indices.push( a, b, c );
  23360. groupCount += 3;
  23361. }
  23362. }
  23363. }
  23364. copy( source ) {
  23365. super.copy( source );
  23366. this.parameters = Object.assign( {}, source.parameters );
  23367. return this;
  23368. }
  23369. toJSON() {
  23370. const data = super.toJSON();
  23371. const shapes = this.parameters.shapes;
  23372. return toJSON( shapes, data );
  23373. }
  23374. static fromJSON( data, shapes ) {
  23375. const geometryShapes = [];
  23376. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23377. const shape = shapes[ data.shapes[ j ] ];
  23378. geometryShapes.push( shape );
  23379. }
  23380. return new ShapeGeometry( geometryShapes, data.curveSegments );
  23381. }
  23382. }
  23383. function toJSON( shapes, data ) {
  23384. data.shapes = [];
  23385. if ( Array.isArray( shapes ) ) {
  23386. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23387. const shape = shapes[ i ];
  23388. data.shapes.push( shape.uuid );
  23389. }
  23390. } else {
  23391. data.shapes.push( shapes.uuid );
  23392. }
  23393. return data;
  23394. }
  23395. class SphereGeometry extends BufferGeometry {
  23396. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  23397. super();
  23398. this.type = 'SphereGeometry';
  23399. this.parameters = {
  23400. radius: radius,
  23401. widthSegments: widthSegments,
  23402. heightSegments: heightSegments,
  23403. phiStart: phiStart,
  23404. phiLength: phiLength,
  23405. thetaStart: thetaStart,
  23406. thetaLength: thetaLength
  23407. };
  23408. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  23409. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  23410. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  23411. let index = 0;
  23412. const grid = [];
  23413. const vertex = new Vector3();
  23414. const normal = new Vector3();
  23415. // buffers
  23416. const indices = [];
  23417. const vertices = [];
  23418. const normals = [];
  23419. const uvs = [];
  23420. // generate vertices, normals and uvs
  23421. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  23422. const verticesRow = [];
  23423. const v = iy / heightSegments;
  23424. // special case for the poles
  23425. let uOffset = 0;
  23426. if ( iy === 0 && thetaStart === 0 ) {
  23427. uOffset = 0.5 / widthSegments;
  23428. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  23429. uOffset = - 0.5 / widthSegments;
  23430. }
  23431. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  23432. const u = ix / widthSegments;
  23433. // vertex
  23434. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23435. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  23436. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23437. vertices.push( vertex.x, vertex.y, vertex.z );
  23438. // normal
  23439. normal.copy( vertex ).normalize();
  23440. normals.push( normal.x, normal.y, normal.z );
  23441. // uv
  23442. uvs.push( u + uOffset, 1 - v );
  23443. verticesRow.push( index ++ );
  23444. }
  23445. grid.push( verticesRow );
  23446. }
  23447. // indices
  23448. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  23449. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  23450. const a = grid[ iy ][ ix + 1 ];
  23451. const b = grid[ iy ][ ix ];
  23452. const c = grid[ iy + 1 ][ ix ];
  23453. const d = grid[ iy + 1 ][ ix + 1 ];
  23454. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  23455. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  23456. }
  23457. }
  23458. // build geometry
  23459. this.setIndex( indices );
  23460. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23461. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23462. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23463. }
  23464. copy( source ) {
  23465. super.copy( source );
  23466. this.parameters = Object.assign( {}, source.parameters );
  23467. return this;
  23468. }
  23469. static fromJSON( data ) {
  23470. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  23471. }
  23472. }
  23473. class TetrahedronGeometry extends PolyhedronGeometry {
  23474. constructor( radius = 1, detail = 0 ) {
  23475. const vertices = [
  23476. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23477. ];
  23478. const indices = [
  23479. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23480. ];
  23481. super( vertices, indices, radius, detail );
  23482. this.type = 'TetrahedronGeometry';
  23483. this.parameters = {
  23484. radius: radius,
  23485. detail: detail
  23486. };
  23487. }
  23488. static fromJSON( data ) {
  23489. return new TetrahedronGeometry( data.radius, data.detail );
  23490. }
  23491. }
  23492. class TorusGeometry extends BufferGeometry {
  23493. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  23494. super();
  23495. this.type = 'TorusGeometry';
  23496. this.parameters = {
  23497. radius: radius,
  23498. tube: tube,
  23499. radialSegments: radialSegments,
  23500. tubularSegments: tubularSegments,
  23501. arc: arc
  23502. };
  23503. radialSegments = Math.floor( radialSegments );
  23504. tubularSegments = Math.floor( tubularSegments );
  23505. // buffers
  23506. const indices = [];
  23507. const vertices = [];
  23508. const normals = [];
  23509. const uvs = [];
  23510. // helper variables
  23511. const center = new Vector3();
  23512. const vertex = new Vector3();
  23513. const normal = new Vector3();
  23514. // generate vertices, normals and uvs
  23515. for ( let j = 0; j <= radialSegments; j ++ ) {
  23516. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23517. const u = i / tubularSegments * arc;
  23518. const v = j / radialSegments * Math.PI * 2;
  23519. // vertex
  23520. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23521. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23522. vertex.z = tube * Math.sin( v );
  23523. vertices.push( vertex.x, vertex.y, vertex.z );
  23524. // normal
  23525. center.x = radius * Math.cos( u );
  23526. center.y = radius * Math.sin( u );
  23527. normal.subVectors( vertex, center ).normalize();
  23528. normals.push( normal.x, normal.y, normal.z );
  23529. // uv
  23530. uvs.push( i / tubularSegments );
  23531. uvs.push( j / radialSegments );
  23532. }
  23533. }
  23534. // generate indices
  23535. for ( let j = 1; j <= radialSegments; j ++ ) {
  23536. for ( let i = 1; i <= tubularSegments; i ++ ) {
  23537. // indices
  23538. const a = ( tubularSegments + 1 ) * j + i - 1;
  23539. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23540. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23541. const d = ( tubularSegments + 1 ) * j + i;
  23542. // faces
  23543. indices.push( a, b, d );
  23544. indices.push( b, c, d );
  23545. }
  23546. }
  23547. // build geometry
  23548. this.setIndex( indices );
  23549. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23550. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23551. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23552. }
  23553. copy( source ) {
  23554. super.copy( source );
  23555. this.parameters = Object.assign( {}, source.parameters );
  23556. return this;
  23557. }
  23558. static fromJSON( data ) {
  23559. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  23560. }
  23561. }
  23562. class TorusKnotGeometry extends BufferGeometry {
  23563. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  23564. super();
  23565. this.type = 'TorusKnotGeometry';
  23566. this.parameters = {
  23567. radius: radius,
  23568. tube: tube,
  23569. tubularSegments: tubularSegments,
  23570. radialSegments: radialSegments,
  23571. p: p,
  23572. q: q
  23573. };
  23574. tubularSegments = Math.floor( tubularSegments );
  23575. radialSegments = Math.floor( radialSegments );
  23576. // buffers
  23577. const indices = [];
  23578. const vertices = [];
  23579. const normals = [];
  23580. const uvs = [];
  23581. // helper variables
  23582. const vertex = new Vector3();
  23583. const normal = new Vector3();
  23584. const P1 = new Vector3();
  23585. const P2 = new Vector3();
  23586. const B = new Vector3();
  23587. const T = new Vector3();
  23588. const N = new Vector3();
  23589. // generate vertices, normals and uvs
  23590. for ( let i = 0; i <= tubularSegments; ++ i ) {
  23591. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  23592. const u = i / tubularSegments * p * Math.PI * 2;
  23593. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23594. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23595. calculatePositionOnCurve( u, p, q, radius, P1 );
  23596. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23597. // calculate orthonormal basis
  23598. T.subVectors( P2, P1 );
  23599. N.addVectors( P2, P1 );
  23600. B.crossVectors( T, N );
  23601. N.crossVectors( B, T );
  23602. // normalize B, N. T can be ignored, we don't use it
  23603. B.normalize();
  23604. N.normalize();
  23605. for ( let j = 0; j <= radialSegments; ++ j ) {
  23606. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23607. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23608. const v = j / radialSegments * Math.PI * 2;
  23609. const cx = - tube * Math.cos( v );
  23610. const cy = tube * Math.sin( v );
  23611. // now calculate the final vertex position.
  23612. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  23613. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23614. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23615. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23616. vertices.push( vertex.x, vertex.y, vertex.z );
  23617. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23618. normal.subVectors( vertex, P1 ).normalize();
  23619. normals.push( normal.x, normal.y, normal.z );
  23620. // uv
  23621. uvs.push( i / tubularSegments );
  23622. uvs.push( j / radialSegments );
  23623. }
  23624. }
  23625. // generate indices
  23626. for ( let j = 1; j <= tubularSegments; j ++ ) {
  23627. for ( let i = 1; i <= radialSegments; i ++ ) {
  23628. // indices
  23629. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23630. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  23631. const c = ( radialSegments + 1 ) * j + i;
  23632. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23633. // faces
  23634. indices.push( a, b, d );
  23635. indices.push( b, c, d );
  23636. }
  23637. }
  23638. // build geometry
  23639. this.setIndex( indices );
  23640. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23641. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23642. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23643. // this function calculates the current position on the torus curve
  23644. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23645. const cu = Math.cos( u );
  23646. const su = Math.sin( u );
  23647. const quOverP = q / p * u;
  23648. const cs = Math.cos( quOverP );
  23649. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23650. position.y = radius * ( 2 + cs ) * su * 0.5;
  23651. position.z = radius * Math.sin( quOverP ) * 0.5;
  23652. }
  23653. }
  23654. copy( source ) {
  23655. super.copy( source );
  23656. this.parameters = Object.assign( {}, source.parameters );
  23657. return this;
  23658. }
  23659. static fromJSON( data ) {
  23660. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  23661. }
  23662. }
  23663. class TubeGeometry extends BufferGeometry {
  23664. 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 ) {
  23665. super();
  23666. this.type = 'TubeGeometry';
  23667. this.parameters = {
  23668. path: path,
  23669. tubularSegments: tubularSegments,
  23670. radius: radius,
  23671. radialSegments: radialSegments,
  23672. closed: closed
  23673. };
  23674. const frames = path.computeFrenetFrames( tubularSegments, closed );
  23675. // expose internals
  23676. this.tangents = frames.tangents;
  23677. this.normals = frames.normals;
  23678. this.binormals = frames.binormals;
  23679. // helper variables
  23680. const vertex = new Vector3();
  23681. const normal = new Vector3();
  23682. const uv = new Vector2();
  23683. let P = new Vector3();
  23684. // buffer
  23685. const vertices = [];
  23686. const normals = [];
  23687. const uvs = [];
  23688. const indices = [];
  23689. // create buffer data
  23690. generateBufferData();
  23691. // build geometry
  23692. this.setIndex( indices );
  23693. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23694. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23695. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23696. // functions
  23697. function generateBufferData() {
  23698. for ( let i = 0; i < tubularSegments; i ++ ) {
  23699. generateSegment( i );
  23700. }
  23701. // if the geometry is not closed, generate the last row of vertices and normals
  23702. // at the regular position on the given path
  23703. //
  23704. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  23705. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  23706. // uvs are generated in a separate function.
  23707. // this makes it easy compute correct values for closed geometries
  23708. generateUVs();
  23709. // finally create faces
  23710. generateIndices();
  23711. }
  23712. function generateSegment( i ) {
  23713. // we use getPointAt to sample evenly distributed points from the given path
  23714. P = path.getPointAt( i / tubularSegments, P );
  23715. // retrieve corresponding normal and binormal
  23716. const N = frames.normals[ i ];
  23717. const B = frames.binormals[ i ];
  23718. // generate normals and vertices for the current segment
  23719. for ( let j = 0; j <= radialSegments; j ++ ) {
  23720. const v = j / radialSegments * Math.PI * 2;
  23721. const sin = Math.sin( v );
  23722. const cos = - Math.cos( v );
  23723. // normal
  23724. normal.x = ( cos * N.x + sin * B.x );
  23725. normal.y = ( cos * N.y + sin * B.y );
  23726. normal.z = ( cos * N.z + sin * B.z );
  23727. normal.normalize();
  23728. normals.push( normal.x, normal.y, normal.z );
  23729. // vertex
  23730. vertex.x = P.x + radius * normal.x;
  23731. vertex.y = P.y + radius * normal.y;
  23732. vertex.z = P.z + radius * normal.z;
  23733. vertices.push( vertex.x, vertex.y, vertex.z );
  23734. }
  23735. }
  23736. function generateIndices() {
  23737. for ( let j = 1; j <= tubularSegments; j ++ ) {
  23738. for ( let i = 1; i <= radialSegments; i ++ ) {
  23739. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23740. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  23741. const c = ( radialSegments + 1 ) * j + i;
  23742. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23743. // faces
  23744. indices.push( a, b, d );
  23745. indices.push( b, c, d );
  23746. }
  23747. }
  23748. }
  23749. function generateUVs() {
  23750. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23751. for ( let j = 0; j <= radialSegments; j ++ ) {
  23752. uv.x = i / tubularSegments;
  23753. uv.y = j / radialSegments;
  23754. uvs.push( uv.x, uv.y );
  23755. }
  23756. }
  23757. }
  23758. }
  23759. copy( source ) {
  23760. super.copy( source );
  23761. this.parameters = Object.assign( {}, source.parameters );
  23762. return this;
  23763. }
  23764. toJSON() {
  23765. const data = super.toJSON();
  23766. data.path = this.parameters.path.toJSON();
  23767. return data;
  23768. }
  23769. static fromJSON( data ) {
  23770. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23771. // User defined curves or instances of CurvePath will not be deserialized.
  23772. return new TubeGeometry(
  23773. new Curves[ data.path.type ]().fromJSON( data.path ),
  23774. data.tubularSegments,
  23775. data.radius,
  23776. data.radialSegments,
  23777. data.closed
  23778. );
  23779. }
  23780. }
  23781. class WireframeGeometry extends BufferGeometry {
  23782. constructor( geometry = null ) {
  23783. super();
  23784. this.type = 'WireframeGeometry';
  23785. this.parameters = {
  23786. geometry: geometry
  23787. };
  23788. if ( geometry !== null ) {
  23789. // buffer
  23790. const vertices = [];
  23791. const edges = new Set();
  23792. // helper variables
  23793. const start = new Vector3();
  23794. const end = new Vector3();
  23795. if ( geometry.index !== null ) {
  23796. // indexed BufferGeometry
  23797. const position = geometry.attributes.position;
  23798. const indices = geometry.index;
  23799. let groups = geometry.groups;
  23800. if ( groups.length === 0 ) {
  23801. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  23802. }
  23803. // create a data structure that contains all edges without duplicates
  23804. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  23805. const group = groups[ o ];
  23806. const groupStart = group.start;
  23807. const groupCount = group.count;
  23808. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  23809. for ( let j = 0; j < 3; j ++ ) {
  23810. const index1 = indices.getX( i + j );
  23811. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  23812. start.fromBufferAttribute( position, index1 );
  23813. end.fromBufferAttribute( position, index2 );
  23814. if ( isUniqueEdge( start, end, edges ) === true ) {
  23815. vertices.push( start.x, start.y, start.z );
  23816. vertices.push( end.x, end.y, end.z );
  23817. }
  23818. }
  23819. }
  23820. }
  23821. } else {
  23822. // non-indexed BufferGeometry
  23823. const position = geometry.attributes.position;
  23824. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  23825. for ( let j = 0; j < 3; j ++ ) {
  23826. // three edges per triangle, an edge is represented as (index1, index2)
  23827. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  23828. const index1 = 3 * i + j;
  23829. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  23830. start.fromBufferAttribute( position, index1 );
  23831. end.fromBufferAttribute( position, index2 );
  23832. if ( isUniqueEdge( start, end, edges ) === true ) {
  23833. vertices.push( start.x, start.y, start.z );
  23834. vertices.push( end.x, end.y, end.z );
  23835. }
  23836. }
  23837. }
  23838. }
  23839. // build geometry
  23840. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23841. }
  23842. }
  23843. copy( source ) {
  23844. super.copy( source );
  23845. this.parameters = Object.assign( {}, source.parameters );
  23846. return this;
  23847. }
  23848. }
  23849. function isUniqueEdge( start, end, edges ) {
  23850. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  23851. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  23852. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  23853. return false;
  23854. } else {
  23855. edges.add( hash1 );
  23856. edges.add( hash2 );
  23857. return true;
  23858. }
  23859. }
  23860. var Geometries = /*#__PURE__*/Object.freeze({
  23861. __proto__: null,
  23862. BoxGeometry: BoxGeometry,
  23863. CapsuleGeometry: CapsuleGeometry,
  23864. CircleGeometry: CircleGeometry,
  23865. ConeGeometry: ConeGeometry,
  23866. CylinderGeometry: CylinderGeometry,
  23867. DodecahedronGeometry: DodecahedronGeometry,
  23868. EdgesGeometry: EdgesGeometry,
  23869. ExtrudeGeometry: ExtrudeGeometry,
  23870. IcosahedronGeometry: IcosahedronGeometry,
  23871. LatheGeometry: LatheGeometry,
  23872. OctahedronGeometry: OctahedronGeometry,
  23873. PlaneGeometry: PlaneGeometry,
  23874. PolyhedronGeometry: PolyhedronGeometry,
  23875. RingGeometry: RingGeometry,
  23876. ShapeGeometry: ShapeGeometry,
  23877. SphereGeometry: SphereGeometry,
  23878. TetrahedronGeometry: TetrahedronGeometry,
  23879. TorusGeometry: TorusGeometry,
  23880. TorusKnotGeometry: TorusKnotGeometry,
  23881. TubeGeometry: TubeGeometry,
  23882. WireframeGeometry: WireframeGeometry
  23883. });
  23884. class ShadowMaterial extends Material {
  23885. constructor( parameters ) {
  23886. super();
  23887. this.isShadowMaterial = true;
  23888. this.type = 'ShadowMaterial';
  23889. this.color = new Color( 0x000000 );
  23890. this.transparent = true;
  23891. this.fog = true;
  23892. this.setValues( parameters );
  23893. }
  23894. copy( source ) {
  23895. super.copy( source );
  23896. this.color.copy( source.color );
  23897. this.fog = source.fog;
  23898. return this;
  23899. }
  23900. }
  23901. class RawShaderMaterial extends ShaderMaterial {
  23902. constructor( parameters ) {
  23903. super( parameters );
  23904. this.isRawShaderMaterial = true;
  23905. this.type = 'RawShaderMaterial';
  23906. }
  23907. }
  23908. class MeshStandardMaterial extends Material {
  23909. constructor( parameters ) {
  23910. super();
  23911. this.isMeshStandardMaterial = true;
  23912. this.defines = { 'STANDARD': '' };
  23913. this.type = 'MeshStandardMaterial';
  23914. this.color = new Color( 0xffffff ); // diffuse
  23915. this.roughness = 1.0;
  23916. this.metalness = 0.0;
  23917. this.map = null;
  23918. this.lightMap = null;
  23919. this.lightMapIntensity = 1.0;
  23920. this.aoMap = null;
  23921. this.aoMapIntensity = 1.0;
  23922. this.emissive = new Color( 0x000000 );
  23923. this.emissiveIntensity = 1.0;
  23924. this.emissiveMap = null;
  23925. this.bumpMap = null;
  23926. this.bumpScale = 1;
  23927. this.normalMap = null;
  23928. this.normalMapType = TangentSpaceNormalMap;
  23929. this.normalScale = new Vector2( 1, 1 );
  23930. this.displacementMap = null;
  23931. this.displacementScale = 1;
  23932. this.displacementBias = 0;
  23933. this.roughnessMap = null;
  23934. this.metalnessMap = null;
  23935. this.alphaMap = null;
  23936. this.envMap = null;
  23937. this.envMapRotation = new Euler();
  23938. this.envMapIntensity = 1.0;
  23939. this.wireframe = false;
  23940. this.wireframeLinewidth = 1;
  23941. this.wireframeLinecap = 'round';
  23942. this.wireframeLinejoin = 'round';
  23943. this.flatShading = false;
  23944. this.fog = true;
  23945. this.setValues( parameters );
  23946. }
  23947. copy( source ) {
  23948. super.copy( source );
  23949. this.defines = { 'STANDARD': '' };
  23950. this.color.copy( source.color );
  23951. this.roughness = source.roughness;
  23952. this.metalness = source.metalness;
  23953. this.map = source.map;
  23954. this.lightMap = source.lightMap;
  23955. this.lightMapIntensity = source.lightMapIntensity;
  23956. this.aoMap = source.aoMap;
  23957. this.aoMapIntensity = source.aoMapIntensity;
  23958. this.emissive.copy( source.emissive );
  23959. this.emissiveMap = source.emissiveMap;
  23960. this.emissiveIntensity = source.emissiveIntensity;
  23961. this.bumpMap = source.bumpMap;
  23962. this.bumpScale = source.bumpScale;
  23963. this.normalMap = source.normalMap;
  23964. this.normalMapType = source.normalMapType;
  23965. this.normalScale.copy( source.normalScale );
  23966. this.displacementMap = source.displacementMap;
  23967. this.displacementScale = source.displacementScale;
  23968. this.displacementBias = source.displacementBias;
  23969. this.roughnessMap = source.roughnessMap;
  23970. this.metalnessMap = source.metalnessMap;
  23971. this.alphaMap = source.alphaMap;
  23972. this.envMap = source.envMap;
  23973. this.envMapRotation.copy( source.envMapRotation );
  23974. this.envMapIntensity = source.envMapIntensity;
  23975. this.wireframe = source.wireframe;
  23976. this.wireframeLinewidth = source.wireframeLinewidth;
  23977. this.wireframeLinecap = source.wireframeLinecap;
  23978. this.wireframeLinejoin = source.wireframeLinejoin;
  23979. this.flatShading = source.flatShading;
  23980. this.fog = source.fog;
  23981. return this;
  23982. }
  23983. }
  23984. class MeshPhysicalMaterial extends MeshStandardMaterial {
  23985. constructor( parameters ) {
  23986. super();
  23987. this.isMeshPhysicalMaterial = true;
  23988. this.defines = {
  23989. 'STANDARD': '',
  23990. 'PHYSICAL': ''
  23991. };
  23992. this.type = 'MeshPhysicalMaterial';
  23993. this.anisotropyRotation = 0;
  23994. this.anisotropyMap = null;
  23995. this.clearcoatMap = null;
  23996. this.clearcoatRoughness = 0.0;
  23997. this.clearcoatRoughnessMap = null;
  23998. this.clearcoatNormalScale = new Vector2( 1, 1 );
  23999. this.clearcoatNormalMap = null;
  24000. this.ior = 1.5;
  24001. Object.defineProperty( this, 'reflectivity', {
  24002. get: function () {
  24003. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  24004. },
  24005. set: function ( reflectivity ) {
  24006. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  24007. }
  24008. } );
  24009. this.iridescenceMap = null;
  24010. this.iridescenceIOR = 1.3;
  24011. this.iridescenceThicknessRange = [ 100, 400 ];
  24012. this.iridescenceThicknessMap = null;
  24013. this.sheenColor = new Color( 0x000000 );
  24014. this.sheenColorMap = null;
  24015. this.sheenRoughness = 1.0;
  24016. this.sheenRoughnessMap = null;
  24017. this.transmissionMap = null;
  24018. this.thickness = 0;
  24019. this.thicknessMap = null;
  24020. this.attenuationDistance = Infinity;
  24021. this.attenuationColor = new Color( 1, 1, 1 );
  24022. this.specularIntensity = 1.0;
  24023. this.specularIntensityMap = null;
  24024. this.specularColor = new Color( 1, 1, 1 );
  24025. this.specularColorMap = null;
  24026. this._anisotropy = 0;
  24027. this._clearcoat = 0;
  24028. this._iridescence = 0;
  24029. this._sheen = 0.0;
  24030. this._transmission = 0;
  24031. this.setValues( parameters );
  24032. }
  24033. get anisotropy() {
  24034. return this._anisotropy;
  24035. }
  24036. set anisotropy( value ) {
  24037. if ( this._anisotropy > 0 !== value > 0 ) {
  24038. this.version ++;
  24039. }
  24040. this._anisotropy = value;
  24041. }
  24042. get clearcoat() {
  24043. return this._clearcoat;
  24044. }
  24045. set clearcoat( value ) {
  24046. if ( this._clearcoat > 0 !== value > 0 ) {
  24047. this.version ++;
  24048. }
  24049. this._clearcoat = value;
  24050. }
  24051. get iridescence() {
  24052. return this._iridescence;
  24053. }
  24054. set iridescence( value ) {
  24055. if ( this._iridescence > 0 !== value > 0 ) {
  24056. this.version ++;
  24057. }
  24058. this._iridescence = value;
  24059. }
  24060. get sheen() {
  24061. return this._sheen;
  24062. }
  24063. set sheen( value ) {
  24064. if ( this._sheen > 0 !== value > 0 ) {
  24065. this.version ++;
  24066. }
  24067. this._sheen = value;
  24068. }
  24069. get transmission() {
  24070. return this._transmission;
  24071. }
  24072. set transmission( value ) {
  24073. if ( this._transmission > 0 !== value > 0 ) {
  24074. this.version ++;
  24075. }
  24076. this._transmission = value;
  24077. }
  24078. copy( source ) {
  24079. super.copy( source );
  24080. this.defines = {
  24081. 'STANDARD': '',
  24082. 'PHYSICAL': ''
  24083. };
  24084. this.anisotropy = source.anisotropy;
  24085. this.anisotropyRotation = source.anisotropyRotation;
  24086. this.anisotropyMap = source.anisotropyMap;
  24087. this.clearcoat = source.clearcoat;
  24088. this.clearcoatMap = source.clearcoatMap;
  24089. this.clearcoatRoughness = source.clearcoatRoughness;
  24090. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  24091. this.clearcoatNormalMap = source.clearcoatNormalMap;
  24092. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  24093. this.ior = source.ior;
  24094. this.iridescence = source.iridescence;
  24095. this.iridescenceMap = source.iridescenceMap;
  24096. this.iridescenceIOR = source.iridescenceIOR;
  24097. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  24098. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  24099. this.sheen = source.sheen;
  24100. this.sheenColor.copy( source.sheenColor );
  24101. this.sheenColorMap = source.sheenColorMap;
  24102. this.sheenRoughness = source.sheenRoughness;
  24103. this.sheenRoughnessMap = source.sheenRoughnessMap;
  24104. this.transmission = source.transmission;
  24105. this.transmissionMap = source.transmissionMap;
  24106. this.thickness = source.thickness;
  24107. this.thicknessMap = source.thicknessMap;
  24108. this.attenuationDistance = source.attenuationDistance;
  24109. this.attenuationColor.copy( source.attenuationColor );
  24110. this.specularIntensity = source.specularIntensity;
  24111. this.specularIntensityMap = source.specularIntensityMap;
  24112. this.specularColor.copy( source.specularColor );
  24113. this.specularColorMap = source.specularColorMap;
  24114. return this;
  24115. }
  24116. }
  24117. class MeshPhongMaterial extends Material {
  24118. constructor( parameters ) {
  24119. super();
  24120. this.isMeshPhongMaterial = true;
  24121. this.type = 'MeshPhongMaterial';
  24122. this.color = new Color( 0xffffff ); // diffuse
  24123. this.specular = new Color( 0x111111 );
  24124. this.shininess = 30;
  24125. this.map = null;
  24126. this.lightMap = null;
  24127. this.lightMapIntensity = 1.0;
  24128. this.aoMap = null;
  24129. this.aoMapIntensity = 1.0;
  24130. this.emissive = new Color( 0x000000 );
  24131. this.emissiveIntensity = 1.0;
  24132. this.emissiveMap = null;
  24133. this.bumpMap = null;
  24134. this.bumpScale = 1;
  24135. this.normalMap = null;
  24136. this.normalMapType = TangentSpaceNormalMap;
  24137. this.normalScale = new Vector2( 1, 1 );
  24138. this.displacementMap = null;
  24139. this.displacementScale = 1;
  24140. this.displacementBias = 0;
  24141. this.specularMap = null;
  24142. this.alphaMap = null;
  24143. this.envMap = null;
  24144. this.envMapRotation = new Euler();
  24145. this.combine = MultiplyOperation;
  24146. this.reflectivity = 1;
  24147. this.refractionRatio = 0.98;
  24148. this.wireframe = false;
  24149. this.wireframeLinewidth = 1;
  24150. this.wireframeLinecap = 'round';
  24151. this.wireframeLinejoin = 'round';
  24152. this.flatShading = false;
  24153. this.fog = true;
  24154. this.setValues( parameters );
  24155. }
  24156. copy( source ) {
  24157. super.copy( source );
  24158. this.color.copy( source.color );
  24159. this.specular.copy( source.specular );
  24160. this.shininess = source.shininess;
  24161. this.map = source.map;
  24162. this.lightMap = source.lightMap;
  24163. this.lightMapIntensity = source.lightMapIntensity;
  24164. this.aoMap = source.aoMap;
  24165. this.aoMapIntensity = source.aoMapIntensity;
  24166. this.emissive.copy( source.emissive );
  24167. this.emissiveMap = source.emissiveMap;
  24168. this.emissiveIntensity = source.emissiveIntensity;
  24169. this.bumpMap = source.bumpMap;
  24170. this.bumpScale = source.bumpScale;
  24171. this.normalMap = source.normalMap;
  24172. this.normalMapType = source.normalMapType;
  24173. this.normalScale.copy( source.normalScale );
  24174. this.displacementMap = source.displacementMap;
  24175. this.displacementScale = source.displacementScale;
  24176. this.displacementBias = source.displacementBias;
  24177. this.specularMap = source.specularMap;
  24178. this.alphaMap = source.alphaMap;
  24179. this.envMap = source.envMap;
  24180. this.envMapRotation.copy( source.envMapRotation );
  24181. this.combine = source.combine;
  24182. this.reflectivity = source.reflectivity;
  24183. this.refractionRatio = source.refractionRatio;
  24184. this.wireframe = source.wireframe;
  24185. this.wireframeLinewidth = source.wireframeLinewidth;
  24186. this.wireframeLinecap = source.wireframeLinecap;
  24187. this.wireframeLinejoin = source.wireframeLinejoin;
  24188. this.flatShading = source.flatShading;
  24189. this.fog = source.fog;
  24190. return this;
  24191. }
  24192. }
  24193. class MeshToonMaterial extends Material {
  24194. constructor( parameters ) {
  24195. super();
  24196. this.isMeshToonMaterial = true;
  24197. this.defines = { 'TOON': '' };
  24198. this.type = 'MeshToonMaterial';
  24199. this.color = new Color( 0xffffff );
  24200. this.map = null;
  24201. this.gradientMap = null;
  24202. this.lightMap = null;
  24203. this.lightMapIntensity = 1.0;
  24204. this.aoMap = null;
  24205. this.aoMapIntensity = 1.0;
  24206. this.emissive = new Color( 0x000000 );
  24207. this.emissiveIntensity = 1.0;
  24208. this.emissiveMap = null;
  24209. this.bumpMap = null;
  24210. this.bumpScale = 1;
  24211. this.normalMap = null;
  24212. this.normalMapType = TangentSpaceNormalMap;
  24213. this.normalScale = new Vector2( 1, 1 );
  24214. this.displacementMap = null;
  24215. this.displacementScale = 1;
  24216. this.displacementBias = 0;
  24217. this.alphaMap = null;
  24218. this.wireframe = false;
  24219. this.wireframeLinewidth = 1;
  24220. this.wireframeLinecap = 'round';
  24221. this.wireframeLinejoin = 'round';
  24222. this.fog = true;
  24223. this.setValues( parameters );
  24224. }
  24225. copy( source ) {
  24226. super.copy( source );
  24227. this.color.copy( source.color );
  24228. this.map = source.map;
  24229. this.gradientMap = source.gradientMap;
  24230. this.lightMap = source.lightMap;
  24231. this.lightMapIntensity = source.lightMapIntensity;
  24232. this.aoMap = source.aoMap;
  24233. this.aoMapIntensity = source.aoMapIntensity;
  24234. this.emissive.copy( source.emissive );
  24235. this.emissiveMap = source.emissiveMap;
  24236. this.emissiveIntensity = source.emissiveIntensity;
  24237. this.bumpMap = source.bumpMap;
  24238. this.bumpScale = source.bumpScale;
  24239. this.normalMap = source.normalMap;
  24240. this.normalMapType = source.normalMapType;
  24241. this.normalScale.copy( source.normalScale );
  24242. this.displacementMap = source.displacementMap;
  24243. this.displacementScale = source.displacementScale;
  24244. this.displacementBias = source.displacementBias;
  24245. this.alphaMap = source.alphaMap;
  24246. this.wireframe = source.wireframe;
  24247. this.wireframeLinewidth = source.wireframeLinewidth;
  24248. this.wireframeLinecap = source.wireframeLinecap;
  24249. this.wireframeLinejoin = source.wireframeLinejoin;
  24250. this.fog = source.fog;
  24251. return this;
  24252. }
  24253. }
  24254. class MeshNormalMaterial extends Material {
  24255. constructor( parameters ) {
  24256. super();
  24257. this.isMeshNormalMaterial = true;
  24258. this.type = 'MeshNormalMaterial';
  24259. this.bumpMap = null;
  24260. this.bumpScale = 1;
  24261. this.normalMap = null;
  24262. this.normalMapType = TangentSpaceNormalMap;
  24263. this.normalScale = new Vector2( 1, 1 );
  24264. this.displacementMap = null;
  24265. this.displacementScale = 1;
  24266. this.displacementBias = 0;
  24267. this.wireframe = false;
  24268. this.wireframeLinewidth = 1;
  24269. this.flatShading = false;
  24270. this.setValues( parameters );
  24271. }
  24272. copy( source ) {
  24273. super.copy( source );
  24274. this.bumpMap = source.bumpMap;
  24275. this.bumpScale = source.bumpScale;
  24276. this.normalMap = source.normalMap;
  24277. this.normalMapType = source.normalMapType;
  24278. this.normalScale.copy( source.normalScale );
  24279. this.displacementMap = source.displacementMap;
  24280. this.displacementScale = source.displacementScale;
  24281. this.displacementBias = source.displacementBias;
  24282. this.wireframe = source.wireframe;
  24283. this.wireframeLinewidth = source.wireframeLinewidth;
  24284. this.flatShading = source.flatShading;
  24285. return this;
  24286. }
  24287. }
  24288. class MeshLambertMaterial extends Material {
  24289. constructor( parameters ) {
  24290. super();
  24291. this.isMeshLambertMaterial = true;
  24292. this.type = 'MeshLambertMaterial';
  24293. this.color = new Color( 0xffffff ); // diffuse
  24294. this.map = null;
  24295. this.lightMap = null;
  24296. this.lightMapIntensity = 1.0;
  24297. this.aoMap = null;
  24298. this.aoMapIntensity = 1.0;
  24299. this.emissive = new Color( 0x000000 );
  24300. this.emissiveIntensity = 1.0;
  24301. this.emissiveMap = null;
  24302. this.bumpMap = null;
  24303. this.bumpScale = 1;
  24304. this.normalMap = null;
  24305. this.normalMapType = TangentSpaceNormalMap;
  24306. this.normalScale = new Vector2( 1, 1 );
  24307. this.displacementMap = null;
  24308. this.displacementScale = 1;
  24309. this.displacementBias = 0;
  24310. this.specularMap = null;
  24311. this.alphaMap = null;
  24312. this.envMap = null;
  24313. this.envMapRotation = new Euler();
  24314. this.combine = MultiplyOperation;
  24315. this.reflectivity = 1;
  24316. this.refractionRatio = 0.98;
  24317. this.wireframe = false;
  24318. this.wireframeLinewidth = 1;
  24319. this.wireframeLinecap = 'round';
  24320. this.wireframeLinejoin = 'round';
  24321. this.flatShading = false;
  24322. this.fog = true;
  24323. this.setValues( parameters );
  24324. }
  24325. copy( source ) {
  24326. super.copy( source );
  24327. this.color.copy( source.color );
  24328. this.map = source.map;
  24329. this.lightMap = source.lightMap;
  24330. this.lightMapIntensity = source.lightMapIntensity;
  24331. this.aoMap = source.aoMap;
  24332. this.aoMapIntensity = source.aoMapIntensity;
  24333. this.emissive.copy( source.emissive );
  24334. this.emissiveMap = source.emissiveMap;
  24335. this.emissiveIntensity = source.emissiveIntensity;
  24336. this.bumpMap = source.bumpMap;
  24337. this.bumpScale = source.bumpScale;
  24338. this.normalMap = source.normalMap;
  24339. this.normalMapType = source.normalMapType;
  24340. this.normalScale.copy( source.normalScale );
  24341. this.displacementMap = source.displacementMap;
  24342. this.displacementScale = source.displacementScale;
  24343. this.displacementBias = source.displacementBias;
  24344. this.specularMap = source.specularMap;
  24345. this.alphaMap = source.alphaMap;
  24346. this.envMap = source.envMap;
  24347. this.envMapRotation.copy( source.envMapRotation );
  24348. this.combine = source.combine;
  24349. this.reflectivity = source.reflectivity;
  24350. this.refractionRatio = source.refractionRatio;
  24351. this.wireframe = source.wireframe;
  24352. this.wireframeLinewidth = source.wireframeLinewidth;
  24353. this.wireframeLinecap = source.wireframeLinecap;
  24354. this.wireframeLinejoin = source.wireframeLinejoin;
  24355. this.flatShading = source.flatShading;
  24356. this.fog = source.fog;
  24357. return this;
  24358. }
  24359. }
  24360. class MeshMatcapMaterial extends Material {
  24361. constructor( parameters ) {
  24362. super();
  24363. this.isMeshMatcapMaterial = true;
  24364. this.defines = { 'MATCAP': '' };
  24365. this.type = 'MeshMatcapMaterial';
  24366. this.color = new Color( 0xffffff ); // diffuse
  24367. this.matcap = null;
  24368. this.map = null;
  24369. this.bumpMap = null;
  24370. this.bumpScale = 1;
  24371. this.normalMap = null;
  24372. this.normalMapType = TangentSpaceNormalMap;
  24373. this.normalScale = new Vector2( 1, 1 );
  24374. this.displacementMap = null;
  24375. this.displacementScale = 1;
  24376. this.displacementBias = 0;
  24377. this.alphaMap = null;
  24378. this.flatShading = false;
  24379. this.fog = true;
  24380. this.setValues( parameters );
  24381. }
  24382. copy( source ) {
  24383. super.copy( source );
  24384. this.defines = { 'MATCAP': '' };
  24385. this.color.copy( source.color );
  24386. this.matcap = source.matcap;
  24387. this.map = source.map;
  24388. this.bumpMap = source.bumpMap;
  24389. this.bumpScale = source.bumpScale;
  24390. this.normalMap = source.normalMap;
  24391. this.normalMapType = source.normalMapType;
  24392. this.normalScale.copy( source.normalScale );
  24393. this.displacementMap = source.displacementMap;
  24394. this.displacementScale = source.displacementScale;
  24395. this.displacementBias = source.displacementBias;
  24396. this.alphaMap = source.alphaMap;
  24397. this.flatShading = source.flatShading;
  24398. this.fog = source.fog;
  24399. return this;
  24400. }
  24401. }
  24402. class LineDashedMaterial extends LineBasicMaterial {
  24403. constructor( parameters ) {
  24404. super();
  24405. this.isLineDashedMaterial = true;
  24406. this.type = 'LineDashedMaterial';
  24407. this.scale = 1;
  24408. this.dashSize = 3;
  24409. this.gapSize = 1;
  24410. this.setValues( parameters );
  24411. }
  24412. copy( source ) {
  24413. super.copy( source );
  24414. this.scale = source.scale;
  24415. this.dashSize = source.dashSize;
  24416. this.gapSize = source.gapSize;
  24417. return this;
  24418. }
  24419. }
  24420. // converts an array to a specific type
  24421. function convertArray( array, type, forceClone ) {
  24422. if ( ! array || // let 'undefined' and 'null' pass
  24423. ! forceClone && array.constructor === type ) return array;
  24424. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24425. return new type( array ); // create typed array
  24426. }
  24427. return Array.prototype.slice.call( array ); // create Array
  24428. }
  24429. function isTypedArray( object ) {
  24430. return ArrayBuffer.isView( object ) &&
  24431. ! ( object instanceof DataView );
  24432. }
  24433. // returns an array by which times and values can be sorted
  24434. function getKeyframeOrder( times ) {
  24435. function compareTime( i, j ) {
  24436. return times[ i ] - times[ j ];
  24437. }
  24438. const n = times.length;
  24439. const result = new Array( n );
  24440. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  24441. result.sort( compareTime );
  24442. return result;
  24443. }
  24444. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24445. function sortedArray( values, stride, order ) {
  24446. const nValues = values.length;
  24447. const result = new values.constructor( nValues );
  24448. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24449. const srcOffset = order[ i ] * stride;
  24450. for ( let j = 0; j !== stride; ++ j ) {
  24451. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24452. }
  24453. }
  24454. return result;
  24455. }
  24456. // function for parsing AOS keyframe formats
  24457. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  24458. let i = 1, key = jsonKeys[ 0 ];
  24459. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24460. key = jsonKeys[ i ++ ];
  24461. }
  24462. if ( key === undefined ) return; // no data
  24463. let value = key[ valuePropertyName ];
  24464. if ( value === undefined ) return; // no data
  24465. if ( Array.isArray( value ) ) {
  24466. do {
  24467. value = key[ valuePropertyName ];
  24468. if ( value !== undefined ) {
  24469. times.push( key.time );
  24470. values.push.apply( values, value ); // push all elements
  24471. }
  24472. key = jsonKeys[ i ++ ];
  24473. } while ( key !== undefined );
  24474. } else if ( value.toArray !== undefined ) {
  24475. // ...assume THREE.Math-ish
  24476. do {
  24477. value = key[ valuePropertyName ];
  24478. if ( value !== undefined ) {
  24479. times.push( key.time );
  24480. value.toArray( values, values.length );
  24481. }
  24482. key = jsonKeys[ i ++ ];
  24483. } while ( key !== undefined );
  24484. } else {
  24485. // otherwise push as-is
  24486. do {
  24487. value = key[ valuePropertyName ];
  24488. if ( value !== undefined ) {
  24489. times.push( key.time );
  24490. values.push( value );
  24491. }
  24492. key = jsonKeys[ i ++ ];
  24493. } while ( key !== undefined );
  24494. }
  24495. }
  24496. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  24497. const clip = sourceClip.clone();
  24498. clip.name = name;
  24499. const tracks = [];
  24500. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24501. const track = clip.tracks[ i ];
  24502. const valueSize = track.getValueSize();
  24503. const times = [];
  24504. const values = [];
  24505. for ( let j = 0; j < track.times.length; ++ j ) {
  24506. const frame = track.times[ j ] * fps;
  24507. if ( frame < startFrame || frame >= endFrame ) continue;
  24508. times.push( track.times[ j ] );
  24509. for ( let k = 0; k < valueSize; ++ k ) {
  24510. values.push( track.values[ j * valueSize + k ] );
  24511. }
  24512. }
  24513. if ( times.length === 0 ) continue;
  24514. track.times = convertArray( times, track.times.constructor );
  24515. track.values = convertArray( values, track.values.constructor );
  24516. tracks.push( track );
  24517. }
  24518. clip.tracks = tracks;
  24519. // find minimum .times value across all tracks in the trimmed clip
  24520. let minStartTime = Infinity;
  24521. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24522. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  24523. minStartTime = clip.tracks[ i ].times[ 0 ];
  24524. }
  24525. }
  24526. // shift all tracks such that clip begins at t=0
  24527. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24528. clip.tracks[ i ].shift( - 1 * minStartTime );
  24529. }
  24530. clip.resetDuration();
  24531. return clip;
  24532. }
  24533. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  24534. if ( fps <= 0 ) fps = 30;
  24535. const numTracks = referenceClip.tracks.length;
  24536. const referenceTime = referenceFrame / fps;
  24537. // Make each track's values relative to the values at the reference frame
  24538. for ( let i = 0; i < numTracks; ++ i ) {
  24539. const referenceTrack = referenceClip.tracks[ i ];
  24540. const referenceTrackType = referenceTrack.ValueTypeName;
  24541. // Skip this track if it's non-numeric
  24542. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  24543. // Find the track in the target clip whose name and type matches the reference track
  24544. const targetTrack = targetClip.tracks.find( function ( track ) {
  24545. return track.name === referenceTrack.name
  24546. && track.ValueTypeName === referenceTrackType;
  24547. } );
  24548. if ( targetTrack === undefined ) continue;
  24549. let referenceOffset = 0;
  24550. const referenceValueSize = referenceTrack.getValueSize();
  24551. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24552. referenceOffset = referenceValueSize / 3;
  24553. }
  24554. let targetOffset = 0;
  24555. const targetValueSize = targetTrack.getValueSize();
  24556. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24557. targetOffset = targetValueSize / 3;
  24558. }
  24559. const lastIndex = referenceTrack.times.length - 1;
  24560. let referenceValue;
  24561. // Find the value to subtract out of the track
  24562. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  24563. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  24564. const startIndex = referenceOffset;
  24565. const endIndex = referenceValueSize - referenceOffset;
  24566. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24567. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  24568. // Reference frame is after the last keyframe, so just use the last keyframe
  24569. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  24570. const endIndex = startIndex + referenceValueSize - referenceOffset;
  24571. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24572. } else {
  24573. // Interpolate to the reference value
  24574. const interpolant = referenceTrack.createInterpolant();
  24575. const startIndex = referenceOffset;
  24576. const endIndex = referenceValueSize - referenceOffset;
  24577. interpolant.evaluate( referenceTime );
  24578. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  24579. }
  24580. // Conjugate the quaternion
  24581. if ( referenceTrackType === 'quaternion' ) {
  24582. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  24583. referenceQuat.toArray( referenceValue );
  24584. }
  24585. // Subtract the reference value from all of the track values
  24586. const numTimes = targetTrack.times.length;
  24587. for ( let j = 0; j < numTimes; ++ j ) {
  24588. const valueStart = j * targetValueSize + targetOffset;
  24589. if ( referenceTrackType === 'quaternion' ) {
  24590. // Multiply the conjugate for quaternion track types
  24591. Quaternion.multiplyQuaternionsFlat(
  24592. targetTrack.values,
  24593. valueStart,
  24594. referenceValue,
  24595. 0,
  24596. targetTrack.values,
  24597. valueStart
  24598. );
  24599. } else {
  24600. const valueEnd = targetValueSize - targetOffset * 2;
  24601. // Subtract each value for all other numeric track types
  24602. for ( let k = 0; k < valueEnd; ++ k ) {
  24603. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  24604. }
  24605. }
  24606. }
  24607. }
  24608. targetClip.blendMode = AdditiveAnimationBlendMode;
  24609. return targetClip;
  24610. }
  24611. const AnimationUtils = {
  24612. convertArray: convertArray,
  24613. isTypedArray: isTypedArray,
  24614. getKeyframeOrder: getKeyframeOrder,
  24615. sortedArray: sortedArray,
  24616. flattenJSON: flattenJSON,
  24617. subclip: subclip,
  24618. makeClipAdditive: makeClipAdditive
  24619. };
  24620. /**
  24621. * Abstract base class of interpolants over parametric samples.
  24622. *
  24623. * The parameter domain is one dimensional, typically the time or a path
  24624. * along a curve defined by the data.
  24625. *
  24626. * The sample values can have any dimensionality and derived classes may
  24627. * apply special interpretations to the data.
  24628. *
  24629. * This class provides the interval seek in a Template Method, deferring
  24630. * the actual interpolation to derived classes.
  24631. *
  24632. * Time complexity is O(1) for linear access crossing at most two points
  24633. * and O(log N) for random access, where N is the number of positions.
  24634. *
  24635. * References:
  24636. *
  24637. * http://www.oodesign.com/template-method-pattern.html
  24638. *
  24639. */
  24640. class Interpolant {
  24641. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24642. this.parameterPositions = parameterPositions;
  24643. this._cachedIndex = 0;
  24644. this.resultBuffer = resultBuffer !== undefined ?
  24645. resultBuffer : new sampleValues.constructor( sampleSize );
  24646. this.sampleValues = sampleValues;
  24647. this.valueSize = sampleSize;
  24648. this.settings = null;
  24649. this.DefaultSettings_ = {};
  24650. }
  24651. evaluate( t ) {
  24652. const pp = this.parameterPositions;
  24653. let i1 = this._cachedIndex,
  24654. t1 = pp[ i1 ],
  24655. t0 = pp[ i1 - 1 ];
  24656. validate_interval: {
  24657. seek: {
  24658. let right;
  24659. linear_scan: {
  24660. //- See http://jsperf.com/comparison-to-undefined/3
  24661. //- slower code:
  24662. //-
  24663. //- if ( t >= t1 || t1 === undefined ) {
  24664. forward_scan: if ( ! ( t < t1 ) ) {
  24665. for ( let giveUpAt = i1 + 2; ; ) {
  24666. if ( t1 === undefined ) {
  24667. if ( t < t0 ) break forward_scan;
  24668. // after end
  24669. i1 = pp.length;
  24670. this._cachedIndex = i1;
  24671. return this.copySampleValue_( i1 - 1 );
  24672. }
  24673. if ( i1 === giveUpAt ) break; // this loop
  24674. t0 = t1;
  24675. t1 = pp[ ++ i1 ];
  24676. if ( t < t1 ) {
  24677. // we have arrived at the sought interval
  24678. break seek;
  24679. }
  24680. }
  24681. // prepare binary search on the right side of the index
  24682. right = pp.length;
  24683. break linear_scan;
  24684. }
  24685. //- slower code:
  24686. //- if ( t < t0 || t0 === undefined ) {
  24687. if ( ! ( t >= t0 ) ) {
  24688. // looping?
  24689. const t1global = pp[ 1 ];
  24690. if ( t < t1global ) {
  24691. i1 = 2; // + 1, using the scan for the details
  24692. t0 = t1global;
  24693. }
  24694. // linear reverse scan
  24695. for ( let giveUpAt = i1 - 2; ; ) {
  24696. if ( t0 === undefined ) {
  24697. // before start
  24698. this._cachedIndex = 0;
  24699. return this.copySampleValue_( 0 );
  24700. }
  24701. if ( i1 === giveUpAt ) break; // this loop
  24702. t1 = t0;
  24703. t0 = pp[ -- i1 - 1 ];
  24704. if ( t >= t0 ) {
  24705. // we have arrived at the sought interval
  24706. break seek;
  24707. }
  24708. }
  24709. // prepare binary search on the left side of the index
  24710. right = i1;
  24711. i1 = 0;
  24712. break linear_scan;
  24713. }
  24714. // the interval is valid
  24715. break validate_interval;
  24716. } // linear scan
  24717. // binary search
  24718. while ( i1 < right ) {
  24719. const mid = ( i1 + right ) >>> 1;
  24720. if ( t < pp[ mid ] ) {
  24721. right = mid;
  24722. } else {
  24723. i1 = mid + 1;
  24724. }
  24725. }
  24726. t1 = pp[ i1 ];
  24727. t0 = pp[ i1 - 1 ];
  24728. // check boundary cases, again
  24729. if ( t0 === undefined ) {
  24730. this._cachedIndex = 0;
  24731. return this.copySampleValue_( 0 );
  24732. }
  24733. if ( t1 === undefined ) {
  24734. i1 = pp.length;
  24735. this._cachedIndex = i1;
  24736. return this.copySampleValue_( i1 - 1 );
  24737. }
  24738. } // seek
  24739. this._cachedIndex = i1;
  24740. this.intervalChanged_( i1, t0, t1 );
  24741. } // validate_interval
  24742. return this.interpolate_( i1, t0, t, t1 );
  24743. }
  24744. getSettings_() {
  24745. return this.settings || this.DefaultSettings_;
  24746. }
  24747. copySampleValue_( index ) {
  24748. // copies a sample value to the result buffer
  24749. const result = this.resultBuffer,
  24750. values = this.sampleValues,
  24751. stride = this.valueSize,
  24752. offset = index * stride;
  24753. for ( let i = 0; i !== stride; ++ i ) {
  24754. result[ i ] = values[ offset + i ];
  24755. }
  24756. return result;
  24757. }
  24758. // Template methods for derived classes:
  24759. interpolate_( /* i1, t0, t, t1 */ ) {
  24760. throw new Error( 'call to abstract method' );
  24761. // implementations shall return this.resultBuffer
  24762. }
  24763. intervalChanged_( /* i1, t0, t1 */ ) {
  24764. // empty
  24765. }
  24766. }
  24767. /**
  24768. * Fast and simple cubic spline interpolant.
  24769. *
  24770. * It was derived from a Hermitian construction setting the first derivative
  24771. * at each sample position to the linear slope between neighboring positions
  24772. * over their parameter interval.
  24773. */
  24774. class CubicInterpolant extends Interpolant {
  24775. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24776. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24777. this._weightPrev = - 0;
  24778. this._offsetPrev = - 0;
  24779. this._weightNext = - 0;
  24780. this._offsetNext = - 0;
  24781. this.DefaultSettings_ = {
  24782. endingStart: ZeroCurvatureEnding,
  24783. endingEnd: ZeroCurvatureEnding
  24784. };
  24785. }
  24786. intervalChanged_( i1, t0, t1 ) {
  24787. const pp = this.parameterPositions;
  24788. let iPrev = i1 - 2,
  24789. iNext = i1 + 1,
  24790. tPrev = pp[ iPrev ],
  24791. tNext = pp[ iNext ];
  24792. if ( tPrev === undefined ) {
  24793. switch ( this.getSettings_().endingStart ) {
  24794. case ZeroSlopeEnding:
  24795. // f'(t0) = 0
  24796. iPrev = i1;
  24797. tPrev = 2 * t0 - t1;
  24798. break;
  24799. case WrapAroundEnding:
  24800. // use the other end of the curve
  24801. iPrev = pp.length - 2;
  24802. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24803. break;
  24804. default: // ZeroCurvatureEnding
  24805. // f''(t0) = 0 a.k.a. Natural Spline
  24806. iPrev = i1;
  24807. tPrev = t1;
  24808. }
  24809. }
  24810. if ( tNext === undefined ) {
  24811. switch ( this.getSettings_().endingEnd ) {
  24812. case ZeroSlopeEnding:
  24813. // f'(tN) = 0
  24814. iNext = i1;
  24815. tNext = 2 * t1 - t0;
  24816. break;
  24817. case WrapAroundEnding:
  24818. // use the other end of the curve
  24819. iNext = 1;
  24820. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24821. break;
  24822. default: // ZeroCurvatureEnding
  24823. // f''(tN) = 0, a.k.a. Natural Spline
  24824. iNext = i1 - 1;
  24825. tNext = t0;
  24826. }
  24827. }
  24828. const halfDt = ( t1 - t0 ) * 0.5,
  24829. stride = this.valueSize;
  24830. this._weightPrev = halfDt / ( t0 - tPrev );
  24831. this._weightNext = halfDt / ( tNext - t1 );
  24832. this._offsetPrev = iPrev * stride;
  24833. this._offsetNext = iNext * stride;
  24834. }
  24835. interpolate_( i1, t0, t, t1 ) {
  24836. const result = this.resultBuffer,
  24837. values = this.sampleValues,
  24838. stride = this.valueSize,
  24839. o1 = i1 * stride, o0 = o1 - stride,
  24840. oP = this._offsetPrev, oN = this._offsetNext,
  24841. wP = this._weightPrev, wN = this._weightNext,
  24842. p = ( t - t0 ) / ( t1 - t0 ),
  24843. pp = p * p,
  24844. ppp = pp * p;
  24845. // evaluate polynomials
  24846. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  24847. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24848. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24849. const sN = wN * ppp - wN * pp;
  24850. // combine data linearly
  24851. for ( let i = 0; i !== stride; ++ i ) {
  24852. result[ i ] =
  24853. sP * values[ oP + i ] +
  24854. s0 * values[ o0 + i ] +
  24855. s1 * values[ o1 + i ] +
  24856. sN * values[ oN + i ];
  24857. }
  24858. return result;
  24859. }
  24860. }
  24861. class LinearInterpolant extends Interpolant {
  24862. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24863. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24864. }
  24865. interpolate_( i1, t0, t, t1 ) {
  24866. const result = this.resultBuffer,
  24867. values = this.sampleValues,
  24868. stride = this.valueSize,
  24869. offset1 = i1 * stride,
  24870. offset0 = offset1 - stride,
  24871. weight1 = ( t - t0 ) / ( t1 - t0 ),
  24872. weight0 = 1 - weight1;
  24873. for ( let i = 0; i !== stride; ++ i ) {
  24874. result[ i ] =
  24875. values[ offset0 + i ] * weight0 +
  24876. values[ offset1 + i ] * weight1;
  24877. }
  24878. return result;
  24879. }
  24880. }
  24881. /**
  24882. *
  24883. * Interpolant that evaluates to the sample value at the position preceding
  24884. * the parameter.
  24885. */
  24886. class DiscreteInterpolant extends Interpolant {
  24887. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24888. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24889. }
  24890. interpolate_( i1 /*, t0, t, t1 */ ) {
  24891. return this.copySampleValue_( i1 - 1 );
  24892. }
  24893. }
  24894. class KeyframeTrack {
  24895. constructor( name, times, values, interpolation ) {
  24896. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  24897. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  24898. this.name = name;
  24899. this.times = convertArray( times, this.TimeBufferType );
  24900. this.values = convertArray( values, this.ValueBufferType );
  24901. this.setInterpolation( interpolation || this.DefaultInterpolation );
  24902. }
  24903. // Serialization (in static context, because of constructor invocation
  24904. // and automatic invocation of .toJSON):
  24905. static toJSON( track ) {
  24906. const trackType = track.constructor;
  24907. let json;
  24908. // derived classes can define a static toJSON method
  24909. if ( trackType.toJSON !== this.toJSON ) {
  24910. json = trackType.toJSON( track );
  24911. } else {
  24912. // by default, we assume the data can be serialized as-is
  24913. json = {
  24914. 'name': track.name,
  24915. 'times': convertArray( track.times, Array ),
  24916. 'values': convertArray( track.values, Array )
  24917. };
  24918. const interpolation = track.getInterpolation();
  24919. if ( interpolation !== track.DefaultInterpolation ) {
  24920. json.interpolation = interpolation;
  24921. }
  24922. }
  24923. json.type = track.ValueTypeName; // mandatory
  24924. return json;
  24925. }
  24926. InterpolantFactoryMethodDiscrete( result ) {
  24927. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  24928. }
  24929. InterpolantFactoryMethodLinear( result ) {
  24930. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24931. }
  24932. InterpolantFactoryMethodSmooth( result ) {
  24933. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  24934. }
  24935. setInterpolation( interpolation ) {
  24936. let factoryMethod;
  24937. switch ( interpolation ) {
  24938. case InterpolateDiscrete:
  24939. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  24940. break;
  24941. case InterpolateLinear:
  24942. factoryMethod = this.InterpolantFactoryMethodLinear;
  24943. break;
  24944. case InterpolateSmooth:
  24945. factoryMethod = this.InterpolantFactoryMethodSmooth;
  24946. break;
  24947. }
  24948. if ( factoryMethod === undefined ) {
  24949. const message = 'unsupported interpolation for ' +
  24950. this.ValueTypeName + ' keyframe track named ' + this.name;
  24951. if ( this.createInterpolant === undefined ) {
  24952. // fall back to default, unless the default itself is messed up
  24953. if ( interpolation !== this.DefaultInterpolation ) {
  24954. this.setInterpolation( this.DefaultInterpolation );
  24955. } else {
  24956. throw new Error( message ); // fatal, in this case
  24957. }
  24958. }
  24959. console.warn( 'THREE.KeyframeTrack:', message );
  24960. return this;
  24961. }
  24962. this.createInterpolant = factoryMethod;
  24963. return this;
  24964. }
  24965. getInterpolation() {
  24966. switch ( this.createInterpolant ) {
  24967. case this.InterpolantFactoryMethodDiscrete:
  24968. return InterpolateDiscrete;
  24969. case this.InterpolantFactoryMethodLinear:
  24970. return InterpolateLinear;
  24971. case this.InterpolantFactoryMethodSmooth:
  24972. return InterpolateSmooth;
  24973. }
  24974. }
  24975. getValueSize() {
  24976. return this.values.length / this.times.length;
  24977. }
  24978. // move all keyframes either forwards or backwards in time
  24979. shift( timeOffset ) {
  24980. if ( timeOffset !== 0.0 ) {
  24981. const times = this.times;
  24982. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24983. times[ i ] += timeOffset;
  24984. }
  24985. }
  24986. return this;
  24987. }
  24988. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  24989. scale( timeScale ) {
  24990. if ( timeScale !== 1.0 ) {
  24991. const times = this.times;
  24992. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24993. times[ i ] *= timeScale;
  24994. }
  24995. }
  24996. return this;
  24997. }
  24998. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  24999. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25000. trim( startTime, endTime ) {
  25001. const times = this.times,
  25002. nKeys = times.length;
  25003. let from = 0,
  25004. to = nKeys - 1;
  25005. while ( from !== nKeys && times[ from ] < startTime ) {
  25006. ++ from;
  25007. }
  25008. while ( to !== - 1 && times[ to ] > endTime ) {
  25009. -- to;
  25010. }
  25011. ++ to; // inclusive -> exclusive bound
  25012. if ( from !== 0 || to !== nKeys ) {
  25013. // empty tracks are forbidden, so keep at least one keyframe
  25014. if ( from >= to ) {
  25015. to = Math.max( to, 1 );
  25016. from = to - 1;
  25017. }
  25018. const stride = this.getValueSize();
  25019. this.times = times.slice( from, to );
  25020. this.values = this.values.slice( from * stride, to * stride );
  25021. }
  25022. return this;
  25023. }
  25024. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25025. validate() {
  25026. let valid = true;
  25027. const valueSize = this.getValueSize();
  25028. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25029. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25030. valid = false;
  25031. }
  25032. const times = this.times,
  25033. values = this.values,
  25034. nKeys = times.length;
  25035. if ( nKeys === 0 ) {
  25036. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25037. valid = false;
  25038. }
  25039. let prevTime = null;
  25040. for ( let i = 0; i !== nKeys; i ++ ) {
  25041. const currTime = times[ i ];
  25042. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25043. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25044. valid = false;
  25045. break;
  25046. }
  25047. if ( prevTime !== null && prevTime > currTime ) {
  25048. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25049. valid = false;
  25050. break;
  25051. }
  25052. prevTime = currTime;
  25053. }
  25054. if ( values !== undefined ) {
  25055. if ( isTypedArray( values ) ) {
  25056. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  25057. const value = values[ i ];
  25058. if ( isNaN( value ) ) {
  25059. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25060. valid = false;
  25061. break;
  25062. }
  25063. }
  25064. }
  25065. }
  25066. return valid;
  25067. }
  25068. // removes equivalent sequential keys as common in morph target sequences
  25069. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25070. optimize() {
  25071. // times or values may be shared with other tracks, so overwriting is unsafe
  25072. const times = this.times.slice(),
  25073. values = this.values.slice(),
  25074. stride = this.getValueSize(),
  25075. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25076. lastIndex = times.length - 1;
  25077. let writeIndex = 1;
  25078. for ( let i = 1; i < lastIndex; ++ i ) {
  25079. let keep = false;
  25080. const time = times[ i ];
  25081. const timeNext = times[ i + 1 ];
  25082. // remove adjacent keyframes scheduled at the same time
  25083. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  25084. if ( ! smoothInterpolation ) {
  25085. // remove unnecessary keyframes same as their neighbors
  25086. const offset = i * stride,
  25087. offsetP = offset - stride,
  25088. offsetN = offset + stride;
  25089. for ( let j = 0; j !== stride; ++ j ) {
  25090. const value = values[ offset + j ];
  25091. if ( value !== values[ offsetP + j ] ||
  25092. value !== values[ offsetN + j ] ) {
  25093. keep = true;
  25094. break;
  25095. }
  25096. }
  25097. } else {
  25098. keep = true;
  25099. }
  25100. }
  25101. // in-place compaction
  25102. if ( keep ) {
  25103. if ( i !== writeIndex ) {
  25104. times[ writeIndex ] = times[ i ];
  25105. const readOffset = i * stride,
  25106. writeOffset = writeIndex * stride;
  25107. for ( let j = 0; j !== stride; ++ j ) {
  25108. values[ writeOffset + j ] = values[ readOffset + j ];
  25109. }
  25110. }
  25111. ++ writeIndex;
  25112. }
  25113. }
  25114. // flush last keyframe (compaction looks ahead)
  25115. if ( lastIndex > 0 ) {
  25116. times[ writeIndex ] = times[ lastIndex ];
  25117. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25118. values[ writeOffset + j ] = values[ readOffset + j ];
  25119. }
  25120. ++ writeIndex;
  25121. }
  25122. if ( writeIndex !== times.length ) {
  25123. this.times = times.slice( 0, writeIndex );
  25124. this.values = values.slice( 0, writeIndex * stride );
  25125. } else {
  25126. this.times = times;
  25127. this.values = values;
  25128. }
  25129. return this;
  25130. }
  25131. clone() {
  25132. const times = this.times.slice();
  25133. const values = this.values.slice();
  25134. const TypedKeyframeTrack = this.constructor;
  25135. const track = new TypedKeyframeTrack( this.name, times, values );
  25136. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  25137. track.createInterpolant = this.createInterpolant;
  25138. return track;
  25139. }
  25140. }
  25141. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  25142. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  25143. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25144. /**
  25145. * A Track of Boolean keyframe values.
  25146. */
  25147. class BooleanKeyframeTrack extends KeyframeTrack {}
  25148. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  25149. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  25150. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25151. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25152. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25153. /**
  25154. * A Track of keyframe values that represent color.
  25155. */
  25156. class ColorKeyframeTrack extends KeyframeTrack {}
  25157. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  25158. /**
  25159. * A Track of numeric keyframe values.
  25160. */
  25161. class NumberKeyframeTrack extends KeyframeTrack {}
  25162. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  25163. /**
  25164. * Spherical linear unit quaternion interpolant.
  25165. */
  25166. class QuaternionLinearInterpolant extends Interpolant {
  25167. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25168. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25169. }
  25170. interpolate_( i1, t0, t, t1 ) {
  25171. const result = this.resultBuffer,
  25172. values = this.sampleValues,
  25173. stride = this.valueSize,
  25174. alpha = ( t - t0 ) / ( t1 - t0 );
  25175. let offset = i1 * stride;
  25176. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  25177. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25178. }
  25179. return result;
  25180. }
  25181. }
  25182. /**
  25183. * A Track of quaternion keyframe values.
  25184. */
  25185. class QuaternionKeyframeTrack extends KeyframeTrack {
  25186. InterpolantFactoryMethodLinear( result ) {
  25187. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25188. }
  25189. }
  25190. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  25191. // ValueBufferType is inherited
  25192. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25193. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25194. /**
  25195. * A Track that interpolates Strings
  25196. */
  25197. class StringKeyframeTrack extends KeyframeTrack {}
  25198. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  25199. StringKeyframeTrack.prototype.ValueBufferType = Array;
  25200. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25201. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25202. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25203. /**
  25204. * A Track of vectored keyframe values.
  25205. */
  25206. class VectorKeyframeTrack extends KeyframeTrack {}
  25207. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  25208. class AnimationClip {
  25209. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  25210. this.name = name;
  25211. this.tracks = tracks;
  25212. this.duration = duration;
  25213. this.blendMode = blendMode;
  25214. this.uuid = generateUUID();
  25215. // this means it should figure out its duration by scanning the tracks
  25216. if ( this.duration < 0 ) {
  25217. this.resetDuration();
  25218. }
  25219. }
  25220. static parse( json ) {
  25221. const tracks = [],
  25222. jsonTracks = json.tracks,
  25223. frameTime = 1.0 / ( json.fps || 1.0 );
  25224. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25225. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25226. }
  25227. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  25228. clip.uuid = json.uuid;
  25229. return clip;
  25230. }
  25231. static toJSON( clip ) {
  25232. const tracks = [],
  25233. clipTracks = clip.tracks;
  25234. const json = {
  25235. 'name': clip.name,
  25236. 'duration': clip.duration,
  25237. 'tracks': tracks,
  25238. 'uuid': clip.uuid,
  25239. 'blendMode': clip.blendMode
  25240. };
  25241. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25242. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25243. }
  25244. return json;
  25245. }
  25246. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  25247. const numMorphTargets = morphTargetSequence.length;
  25248. const tracks = [];
  25249. for ( let i = 0; i < numMorphTargets; i ++ ) {
  25250. let times = [];
  25251. let values = [];
  25252. times.push(
  25253. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25254. i,
  25255. ( i + 1 ) % numMorphTargets );
  25256. values.push( 0, 1, 0 );
  25257. const order = getKeyframeOrder( times );
  25258. times = sortedArray( times, 1, order );
  25259. values = sortedArray( values, 1, order );
  25260. // if there is a key at the first frame, duplicate it as the
  25261. // last frame as well for perfect loop.
  25262. if ( ! noLoop && times[ 0 ] === 0 ) {
  25263. times.push( numMorphTargets );
  25264. values.push( values[ 0 ] );
  25265. }
  25266. tracks.push(
  25267. new NumberKeyframeTrack(
  25268. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25269. times, values
  25270. ).scale( 1.0 / fps ) );
  25271. }
  25272. return new this( name, - 1, tracks );
  25273. }
  25274. static findByName( objectOrClipArray, name ) {
  25275. let clipArray = objectOrClipArray;
  25276. if ( ! Array.isArray( objectOrClipArray ) ) {
  25277. const o = objectOrClipArray;
  25278. clipArray = o.geometry && o.geometry.animations || o.animations;
  25279. }
  25280. for ( let i = 0; i < clipArray.length; i ++ ) {
  25281. if ( clipArray[ i ].name === name ) {
  25282. return clipArray[ i ];
  25283. }
  25284. }
  25285. return null;
  25286. }
  25287. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  25288. const animationToMorphTargets = {};
  25289. // tested with https://regex101.com/ on trick sequences
  25290. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25291. const pattern = /^([\w-]*?)([\d]+)$/;
  25292. // sort morph target names into animation groups based
  25293. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25294. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  25295. const morphTarget = morphTargets[ i ];
  25296. const parts = morphTarget.name.match( pattern );
  25297. if ( parts && parts.length > 1 ) {
  25298. const name = parts[ 1 ];
  25299. let animationMorphTargets = animationToMorphTargets[ name ];
  25300. if ( ! animationMorphTargets ) {
  25301. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25302. }
  25303. animationMorphTargets.push( morphTarget );
  25304. }
  25305. }
  25306. const clips = [];
  25307. for ( const name in animationToMorphTargets ) {
  25308. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25309. }
  25310. return clips;
  25311. }
  25312. // parse the animation.hierarchy format
  25313. static parseAnimation( animation, bones ) {
  25314. if ( ! animation ) {
  25315. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25316. return null;
  25317. }
  25318. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25319. // only return track if there are actually keys.
  25320. if ( animationKeys.length !== 0 ) {
  25321. const times = [];
  25322. const values = [];
  25323. flattenJSON( animationKeys, times, values, propertyName );
  25324. // empty keys are filtered out, so check again
  25325. if ( times.length !== 0 ) {
  25326. destTracks.push( new trackType( trackName, times, values ) );
  25327. }
  25328. }
  25329. };
  25330. const tracks = [];
  25331. const clipName = animation.name || 'default';
  25332. const fps = animation.fps || 30;
  25333. const blendMode = animation.blendMode;
  25334. // automatic length determination in AnimationClip.
  25335. let duration = animation.length || - 1;
  25336. const hierarchyTracks = animation.hierarchy || [];
  25337. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  25338. const animationKeys = hierarchyTracks[ h ].keys;
  25339. // skip empty tracks
  25340. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25341. // process morph targets
  25342. if ( animationKeys[ 0 ].morphTargets ) {
  25343. // figure out all morph targets used in this track
  25344. const morphTargetNames = {};
  25345. let k;
  25346. for ( k = 0; k < animationKeys.length; k ++ ) {
  25347. if ( animationKeys[ k ].morphTargets ) {
  25348. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25349. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25350. }
  25351. }
  25352. }
  25353. // create a track for each morph target with all zero
  25354. // morphTargetInfluences except for the keys in which
  25355. // the morphTarget is named.
  25356. for ( const morphTargetName in morphTargetNames ) {
  25357. const times = [];
  25358. const values = [];
  25359. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25360. const animationKey = animationKeys[ k ];
  25361. times.push( animationKey.time );
  25362. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25363. }
  25364. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25365. }
  25366. duration = morphTargetNames.length * fps;
  25367. } else {
  25368. // ...assume skeletal animation
  25369. const boneName = '.bones[' + bones[ h ].name + ']';
  25370. addNonemptyTrack(
  25371. VectorKeyframeTrack, boneName + '.position',
  25372. animationKeys, 'pos', tracks );
  25373. addNonemptyTrack(
  25374. QuaternionKeyframeTrack, boneName + '.quaternion',
  25375. animationKeys, 'rot', tracks );
  25376. addNonemptyTrack(
  25377. VectorKeyframeTrack, boneName + '.scale',
  25378. animationKeys, 'scl', tracks );
  25379. }
  25380. }
  25381. if ( tracks.length === 0 ) {
  25382. return null;
  25383. }
  25384. const clip = new this( clipName, duration, tracks, blendMode );
  25385. return clip;
  25386. }
  25387. resetDuration() {
  25388. const tracks = this.tracks;
  25389. let duration = 0;
  25390. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  25391. const track = this.tracks[ i ];
  25392. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25393. }
  25394. this.duration = duration;
  25395. return this;
  25396. }
  25397. trim() {
  25398. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25399. this.tracks[ i ].trim( 0, this.duration );
  25400. }
  25401. return this;
  25402. }
  25403. validate() {
  25404. let valid = true;
  25405. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25406. valid = valid && this.tracks[ i ].validate();
  25407. }
  25408. return valid;
  25409. }
  25410. optimize() {
  25411. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25412. this.tracks[ i ].optimize();
  25413. }
  25414. return this;
  25415. }
  25416. clone() {
  25417. const tracks = [];
  25418. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25419. tracks.push( this.tracks[ i ].clone() );
  25420. }
  25421. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  25422. }
  25423. toJSON() {
  25424. return this.constructor.toJSON( this );
  25425. }
  25426. }
  25427. function getTrackTypeForValueTypeName( typeName ) {
  25428. switch ( typeName.toLowerCase() ) {
  25429. case 'scalar':
  25430. case 'double':
  25431. case 'float':
  25432. case 'number':
  25433. case 'integer':
  25434. return NumberKeyframeTrack;
  25435. case 'vector':
  25436. case 'vector2':
  25437. case 'vector3':
  25438. case 'vector4':
  25439. return VectorKeyframeTrack;
  25440. case 'color':
  25441. return ColorKeyframeTrack;
  25442. case 'quaternion':
  25443. return QuaternionKeyframeTrack;
  25444. case 'bool':
  25445. case 'boolean':
  25446. return BooleanKeyframeTrack;
  25447. case 'string':
  25448. return StringKeyframeTrack;
  25449. }
  25450. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25451. }
  25452. function parseKeyframeTrack( json ) {
  25453. if ( json.type === undefined ) {
  25454. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25455. }
  25456. const trackType = getTrackTypeForValueTypeName( json.type );
  25457. if ( json.times === undefined ) {
  25458. const times = [], values = [];
  25459. flattenJSON( json.keys, times, values, 'value' );
  25460. json.times = times;
  25461. json.values = values;
  25462. }
  25463. // derived classes can define a static parse method
  25464. if ( trackType.parse !== undefined ) {
  25465. return trackType.parse( json );
  25466. } else {
  25467. // by default, we assume a constructor compatible with the base
  25468. return new trackType( json.name, json.times, json.values, json.interpolation );
  25469. }
  25470. }
  25471. const Cache = {
  25472. enabled: false,
  25473. files: {},
  25474. add: function ( key, file ) {
  25475. if ( this.enabled === false ) return;
  25476. // console.log( 'THREE.Cache', 'Adding key:', key );
  25477. this.files[ key ] = file;
  25478. },
  25479. get: function ( key ) {
  25480. if ( this.enabled === false ) return;
  25481. // console.log( 'THREE.Cache', 'Checking key:', key );
  25482. return this.files[ key ];
  25483. },
  25484. remove: function ( key ) {
  25485. delete this.files[ key ];
  25486. },
  25487. clear: function () {
  25488. this.files = {};
  25489. }
  25490. };
  25491. class LoadingManager {
  25492. constructor( onLoad, onProgress, onError ) {
  25493. const scope = this;
  25494. let isLoading = false;
  25495. let itemsLoaded = 0;
  25496. let itemsTotal = 0;
  25497. let urlModifier = undefined;
  25498. const handlers = [];
  25499. // Refer to #5689 for the reason why we don't set .onStart
  25500. // in the constructor
  25501. this.onStart = undefined;
  25502. this.onLoad = onLoad;
  25503. this.onProgress = onProgress;
  25504. this.onError = onError;
  25505. this.itemStart = function ( url ) {
  25506. itemsTotal ++;
  25507. if ( isLoading === false ) {
  25508. if ( scope.onStart !== undefined ) {
  25509. scope.onStart( url, itemsLoaded, itemsTotal );
  25510. }
  25511. }
  25512. isLoading = true;
  25513. };
  25514. this.itemEnd = function ( url ) {
  25515. itemsLoaded ++;
  25516. if ( scope.onProgress !== undefined ) {
  25517. scope.onProgress( url, itemsLoaded, itemsTotal );
  25518. }
  25519. if ( itemsLoaded === itemsTotal ) {
  25520. isLoading = false;
  25521. if ( scope.onLoad !== undefined ) {
  25522. scope.onLoad();
  25523. }
  25524. }
  25525. };
  25526. this.itemError = function ( url ) {
  25527. if ( scope.onError !== undefined ) {
  25528. scope.onError( url );
  25529. }
  25530. };
  25531. this.resolveURL = function ( url ) {
  25532. if ( urlModifier ) {
  25533. return urlModifier( url );
  25534. }
  25535. return url;
  25536. };
  25537. this.setURLModifier = function ( transform ) {
  25538. urlModifier = transform;
  25539. return this;
  25540. };
  25541. this.addHandler = function ( regex, loader ) {
  25542. handlers.push( regex, loader );
  25543. return this;
  25544. };
  25545. this.removeHandler = function ( regex ) {
  25546. const index = handlers.indexOf( regex );
  25547. if ( index !== - 1 ) {
  25548. handlers.splice( index, 2 );
  25549. }
  25550. return this;
  25551. };
  25552. this.getHandler = function ( file ) {
  25553. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  25554. const regex = handlers[ i ];
  25555. const loader = handlers[ i + 1 ];
  25556. if ( regex.global ) regex.lastIndex = 0; // see #17920
  25557. if ( regex.test( file ) ) {
  25558. return loader;
  25559. }
  25560. }
  25561. return null;
  25562. };
  25563. }
  25564. }
  25565. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  25566. class Loader {
  25567. constructor( manager ) {
  25568. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25569. this.crossOrigin = 'anonymous';
  25570. this.withCredentials = false;
  25571. this.path = '';
  25572. this.resourcePath = '';
  25573. this.requestHeader = {};
  25574. }
  25575. load( /* url, onLoad, onProgress, onError */ ) {}
  25576. loadAsync( url, onProgress ) {
  25577. const scope = this;
  25578. return new Promise( function ( resolve, reject ) {
  25579. scope.load( url, resolve, onProgress, reject );
  25580. } );
  25581. }
  25582. parse( /* data */ ) {}
  25583. setCrossOrigin( crossOrigin ) {
  25584. this.crossOrigin = crossOrigin;
  25585. return this;
  25586. }
  25587. setWithCredentials( value ) {
  25588. this.withCredentials = value;
  25589. return this;
  25590. }
  25591. setPath( path ) {
  25592. this.path = path;
  25593. return this;
  25594. }
  25595. setResourcePath( resourcePath ) {
  25596. this.resourcePath = resourcePath;
  25597. return this;
  25598. }
  25599. setRequestHeader( requestHeader ) {
  25600. this.requestHeader = requestHeader;
  25601. return this;
  25602. }
  25603. }
  25604. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  25605. const loading = {};
  25606. class HttpError extends Error {
  25607. constructor( message, response ) {
  25608. super( message );
  25609. this.response = response;
  25610. }
  25611. }
  25612. class FileLoader extends Loader {
  25613. constructor( manager ) {
  25614. super( manager );
  25615. }
  25616. load( url, onLoad, onProgress, onError ) {
  25617. if ( url === undefined ) url = '';
  25618. if ( this.path !== undefined ) url = this.path + url;
  25619. url = this.manager.resolveURL( url );
  25620. const cached = Cache.get( url );
  25621. if ( cached !== undefined ) {
  25622. this.manager.itemStart( url );
  25623. setTimeout( () => {
  25624. if ( onLoad ) onLoad( cached );
  25625. this.manager.itemEnd( url );
  25626. }, 0 );
  25627. return cached;
  25628. }
  25629. // Check if request is duplicate
  25630. if ( loading[ url ] !== undefined ) {
  25631. loading[ url ].push( {
  25632. onLoad: onLoad,
  25633. onProgress: onProgress,
  25634. onError: onError
  25635. } );
  25636. return;
  25637. }
  25638. // Initialise array for duplicate requests
  25639. loading[ url ] = [];
  25640. loading[ url ].push( {
  25641. onLoad: onLoad,
  25642. onProgress: onProgress,
  25643. onError: onError,
  25644. } );
  25645. // create request
  25646. const req = new Request( url, {
  25647. headers: new Headers( this.requestHeader ),
  25648. credentials: this.withCredentials ? 'include' : 'same-origin',
  25649. // An abort controller could be added within a future PR
  25650. } );
  25651. // record states ( avoid data race )
  25652. const mimeType = this.mimeType;
  25653. const responseType = this.responseType;
  25654. // start the fetch
  25655. fetch( req )
  25656. .then( response => {
  25657. if ( response.status === 200 || response.status === 0 ) {
  25658. // Some browsers return HTTP Status 0 when using non-http protocol
  25659. // e.g. 'file://' or 'data://'. Handle as success.
  25660. if ( response.status === 0 ) {
  25661. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  25662. }
  25663. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  25664. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  25665. return response;
  25666. }
  25667. const callbacks = loading[ url ];
  25668. const reader = response.body.getReader();
  25669. // Nginx needs X-File-Size check
  25670. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  25671. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  25672. const total = contentLength ? parseInt( contentLength ) : 0;
  25673. const lengthComputable = total !== 0;
  25674. let loaded = 0;
  25675. // periodically read data into the new stream tracking while download progress
  25676. const stream = new ReadableStream( {
  25677. start( controller ) {
  25678. readData();
  25679. function readData() {
  25680. reader.read().then( ( { done, value } ) => {
  25681. if ( done ) {
  25682. controller.close();
  25683. } else {
  25684. loaded += value.byteLength;
  25685. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  25686. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25687. const callback = callbacks[ i ];
  25688. if ( callback.onProgress ) callback.onProgress( event );
  25689. }
  25690. controller.enqueue( value );
  25691. readData();
  25692. }
  25693. } );
  25694. }
  25695. }
  25696. } );
  25697. return new Response( stream );
  25698. } else {
  25699. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  25700. }
  25701. } )
  25702. .then( response => {
  25703. switch ( responseType ) {
  25704. case 'arraybuffer':
  25705. return response.arrayBuffer();
  25706. case 'blob':
  25707. return response.blob();
  25708. case 'document':
  25709. return response.text()
  25710. .then( text => {
  25711. const parser = new DOMParser();
  25712. return parser.parseFromString( text, mimeType );
  25713. } );
  25714. case 'json':
  25715. return response.json();
  25716. default:
  25717. if ( mimeType === undefined ) {
  25718. return response.text();
  25719. } else {
  25720. // sniff encoding
  25721. const re = /charset="?([^;"\s]*)"?/i;
  25722. const exec = re.exec( mimeType );
  25723. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  25724. const decoder = new TextDecoder( label );
  25725. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  25726. }
  25727. }
  25728. } )
  25729. .then( data => {
  25730. // Add to cache only on HTTP success, so that we do not cache
  25731. // error response bodies as proper responses to requests.
  25732. Cache.add( url, data );
  25733. const callbacks = loading[ url ];
  25734. delete loading[ url ];
  25735. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25736. const callback = callbacks[ i ];
  25737. if ( callback.onLoad ) callback.onLoad( data );
  25738. }
  25739. } )
  25740. .catch( err => {
  25741. // Abort errors and other errors are handled the same
  25742. const callbacks = loading[ url ];
  25743. if ( callbacks === undefined ) {
  25744. // When onLoad was called and url was deleted in `loading`
  25745. this.manager.itemError( url );
  25746. throw err;
  25747. }
  25748. delete loading[ url ];
  25749. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25750. const callback = callbacks[ i ];
  25751. if ( callback.onError ) callback.onError( err );
  25752. }
  25753. this.manager.itemError( url );
  25754. } )
  25755. .finally( () => {
  25756. this.manager.itemEnd( url );
  25757. } );
  25758. this.manager.itemStart( url );
  25759. }
  25760. setResponseType( value ) {
  25761. this.responseType = value;
  25762. return this;
  25763. }
  25764. setMimeType( value ) {
  25765. this.mimeType = value;
  25766. return this;
  25767. }
  25768. }
  25769. class AnimationLoader extends Loader {
  25770. constructor( manager ) {
  25771. super( manager );
  25772. }
  25773. load( url, onLoad, onProgress, onError ) {
  25774. const scope = this;
  25775. const loader = new FileLoader( this.manager );
  25776. loader.setPath( this.path );
  25777. loader.setRequestHeader( this.requestHeader );
  25778. loader.setWithCredentials( this.withCredentials );
  25779. loader.load( url, function ( text ) {
  25780. try {
  25781. onLoad( scope.parse( JSON.parse( text ) ) );
  25782. } catch ( e ) {
  25783. if ( onError ) {
  25784. onError( e );
  25785. } else {
  25786. console.error( e );
  25787. }
  25788. scope.manager.itemError( url );
  25789. }
  25790. }, onProgress, onError );
  25791. }
  25792. parse( json ) {
  25793. const animations = [];
  25794. for ( let i = 0; i < json.length; i ++ ) {
  25795. const clip = AnimationClip.parse( json[ i ] );
  25796. animations.push( clip );
  25797. }
  25798. return animations;
  25799. }
  25800. }
  25801. /**
  25802. * Abstract Base class to block based textures loader (dds, pvr, ...)
  25803. *
  25804. * Sub classes have to implement the parse() method which will be used in load().
  25805. */
  25806. class CompressedTextureLoader extends Loader {
  25807. constructor( manager ) {
  25808. super( manager );
  25809. }
  25810. load( url, onLoad, onProgress, onError ) {
  25811. const scope = this;
  25812. const images = [];
  25813. const texture = new CompressedTexture();
  25814. const loader = new FileLoader( this.manager );
  25815. loader.setPath( this.path );
  25816. loader.setResponseType( 'arraybuffer' );
  25817. loader.setRequestHeader( this.requestHeader );
  25818. loader.setWithCredentials( scope.withCredentials );
  25819. let loaded = 0;
  25820. function loadTexture( i ) {
  25821. loader.load( url[ i ], function ( buffer ) {
  25822. const texDatas = scope.parse( buffer, true );
  25823. images[ i ] = {
  25824. width: texDatas.width,
  25825. height: texDatas.height,
  25826. format: texDatas.format,
  25827. mipmaps: texDatas.mipmaps
  25828. };
  25829. loaded += 1;
  25830. if ( loaded === 6 ) {
  25831. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  25832. texture.image = images;
  25833. texture.format = texDatas.format;
  25834. texture.needsUpdate = true;
  25835. if ( onLoad ) onLoad( texture );
  25836. }
  25837. }, onProgress, onError );
  25838. }
  25839. if ( Array.isArray( url ) ) {
  25840. for ( let i = 0, il = url.length; i < il; ++ i ) {
  25841. loadTexture( i );
  25842. }
  25843. } else {
  25844. // compressed cubemap texture stored in a single DDS file
  25845. loader.load( url, function ( buffer ) {
  25846. const texDatas = scope.parse( buffer, true );
  25847. if ( texDatas.isCubemap ) {
  25848. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  25849. for ( let f = 0; f < faces; f ++ ) {
  25850. images[ f ] = { mipmaps: [] };
  25851. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  25852. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  25853. images[ f ].format = texDatas.format;
  25854. images[ f ].width = texDatas.width;
  25855. images[ f ].height = texDatas.height;
  25856. }
  25857. }
  25858. texture.image = images;
  25859. } else {
  25860. texture.image.width = texDatas.width;
  25861. texture.image.height = texDatas.height;
  25862. texture.mipmaps = texDatas.mipmaps;
  25863. }
  25864. if ( texDatas.mipmapCount === 1 ) {
  25865. texture.minFilter = LinearFilter;
  25866. }
  25867. texture.format = texDatas.format;
  25868. texture.needsUpdate = true;
  25869. if ( onLoad ) onLoad( texture );
  25870. }, onProgress, onError );
  25871. }
  25872. return texture;
  25873. }
  25874. }
  25875. class ImageLoader extends Loader {
  25876. constructor( manager ) {
  25877. super( manager );
  25878. }
  25879. load( url, onLoad, onProgress, onError ) {
  25880. if ( this.path !== undefined ) url = this.path + url;
  25881. url = this.manager.resolveURL( url );
  25882. const scope = this;
  25883. const cached = Cache.get( url );
  25884. if ( cached !== undefined ) {
  25885. scope.manager.itemStart( url );
  25886. setTimeout( function () {
  25887. if ( onLoad ) onLoad( cached );
  25888. scope.manager.itemEnd( url );
  25889. }, 0 );
  25890. return cached;
  25891. }
  25892. const image = createElementNS( 'img' );
  25893. function onImageLoad() {
  25894. removeEventListeners();
  25895. Cache.add( url, this );
  25896. if ( onLoad ) onLoad( this );
  25897. scope.manager.itemEnd( url );
  25898. }
  25899. function onImageError( event ) {
  25900. removeEventListeners();
  25901. if ( onError ) onError( event );
  25902. scope.manager.itemError( url );
  25903. scope.manager.itemEnd( url );
  25904. }
  25905. function removeEventListeners() {
  25906. image.removeEventListener( 'load', onImageLoad, false );
  25907. image.removeEventListener( 'error', onImageError, false );
  25908. }
  25909. image.addEventListener( 'load', onImageLoad, false );
  25910. image.addEventListener( 'error', onImageError, false );
  25911. if ( url.slice( 0, 5 ) !== 'data:' ) {
  25912. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  25913. }
  25914. scope.manager.itemStart( url );
  25915. image.src = url;
  25916. return image;
  25917. }
  25918. }
  25919. class CubeTextureLoader extends Loader {
  25920. constructor( manager ) {
  25921. super( manager );
  25922. }
  25923. load( urls, onLoad, onProgress, onError ) {
  25924. const texture = new CubeTexture();
  25925. texture.colorSpace = SRGBColorSpace;
  25926. const loader = new ImageLoader( this.manager );
  25927. loader.setCrossOrigin( this.crossOrigin );
  25928. loader.setPath( this.path );
  25929. let loaded = 0;
  25930. function loadTexture( i ) {
  25931. loader.load( urls[ i ], function ( image ) {
  25932. texture.images[ i ] = image;
  25933. loaded ++;
  25934. if ( loaded === 6 ) {
  25935. texture.needsUpdate = true;
  25936. if ( onLoad ) onLoad( texture );
  25937. }
  25938. }, undefined, onError );
  25939. }
  25940. for ( let i = 0; i < urls.length; ++ i ) {
  25941. loadTexture( i );
  25942. }
  25943. return texture;
  25944. }
  25945. }
  25946. /**
  25947. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25948. *
  25949. * Sub classes have to implement the parse() method which will be used in load().
  25950. */
  25951. class DataTextureLoader extends Loader {
  25952. constructor( manager ) {
  25953. super( manager );
  25954. }
  25955. load( url, onLoad, onProgress, onError ) {
  25956. const scope = this;
  25957. const texture = new DataTexture();
  25958. const loader = new FileLoader( this.manager );
  25959. loader.setResponseType( 'arraybuffer' );
  25960. loader.setRequestHeader( this.requestHeader );
  25961. loader.setPath( this.path );
  25962. loader.setWithCredentials( scope.withCredentials );
  25963. loader.load( url, function ( buffer ) {
  25964. let texData;
  25965. try {
  25966. texData = scope.parse( buffer );
  25967. } catch ( error ) {
  25968. if ( onError !== undefined ) {
  25969. onError( error );
  25970. } else {
  25971. console.error( error );
  25972. return;
  25973. }
  25974. }
  25975. if ( texData.image !== undefined ) {
  25976. texture.image = texData.image;
  25977. } else if ( texData.data !== undefined ) {
  25978. texture.image.width = texData.width;
  25979. texture.image.height = texData.height;
  25980. texture.image.data = texData.data;
  25981. }
  25982. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25983. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25984. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25985. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  25986. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25987. if ( texData.colorSpace !== undefined ) {
  25988. texture.colorSpace = texData.colorSpace;
  25989. }
  25990. if ( texData.flipY !== undefined ) {
  25991. texture.flipY = texData.flipY;
  25992. }
  25993. if ( texData.format !== undefined ) {
  25994. texture.format = texData.format;
  25995. }
  25996. if ( texData.type !== undefined ) {
  25997. texture.type = texData.type;
  25998. }
  25999. if ( texData.mipmaps !== undefined ) {
  26000. texture.mipmaps = texData.mipmaps;
  26001. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  26002. }
  26003. if ( texData.mipmapCount === 1 ) {
  26004. texture.minFilter = LinearFilter;
  26005. }
  26006. if ( texData.generateMipmaps !== undefined ) {
  26007. texture.generateMipmaps = texData.generateMipmaps;
  26008. }
  26009. texture.needsUpdate = true;
  26010. if ( onLoad ) onLoad( texture, texData );
  26011. }, onProgress, onError );
  26012. return texture;
  26013. }
  26014. }
  26015. class TextureLoader extends Loader {
  26016. constructor( manager ) {
  26017. super( manager );
  26018. }
  26019. load( url, onLoad, onProgress, onError ) {
  26020. const texture = new Texture();
  26021. const loader = new ImageLoader( this.manager );
  26022. loader.setCrossOrigin( this.crossOrigin );
  26023. loader.setPath( this.path );
  26024. loader.load( url, function ( image ) {
  26025. texture.image = image;
  26026. texture.needsUpdate = true;
  26027. if ( onLoad !== undefined ) {
  26028. onLoad( texture );
  26029. }
  26030. }, onProgress, onError );
  26031. return texture;
  26032. }
  26033. }
  26034. class Light extends Object3D {
  26035. constructor( color, intensity = 1 ) {
  26036. super();
  26037. this.isLight = true;
  26038. this.type = 'Light';
  26039. this.color = new Color( color );
  26040. this.intensity = intensity;
  26041. }
  26042. dispose() {
  26043. // Empty here in base class; some subclasses override.
  26044. }
  26045. copy( source, recursive ) {
  26046. super.copy( source, recursive );
  26047. this.color.copy( source.color );
  26048. this.intensity = source.intensity;
  26049. return this;
  26050. }
  26051. toJSON( meta ) {
  26052. const data = super.toJSON( meta );
  26053. data.object.color = this.color.getHex();
  26054. data.object.intensity = this.intensity;
  26055. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26056. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26057. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26058. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26059. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26060. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26061. return data;
  26062. }
  26063. }
  26064. class HemisphereLight extends Light {
  26065. constructor( skyColor, groundColor, intensity ) {
  26066. super( skyColor, intensity );
  26067. this.isHemisphereLight = true;
  26068. this.type = 'HemisphereLight';
  26069. this.position.copy( Object3D.DEFAULT_UP );
  26070. this.updateMatrix();
  26071. this.groundColor = new Color( groundColor );
  26072. }
  26073. copy( source, recursive ) {
  26074. super.copy( source, recursive );
  26075. this.groundColor.copy( source.groundColor );
  26076. return this;
  26077. }
  26078. }
  26079. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  26080. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  26081. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  26082. class LightShadow {
  26083. constructor( camera ) {
  26084. this.camera = camera;
  26085. this.bias = 0;
  26086. this.normalBias = 0;
  26087. this.radius = 1;
  26088. this.blurSamples = 8;
  26089. this.mapSize = new Vector2( 512, 512 );
  26090. this.map = null;
  26091. this.mapPass = null;
  26092. this.matrix = new Matrix4();
  26093. this.autoUpdate = true;
  26094. this.needsUpdate = false;
  26095. this._frustum = new Frustum();
  26096. this._frameExtents = new Vector2( 1, 1 );
  26097. this._viewportCount = 1;
  26098. this._viewports = [
  26099. new Vector4( 0, 0, 1, 1 )
  26100. ];
  26101. }
  26102. getViewportCount() {
  26103. return this._viewportCount;
  26104. }
  26105. getFrustum() {
  26106. return this._frustum;
  26107. }
  26108. updateMatrices( light ) {
  26109. const shadowCamera = this.camera;
  26110. const shadowMatrix = this.matrix;
  26111. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  26112. shadowCamera.position.copy( _lightPositionWorld$1 );
  26113. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  26114. shadowCamera.lookAt( _lookTarget$1 );
  26115. shadowCamera.updateMatrixWorld();
  26116. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  26117. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  26118. shadowMatrix.set(
  26119. 0.5, 0.0, 0.0, 0.5,
  26120. 0.0, 0.5, 0.0, 0.5,
  26121. 0.0, 0.0, 0.5, 0.5,
  26122. 0.0, 0.0, 0.0, 1.0
  26123. );
  26124. shadowMatrix.multiply( _projScreenMatrix$1 );
  26125. }
  26126. getViewport( viewportIndex ) {
  26127. return this._viewports[ viewportIndex ];
  26128. }
  26129. getFrameExtents() {
  26130. return this._frameExtents;
  26131. }
  26132. dispose() {
  26133. if ( this.map ) {
  26134. this.map.dispose();
  26135. }
  26136. if ( this.mapPass ) {
  26137. this.mapPass.dispose();
  26138. }
  26139. }
  26140. copy( source ) {
  26141. this.camera = source.camera.clone();
  26142. this.bias = source.bias;
  26143. this.radius = source.radius;
  26144. this.mapSize.copy( source.mapSize );
  26145. return this;
  26146. }
  26147. clone() {
  26148. return new this.constructor().copy( this );
  26149. }
  26150. toJSON() {
  26151. const object = {};
  26152. if ( this.bias !== 0 ) object.bias = this.bias;
  26153. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  26154. if ( this.radius !== 1 ) object.radius = this.radius;
  26155. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26156. object.camera = this.camera.toJSON( false ).object;
  26157. delete object.camera.matrix;
  26158. return object;
  26159. }
  26160. }
  26161. class SpotLightShadow extends LightShadow {
  26162. constructor() {
  26163. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26164. this.isSpotLightShadow = true;
  26165. this.focus = 1;
  26166. }
  26167. updateMatrices( light ) {
  26168. const camera = this.camera;
  26169. const fov = RAD2DEG * 2 * light.angle * this.focus;
  26170. const aspect = this.mapSize.width / this.mapSize.height;
  26171. const far = light.distance || camera.far;
  26172. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  26173. camera.fov = fov;
  26174. camera.aspect = aspect;
  26175. camera.far = far;
  26176. camera.updateProjectionMatrix();
  26177. }
  26178. super.updateMatrices( light );
  26179. }
  26180. copy( source ) {
  26181. super.copy( source );
  26182. this.focus = source.focus;
  26183. return this;
  26184. }
  26185. }
  26186. class SpotLight extends Light {
  26187. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  26188. super( color, intensity );
  26189. this.isSpotLight = true;
  26190. this.type = 'SpotLight';
  26191. this.position.copy( Object3D.DEFAULT_UP );
  26192. this.updateMatrix();
  26193. this.target = new Object3D();
  26194. this.distance = distance;
  26195. this.angle = angle;
  26196. this.penumbra = penumbra;
  26197. this.decay = decay;
  26198. this.map = null;
  26199. this.shadow = new SpotLightShadow();
  26200. }
  26201. get power() {
  26202. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26203. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  26204. return this.intensity * Math.PI;
  26205. }
  26206. set power( power ) {
  26207. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26208. this.intensity = power / Math.PI;
  26209. }
  26210. dispose() {
  26211. this.shadow.dispose();
  26212. }
  26213. copy( source, recursive ) {
  26214. super.copy( source, recursive );
  26215. this.distance = source.distance;
  26216. this.angle = source.angle;
  26217. this.penumbra = source.penumbra;
  26218. this.decay = source.decay;
  26219. this.target = source.target.clone();
  26220. this.shadow = source.shadow.clone();
  26221. return this;
  26222. }
  26223. }
  26224. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  26225. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  26226. const _lookTarget = /*@__PURE__*/ new Vector3();
  26227. class PointLightShadow extends LightShadow {
  26228. constructor() {
  26229. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  26230. this.isPointLightShadow = true;
  26231. this._frameExtents = new Vector2( 4, 2 );
  26232. this._viewportCount = 6;
  26233. this._viewports = [
  26234. // These viewports map a cube-map onto a 2D texture with the
  26235. // following orientation:
  26236. //
  26237. // xzXZ
  26238. // y Y
  26239. //
  26240. // X - Positive x direction
  26241. // x - Negative x direction
  26242. // Y - Positive y direction
  26243. // y - Negative y direction
  26244. // Z - Positive z direction
  26245. // z - Negative z direction
  26246. // positive X
  26247. new Vector4( 2, 1, 1, 1 ),
  26248. // negative X
  26249. new Vector4( 0, 1, 1, 1 ),
  26250. // positive Z
  26251. new Vector4( 3, 1, 1, 1 ),
  26252. // negative Z
  26253. new Vector4( 1, 1, 1, 1 ),
  26254. // positive Y
  26255. new Vector4( 3, 0, 1, 1 ),
  26256. // negative Y
  26257. new Vector4( 1, 0, 1, 1 )
  26258. ];
  26259. this._cubeDirections = [
  26260. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  26261. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  26262. ];
  26263. this._cubeUps = [
  26264. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  26265. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  26266. ];
  26267. }
  26268. updateMatrices( light, viewportIndex = 0 ) {
  26269. const camera = this.camera;
  26270. const shadowMatrix = this.matrix;
  26271. const far = light.distance || camera.far;
  26272. if ( far !== camera.far ) {
  26273. camera.far = far;
  26274. camera.updateProjectionMatrix();
  26275. }
  26276. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  26277. camera.position.copy( _lightPositionWorld );
  26278. _lookTarget.copy( camera.position );
  26279. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  26280. camera.up.copy( this._cubeUps[ viewportIndex ] );
  26281. camera.lookAt( _lookTarget );
  26282. camera.updateMatrixWorld();
  26283. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  26284. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  26285. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  26286. }
  26287. }
  26288. class PointLight extends Light {
  26289. constructor( color, intensity, distance = 0, decay = 2 ) {
  26290. super( color, intensity );
  26291. this.isPointLight = true;
  26292. this.type = 'PointLight';
  26293. this.distance = distance;
  26294. this.decay = decay;
  26295. this.shadow = new PointLightShadow();
  26296. }
  26297. get power() {
  26298. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26299. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  26300. return this.intensity * 4 * Math.PI;
  26301. }
  26302. set power( power ) {
  26303. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26304. this.intensity = power / ( 4 * Math.PI );
  26305. }
  26306. dispose() {
  26307. this.shadow.dispose();
  26308. }
  26309. copy( source, recursive ) {
  26310. super.copy( source, recursive );
  26311. this.distance = source.distance;
  26312. this.decay = source.decay;
  26313. this.shadow = source.shadow.clone();
  26314. return this;
  26315. }
  26316. }
  26317. class DirectionalLightShadow extends LightShadow {
  26318. constructor() {
  26319. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  26320. this.isDirectionalLightShadow = true;
  26321. }
  26322. }
  26323. class DirectionalLight extends Light {
  26324. constructor( color, intensity ) {
  26325. super( color, intensity );
  26326. this.isDirectionalLight = true;
  26327. this.type = 'DirectionalLight';
  26328. this.position.copy( Object3D.DEFAULT_UP );
  26329. this.updateMatrix();
  26330. this.target = new Object3D();
  26331. this.shadow = new DirectionalLightShadow();
  26332. }
  26333. dispose() {
  26334. this.shadow.dispose();
  26335. }
  26336. copy( source ) {
  26337. super.copy( source );
  26338. this.target = source.target.clone();
  26339. this.shadow = source.shadow.clone();
  26340. return this;
  26341. }
  26342. }
  26343. class AmbientLight extends Light {
  26344. constructor( color, intensity ) {
  26345. super( color, intensity );
  26346. this.isAmbientLight = true;
  26347. this.type = 'AmbientLight';
  26348. }
  26349. }
  26350. class RectAreaLight extends Light {
  26351. constructor( color, intensity, width = 10, height = 10 ) {
  26352. super( color, intensity );
  26353. this.isRectAreaLight = true;
  26354. this.type = 'RectAreaLight';
  26355. this.width = width;
  26356. this.height = height;
  26357. }
  26358. get power() {
  26359. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26360. return this.intensity * this.width * this.height * Math.PI;
  26361. }
  26362. set power( power ) {
  26363. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26364. this.intensity = power / ( this.width * this.height * Math.PI );
  26365. }
  26366. copy( source ) {
  26367. super.copy( source );
  26368. this.width = source.width;
  26369. this.height = source.height;
  26370. return this;
  26371. }
  26372. toJSON( meta ) {
  26373. const data = super.toJSON( meta );
  26374. data.object.width = this.width;
  26375. data.object.height = this.height;
  26376. return data;
  26377. }
  26378. }
  26379. /**
  26380. * Primary reference:
  26381. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26382. *
  26383. * Secondary reference:
  26384. * https://www.ppsloan.org/publications/StupidSH36.pdf
  26385. */
  26386. // 3-band SH defined by 9 coefficients
  26387. class SphericalHarmonics3 {
  26388. constructor() {
  26389. this.isSphericalHarmonics3 = true;
  26390. this.coefficients = [];
  26391. for ( let i = 0; i < 9; i ++ ) {
  26392. this.coefficients.push( new Vector3() );
  26393. }
  26394. }
  26395. set( coefficients ) {
  26396. for ( let i = 0; i < 9; i ++ ) {
  26397. this.coefficients[ i ].copy( coefficients[ i ] );
  26398. }
  26399. return this;
  26400. }
  26401. zero() {
  26402. for ( let i = 0; i < 9; i ++ ) {
  26403. this.coefficients[ i ].set( 0, 0, 0 );
  26404. }
  26405. return this;
  26406. }
  26407. // get the radiance in the direction of the normal
  26408. // target is a Vector3
  26409. getAt( normal, target ) {
  26410. // normal is assumed to be unit length
  26411. const x = normal.x, y = normal.y, z = normal.z;
  26412. const coeff = this.coefficients;
  26413. // band 0
  26414. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  26415. // band 1
  26416. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  26417. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  26418. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  26419. // band 2
  26420. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  26421. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  26422. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  26423. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  26424. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  26425. return target;
  26426. }
  26427. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  26428. // target is a Vector3
  26429. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26430. getIrradianceAt( normal, target ) {
  26431. // normal is assumed to be unit length
  26432. const x = normal.x, y = normal.y, z = normal.z;
  26433. const coeff = this.coefficients;
  26434. // band 0
  26435. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  26436. // band 1
  26437. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  26438. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  26439. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  26440. // band 2
  26441. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  26442. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  26443. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  26444. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  26445. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  26446. return target;
  26447. }
  26448. add( sh ) {
  26449. for ( let i = 0; i < 9; i ++ ) {
  26450. this.coefficients[ i ].add( sh.coefficients[ i ] );
  26451. }
  26452. return this;
  26453. }
  26454. addScaledSH( sh, s ) {
  26455. for ( let i = 0; i < 9; i ++ ) {
  26456. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  26457. }
  26458. return this;
  26459. }
  26460. scale( s ) {
  26461. for ( let i = 0; i < 9; i ++ ) {
  26462. this.coefficients[ i ].multiplyScalar( s );
  26463. }
  26464. return this;
  26465. }
  26466. lerp( sh, alpha ) {
  26467. for ( let i = 0; i < 9; i ++ ) {
  26468. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  26469. }
  26470. return this;
  26471. }
  26472. equals( sh ) {
  26473. for ( let i = 0; i < 9; i ++ ) {
  26474. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  26475. return false;
  26476. }
  26477. }
  26478. return true;
  26479. }
  26480. copy( sh ) {
  26481. return this.set( sh.coefficients );
  26482. }
  26483. clone() {
  26484. return new this.constructor().copy( this );
  26485. }
  26486. fromArray( array, offset = 0 ) {
  26487. const coefficients = this.coefficients;
  26488. for ( let i = 0; i < 9; i ++ ) {
  26489. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  26490. }
  26491. return this;
  26492. }
  26493. toArray( array = [], offset = 0 ) {
  26494. const coefficients = this.coefficients;
  26495. for ( let i = 0; i < 9; i ++ ) {
  26496. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  26497. }
  26498. return array;
  26499. }
  26500. // evaluate the basis functions
  26501. // shBasis is an Array[ 9 ]
  26502. static getBasisAt( normal, shBasis ) {
  26503. // normal is assumed to be unit length
  26504. const x = normal.x, y = normal.y, z = normal.z;
  26505. // band 0
  26506. shBasis[ 0 ] = 0.282095;
  26507. // band 1
  26508. shBasis[ 1 ] = 0.488603 * y;
  26509. shBasis[ 2 ] = 0.488603 * z;
  26510. shBasis[ 3 ] = 0.488603 * x;
  26511. // band 2
  26512. shBasis[ 4 ] = 1.092548 * x * y;
  26513. shBasis[ 5 ] = 1.092548 * y * z;
  26514. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  26515. shBasis[ 7 ] = 1.092548 * x * z;
  26516. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  26517. }
  26518. }
  26519. class LightProbe extends Light {
  26520. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  26521. super( undefined, intensity );
  26522. this.isLightProbe = true;
  26523. this.sh = sh;
  26524. }
  26525. copy( source ) {
  26526. super.copy( source );
  26527. this.sh.copy( source.sh );
  26528. return this;
  26529. }
  26530. fromJSON( json ) {
  26531. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  26532. this.sh.fromArray( json.sh );
  26533. return this;
  26534. }
  26535. toJSON( meta ) {
  26536. const data = super.toJSON( meta );
  26537. data.object.sh = this.sh.toArray();
  26538. return data;
  26539. }
  26540. }
  26541. class MaterialLoader extends Loader {
  26542. constructor( manager ) {
  26543. super( manager );
  26544. this.textures = {};
  26545. }
  26546. load( url, onLoad, onProgress, onError ) {
  26547. const scope = this;
  26548. const loader = new FileLoader( scope.manager );
  26549. loader.setPath( scope.path );
  26550. loader.setRequestHeader( scope.requestHeader );
  26551. loader.setWithCredentials( scope.withCredentials );
  26552. loader.load( url, function ( text ) {
  26553. try {
  26554. onLoad( scope.parse( JSON.parse( text ) ) );
  26555. } catch ( e ) {
  26556. if ( onError ) {
  26557. onError( e );
  26558. } else {
  26559. console.error( e );
  26560. }
  26561. scope.manager.itemError( url );
  26562. }
  26563. }, onProgress, onError );
  26564. }
  26565. parse( json ) {
  26566. const textures = this.textures;
  26567. function getTexture( name ) {
  26568. if ( textures[ name ] === undefined ) {
  26569. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26570. }
  26571. return textures[ name ];
  26572. }
  26573. const material = MaterialLoader.createMaterialFromType( json.type );
  26574. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26575. if ( json.name !== undefined ) material.name = json.name;
  26576. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  26577. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26578. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26579. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  26580. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  26581. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  26582. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26583. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  26584. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  26585. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  26586. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26587. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  26588. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  26589. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  26590. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  26591. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  26592. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  26593. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  26594. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  26595. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  26596. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  26597. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  26598. if ( json.fog !== undefined ) material.fog = json.fog;
  26599. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  26600. if ( json.blending !== undefined ) material.blending = json.blending;
  26601. if ( json.combine !== undefined ) material.combine = json.combine;
  26602. if ( json.side !== undefined ) material.side = json.side;
  26603. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  26604. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  26605. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  26606. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  26607. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  26608. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  26609. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  26610. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  26611. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  26612. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  26613. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  26614. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  26615. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  26616. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  26617. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  26618. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  26619. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  26620. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  26621. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  26622. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  26623. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  26624. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  26625. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  26626. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  26627. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  26628. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  26629. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  26630. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  26631. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  26632. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  26633. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  26634. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  26635. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  26636. if ( json.scale !== undefined ) material.scale = json.scale;
  26637. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  26638. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  26639. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  26640. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  26641. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  26642. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  26643. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  26644. if ( json.visible !== undefined ) material.visible = json.visible;
  26645. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  26646. if ( json.userData !== undefined ) material.userData = json.userData;
  26647. if ( json.vertexColors !== undefined ) {
  26648. if ( typeof json.vertexColors === 'number' ) {
  26649. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  26650. } else {
  26651. material.vertexColors = json.vertexColors;
  26652. }
  26653. }
  26654. // Shader Material
  26655. if ( json.uniforms !== undefined ) {
  26656. for ( const name in json.uniforms ) {
  26657. const uniform = json.uniforms[ name ];
  26658. material.uniforms[ name ] = {};
  26659. switch ( uniform.type ) {
  26660. case 't':
  26661. material.uniforms[ name ].value = getTexture( uniform.value );
  26662. break;
  26663. case 'c':
  26664. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  26665. break;
  26666. case 'v2':
  26667. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  26668. break;
  26669. case 'v3':
  26670. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  26671. break;
  26672. case 'v4':
  26673. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  26674. break;
  26675. case 'm3':
  26676. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  26677. break;
  26678. case 'm4':
  26679. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  26680. break;
  26681. default:
  26682. material.uniforms[ name ].value = uniform.value;
  26683. }
  26684. }
  26685. }
  26686. if ( json.defines !== undefined ) material.defines = json.defines;
  26687. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  26688. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  26689. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  26690. if ( json.extensions !== undefined ) {
  26691. for ( const key in json.extensions ) {
  26692. material.extensions[ key ] = json.extensions[ key ];
  26693. }
  26694. }
  26695. if ( json.lights !== undefined ) material.lights = json.lights;
  26696. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  26697. // for PointsMaterial
  26698. if ( json.size !== undefined ) material.size = json.size;
  26699. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  26700. // maps
  26701. if ( json.map !== undefined ) material.map = getTexture( json.map );
  26702. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  26703. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  26704. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  26705. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  26706. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  26707. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  26708. if ( json.normalScale !== undefined ) {
  26709. let normalScale = json.normalScale;
  26710. if ( Array.isArray( normalScale ) === false ) {
  26711. // Blender exporter used to export a scalar. See #7459
  26712. normalScale = [ normalScale, normalScale ];
  26713. }
  26714. material.normalScale = new Vector2().fromArray( normalScale );
  26715. }
  26716. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  26717. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  26718. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  26719. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  26720. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  26721. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  26722. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  26723. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  26724. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  26725. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  26726. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  26727. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  26728. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  26729. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  26730. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  26731. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  26732. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  26733. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  26734. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  26735. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  26736. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  26737. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  26738. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  26739. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  26740. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  26741. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  26742. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  26743. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  26744. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  26745. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  26746. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  26747. return material;
  26748. }
  26749. setTextures( value ) {
  26750. this.textures = value;
  26751. return this;
  26752. }
  26753. static createMaterialFromType( type ) {
  26754. const materialLib = {
  26755. ShadowMaterial,
  26756. SpriteMaterial,
  26757. RawShaderMaterial,
  26758. ShaderMaterial,
  26759. PointsMaterial,
  26760. MeshPhysicalMaterial,
  26761. MeshStandardMaterial,
  26762. MeshPhongMaterial,
  26763. MeshToonMaterial,
  26764. MeshNormalMaterial,
  26765. MeshLambertMaterial,
  26766. MeshDepthMaterial,
  26767. MeshDistanceMaterial,
  26768. MeshBasicMaterial,
  26769. MeshMatcapMaterial,
  26770. LineDashedMaterial,
  26771. LineBasicMaterial,
  26772. Material
  26773. };
  26774. return new materialLib[ type ]();
  26775. }
  26776. }
  26777. class LoaderUtils {
  26778. static decodeText( array ) {
  26779. if ( typeof TextDecoder !== 'undefined' ) {
  26780. return new TextDecoder().decode( array );
  26781. }
  26782. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26783. // throws a "maximum call stack size exceeded" error for large arrays.
  26784. let s = '';
  26785. for ( let i = 0, il = array.length; i < il; i ++ ) {
  26786. // Implicitly assumes little-endian.
  26787. s += String.fromCharCode( array[ i ] );
  26788. }
  26789. try {
  26790. // merges multi-byte utf-8 characters.
  26791. return decodeURIComponent( escape( s ) );
  26792. } catch ( e ) { // see #16358
  26793. return s;
  26794. }
  26795. }
  26796. static extractUrlBase( url ) {
  26797. const index = url.lastIndexOf( '/' );
  26798. if ( index === - 1 ) return './';
  26799. return url.slice( 0, index + 1 );
  26800. }
  26801. static resolveURL( url, path ) {
  26802. // Invalid URL
  26803. if ( typeof url !== 'string' || url === '' ) return '';
  26804. // Host Relative URL
  26805. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  26806. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  26807. }
  26808. // Absolute URL http://,https://,//
  26809. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  26810. // Data URI
  26811. if ( /^data:.*,.*$/i.test( url ) ) return url;
  26812. // Blob URL
  26813. if ( /^blob:.*$/i.test( url ) ) return url;
  26814. // Relative URL
  26815. return path + url;
  26816. }
  26817. }
  26818. class InstancedBufferGeometry extends BufferGeometry {
  26819. constructor() {
  26820. super();
  26821. this.isInstancedBufferGeometry = true;
  26822. this.type = 'InstancedBufferGeometry';
  26823. this.instanceCount = Infinity;
  26824. }
  26825. copy( source ) {
  26826. super.copy( source );
  26827. this.instanceCount = source.instanceCount;
  26828. return this;
  26829. }
  26830. toJSON() {
  26831. const data = super.toJSON();
  26832. data.instanceCount = this.instanceCount;
  26833. data.isInstancedBufferGeometry = true;
  26834. return data;
  26835. }
  26836. }
  26837. class BufferGeometryLoader extends Loader {
  26838. constructor( manager ) {
  26839. super( manager );
  26840. }
  26841. load( url, onLoad, onProgress, onError ) {
  26842. const scope = this;
  26843. const loader = new FileLoader( scope.manager );
  26844. loader.setPath( scope.path );
  26845. loader.setRequestHeader( scope.requestHeader );
  26846. loader.setWithCredentials( scope.withCredentials );
  26847. loader.load( url, function ( text ) {
  26848. try {
  26849. onLoad( scope.parse( JSON.parse( text ) ) );
  26850. } catch ( e ) {
  26851. if ( onError ) {
  26852. onError( e );
  26853. } else {
  26854. console.error( e );
  26855. }
  26856. scope.manager.itemError( url );
  26857. }
  26858. }, onProgress, onError );
  26859. }
  26860. parse( json ) {
  26861. const interleavedBufferMap = {};
  26862. const arrayBufferMap = {};
  26863. function getInterleavedBuffer( json, uuid ) {
  26864. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  26865. const interleavedBuffers = json.interleavedBuffers;
  26866. const interleavedBuffer = interleavedBuffers[ uuid ];
  26867. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  26868. const array = getTypedArray( interleavedBuffer.type, buffer );
  26869. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  26870. ib.uuid = interleavedBuffer.uuid;
  26871. interleavedBufferMap[ uuid ] = ib;
  26872. return ib;
  26873. }
  26874. function getArrayBuffer( json, uuid ) {
  26875. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  26876. const arrayBuffers = json.arrayBuffers;
  26877. const arrayBuffer = arrayBuffers[ uuid ];
  26878. const ab = new Uint32Array( arrayBuffer ).buffer;
  26879. arrayBufferMap[ uuid ] = ab;
  26880. return ab;
  26881. }
  26882. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  26883. const index = json.data.index;
  26884. if ( index !== undefined ) {
  26885. const typedArray = getTypedArray( index.type, index.array );
  26886. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  26887. }
  26888. const attributes = json.data.attributes;
  26889. for ( const key in attributes ) {
  26890. const attribute = attributes[ key ];
  26891. let bufferAttribute;
  26892. if ( attribute.isInterleavedBufferAttribute ) {
  26893. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26894. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26895. } else {
  26896. const typedArray = getTypedArray( attribute.type, attribute.array );
  26897. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  26898. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  26899. }
  26900. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26901. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  26902. geometry.setAttribute( key, bufferAttribute );
  26903. }
  26904. const morphAttributes = json.data.morphAttributes;
  26905. if ( morphAttributes ) {
  26906. for ( const key in morphAttributes ) {
  26907. const attributeArray = morphAttributes[ key ];
  26908. const array = [];
  26909. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  26910. const attribute = attributeArray[ i ];
  26911. let bufferAttribute;
  26912. if ( attribute.isInterleavedBufferAttribute ) {
  26913. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26914. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26915. } else {
  26916. const typedArray = getTypedArray( attribute.type, attribute.array );
  26917. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  26918. }
  26919. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26920. array.push( bufferAttribute );
  26921. }
  26922. geometry.morphAttributes[ key ] = array;
  26923. }
  26924. }
  26925. const morphTargetsRelative = json.data.morphTargetsRelative;
  26926. if ( morphTargetsRelative ) {
  26927. geometry.morphTargetsRelative = true;
  26928. }
  26929. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  26930. if ( groups !== undefined ) {
  26931. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  26932. const group = groups[ i ];
  26933. geometry.addGroup( group.start, group.count, group.materialIndex );
  26934. }
  26935. }
  26936. const boundingSphere = json.data.boundingSphere;
  26937. if ( boundingSphere !== undefined ) {
  26938. const center = new Vector3();
  26939. if ( boundingSphere.center !== undefined ) {
  26940. center.fromArray( boundingSphere.center );
  26941. }
  26942. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  26943. }
  26944. if ( json.name ) geometry.name = json.name;
  26945. if ( json.userData ) geometry.userData = json.userData;
  26946. return geometry;
  26947. }
  26948. }
  26949. class ObjectLoader extends Loader {
  26950. constructor( manager ) {
  26951. super( manager );
  26952. }
  26953. load( url, onLoad, onProgress, onError ) {
  26954. const scope = this;
  26955. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26956. this.resourcePath = this.resourcePath || path;
  26957. const loader = new FileLoader( this.manager );
  26958. loader.setPath( this.path );
  26959. loader.setRequestHeader( this.requestHeader );
  26960. loader.setWithCredentials( this.withCredentials );
  26961. loader.load( url, function ( text ) {
  26962. let json = null;
  26963. try {
  26964. json = JSON.parse( text );
  26965. } catch ( error ) {
  26966. if ( onError !== undefined ) onError( error );
  26967. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26968. return;
  26969. }
  26970. const metadata = json.metadata;
  26971. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26972. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  26973. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26974. return;
  26975. }
  26976. scope.parse( json, onLoad );
  26977. }, onProgress, onError );
  26978. }
  26979. async loadAsync( url, onProgress ) {
  26980. const scope = this;
  26981. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26982. this.resourcePath = this.resourcePath || path;
  26983. const loader = new FileLoader( this.manager );
  26984. loader.setPath( this.path );
  26985. loader.setRequestHeader( this.requestHeader );
  26986. loader.setWithCredentials( this.withCredentials );
  26987. const text = await loader.loadAsync( url, onProgress );
  26988. const json = JSON.parse( text );
  26989. const metadata = json.metadata;
  26990. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26991. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26992. }
  26993. return await scope.parseAsync( json );
  26994. }
  26995. parse( json, onLoad ) {
  26996. const animations = this.parseAnimations( json.animations );
  26997. const shapes = this.parseShapes( json.shapes );
  26998. const geometries = this.parseGeometries( json.geometries, shapes );
  26999. const images = this.parseImages( json.images, function () {
  27000. if ( onLoad !== undefined ) onLoad( object );
  27001. } );
  27002. const textures = this.parseTextures( json.textures, images );
  27003. const materials = this.parseMaterials( json.materials, textures );
  27004. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27005. const skeletons = this.parseSkeletons( json.skeletons, object );
  27006. this.bindSkeletons( object, skeletons );
  27007. //
  27008. if ( onLoad !== undefined ) {
  27009. let hasImages = false;
  27010. for ( const uuid in images ) {
  27011. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27012. hasImages = true;
  27013. break;
  27014. }
  27015. }
  27016. if ( hasImages === false ) onLoad( object );
  27017. }
  27018. return object;
  27019. }
  27020. async parseAsync( json ) {
  27021. const animations = this.parseAnimations( json.animations );
  27022. const shapes = this.parseShapes( json.shapes );
  27023. const geometries = this.parseGeometries( json.geometries, shapes );
  27024. const images = await this.parseImagesAsync( json.images );
  27025. const textures = this.parseTextures( json.textures, images );
  27026. const materials = this.parseMaterials( json.materials, textures );
  27027. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27028. const skeletons = this.parseSkeletons( json.skeletons, object );
  27029. this.bindSkeletons( object, skeletons );
  27030. return object;
  27031. }
  27032. parseShapes( json ) {
  27033. const shapes = {};
  27034. if ( json !== undefined ) {
  27035. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27036. const shape = new Shape().fromJSON( json[ i ] );
  27037. shapes[ shape.uuid ] = shape;
  27038. }
  27039. }
  27040. return shapes;
  27041. }
  27042. parseSkeletons( json, object ) {
  27043. const skeletons = {};
  27044. const bones = {};
  27045. // generate bone lookup table
  27046. object.traverse( function ( child ) {
  27047. if ( child.isBone ) bones[ child.uuid ] = child;
  27048. } );
  27049. // create skeletons
  27050. if ( json !== undefined ) {
  27051. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27052. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27053. skeletons[ skeleton.uuid ] = skeleton;
  27054. }
  27055. }
  27056. return skeletons;
  27057. }
  27058. parseGeometries( json, shapes ) {
  27059. const geometries = {};
  27060. if ( json !== undefined ) {
  27061. const bufferGeometryLoader = new BufferGeometryLoader();
  27062. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27063. let geometry;
  27064. const data = json[ i ];
  27065. switch ( data.type ) {
  27066. case 'BufferGeometry':
  27067. case 'InstancedBufferGeometry':
  27068. geometry = bufferGeometryLoader.parse( data );
  27069. break;
  27070. default:
  27071. if ( data.type in Geometries ) {
  27072. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27073. } else {
  27074. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27075. }
  27076. }
  27077. geometry.uuid = data.uuid;
  27078. if ( data.name !== undefined ) geometry.name = data.name;
  27079. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27080. geometries[ data.uuid ] = geometry;
  27081. }
  27082. }
  27083. return geometries;
  27084. }
  27085. parseMaterials( json, textures ) {
  27086. const cache = {}; // MultiMaterial
  27087. const materials = {};
  27088. if ( json !== undefined ) {
  27089. const loader = new MaterialLoader();
  27090. loader.setTextures( textures );
  27091. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27092. const data = json[ i ];
  27093. if ( cache[ data.uuid ] === undefined ) {
  27094. cache[ data.uuid ] = loader.parse( data );
  27095. }
  27096. materials[ data.uuid ] = cache[ data.uuid ];
  27097. }
  27098. }
  27099. return materials;
  27100. }
  27101. parseAnimations( json ) {
  27102. const animations = {};
  27103. if ( json !== undefined ) {
  27104. for ( let i = 0; i < json.length; i ++ ) {
  27105. const data = json[ i ];
  27106. const clip = AnimationClip.parse( data );
  27107. animations[ clip.uuid ] = clip;
  27108. }
  27109. }
  27110. return animations;
  27111. }
  27112. parseImages( json, onLoad ) {
  27113. const scope = this;
  27114. const images = {};
  27115. let loader;
  27116. function loadImage( url ) {
  27117. scope.manager.itemStart( url );
  27118. return loader.load( url, function () {
  27119. scope.manager.itemEnd( url );
  27120. }, undefined, function () {
  27121. scope.manager.itemError( url );
  27122. scope.manager.itemEnd( url );
  27123. } );
  27124. }
  27125. function deserializeImage( image ) {
  27126. if ( typeof image === 'string' ) {
  27127. const url = image;
  27128. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27129. return loadImage( path );
  27130. } else {
  27131. if ( image.data ) {
  27132. return {
  27133. data: getTypedArray( image.type, image.data ),
  27134. width: image.width,
  27135. height: image.height
  27136. };
  27137. } else {
  27138. return null;
  27139. }
  27140. }
  27141. }
  27142. if ( json !== undefined && json.length > 0 ) {
  27143. const manager = new LoadingManager( onLoad );
  27144. loader = new ImageLoader( manager );
  27145. loader.setCrossOrigin( this.crossOrigin );
  27146. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27147. const image = json[ i ];
  27148. const url = image.url;
  27149. if ( Array.isArray( url ) ) {
  27150. // load array of images e.g CubeTexture
  27151. const imageArray = [];
  27152. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27153. const currentUrl = url[ j ];
  27154. const deserializedImage = deserializeImage( currentUrl );
  27155. if ( deserializedImage !== null ) {
  27156. if ( deserializedImage instanceof HTMLImageElement ) {
  27157. imageArray.push( deserializedImage );
  27158. } else {
  27159. // special case: handle array of data textures for cube textures
  27160. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27161. }
  27162. }
  27163. }
  27164. images[ image.uuid ] = new Source( imageArray );
  27165. } else {
  27166. // load single image
  27167. const deserializedImage = deserializeImage( image.url );
  27168. images[ image.uuid ] = new Source( deserializedImage );
  27169. }
  27170. }
  27171. }
  27172. return images;
  27173. }
  27174. async parseImagesAsync( json ) {
  27175. const scope = this;
  27176. const images = {};
  27177. let loader;
  27178. async function deserializeImage( image ) {
  27179. if ( typeof image === 'string' ) {
  27180. const url = image;
  27181. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27182. return await loader.loadAsync( path );
  27183. } else {
  27184. if ( image.data ) {
  27185. return {
  27186. data: getTypedArray( image.type, image.data ),
  27187. width: image.width,
  27188. height: image.height
  27189. };
  27190. } else {
  27191. return null;
  27192. }
  27193. }
  27194. }
  27195. if ( json !== undefined && json.length > 0 ) {
  27196. loader = new ImageLoader( this.manager );
  27197. loader.setCrossOrigin( this.crossOrigin );
  27198. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27199. const image = json[ i ];
  27200. const url = image.url;
  27201. if ( Array.isArray( url ) ) {
  27202. // load array of images e.g CubeTexture
  27203. const imageArray = [];
  27204. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27205. const currentUrl = url[ j ];
  27206. const deserializedImage = await deserializeImage( currentUrl );
  27207. if ( deserializedImage !== null ) {
  27208. if ( deserializedImage instanceof HTMLImageElement ) {
  27209. imageArray.push( deserializedImage );
  27210. } else {
  27211. // special case: handle array of data textures for cube textures
  27212. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27213. }
  27214. }
  27215. }
  27216. images[ image.uuid ] = new Source( imageArray );
  27217. } else {
  27218. // load single image
  27219. const deserializedImage = await deserializeImage( image.url );
  27220. images[ image.uuid ] = new Source( deserializedImage );
  27221. }
  27222. }
  27223. }
  27224. return images;
  27225. }
  27226. parseTextures( json, images ) {
  27227. function parseConstant( value, type ) {
  27228. if ( typeof value === 'number' ) return value;
  27229. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27230. return type[ value ];
  27231. }
  27232. const textures = {};
  27233. if ( json !== undefined ) {
  27234. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27235. const data = json[ i ];
  27236. if ( data.image === undefined ) {
  27237. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27238. }
  27239. if ( images[ data.image ] === undefined ) {
  27240. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27241. }
  27242. const source = images[ data.image ];
  27243. const image = source.data;
  27244. let texture;
  27245. if ( Array.isArray( image ) ) {
  27246. texture = new CubeTexture();
  27247. if ( image.length === 6 ) texture.needsUpdate = true;
  27248. } else {
  27249. if ( image && image.data ) {
  27250. texture = new DataTexture();
  27251. } else {
  27252. texture = new Texture();
  27253. }
  27254. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27255. }
  27256. texture.source = source;
  27257. texture.uuid = data.uuid;
  27258. if ( data.name !== undefined ) texture.name = data.name;
  27259. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27260. if ( data.channel !== undefined ) texture.channel = data.channel;
  27261. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27262. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27263. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27264. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27265. if ( data.wrap !== undefined ) {
  27266. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27267. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27268. }
  27269. if ( data.format !== undefined ) texture.format = data.format;
  27270. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27271. if ( data.type !== undefined ) texture.type = data.type;
  27272. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27273. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27274. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27275. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27276. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27277. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27278. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27279. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27280. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27281. if ( data.userData !== undefined ) texture.userData = data.userData;
  27282. textures[ data.uuid ] = texture;
  27283. }
  27284. }
  27285. return textures;
  27286. }
  27287. parseObject( data, geometries, materials, textures, animations ) {
  27288. let object;
  27289. function getGeometry( name ) {
  27290. if ( geometries[ name ] === undefined ) {
  27291. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27292. }
  27293. return geometries[ name ];
  27294. }
  27295. function getMaterial( name ) {
  27296. if ( name === undefined ) return undefined;
  27297. if ( Array.isArray( name ) ) {
  27298. const array = [];
  27299. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27300. const uuid = name[ i ];
  27301. if ( materials[ uuid ] === undefined ) {
  27302. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27303. }
  27304. array.push( materials[ uuid ] );
  27305. }
  27306. return array;
  27307. }
  27308. if ( materials[ name ] === undefined ) {
  27309. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27310. }
  27311. return materials[ name ];
  27312. }
  27313. function getTexture( uuid ) {
  27314. if ( textures[ uuid ] === undefined ) {
  27315. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27316. }
  27317. return textures[ uuid ];
  27318. }
  27319. let geometry, material;
  27320. switch ( data.type ) {
  27321. case 'Scene':
  27322. object = new Scene();
  27323. if ( data.background !== undefined ) {
  27324. if ( Number.isInteger( data.background ) ) {
  27325. object.background = new Color( data.background );
  27326. } else {
  27327. object.background = getTexture( data.background );
  27328. }
  27329. }
  27330. if ( data.environment !== undefined ) {
  27331. object.environment = getTexture( data.environment );
  27332. }
  27333. if ( data.fog !== undefined ) {
  27334. if ( data.fog.type === 'Fog' ) {
  27335. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27336. } else if ( data.fog.type === 'FogExp2' ) {
  27337. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27338. }
  27339. if ( data.fog.name !== '' ) {
  27340. object.fog.name = data.fog.name;
  27341. }
  27342. }
  27343. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27344. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27345. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  27346. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  27347. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  27348. break;
  27349. case 'PerspectiveCamera':
  27350. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27351. if ( data.focus !== undefined ) object.focus = data.focus;
  27352. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27353. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27354. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27355. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27356. break;
  27357. case 'OrthographicCamera':
  27358. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27359. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27360. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27361. break;
  27362. case 'AmbientLight':
  27363. object = new AmbientLight( data.color, data.intensity );
  27364. break;
  27365. case 'DirectionalLight':
  27366. object = new DirectionalLight( data.color, data.intensity );
  27367. break;
  27368. case 'PointLight':
  27369. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27370. break;
  27371. case 'RectAreaLight':
  27372. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27373. break;
  27374. case 'SpotLight':
  27375. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27376. break;
  27377. case 'HemisphereLight':
  27378. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27379. break;
  27380. case 'LightProbe':
  27381. object = new LightProbe().fromJSON( data );
  27382. break;
  27383. case 'SkinnedMesh':
  27384. geometry = getGeometry( data.geometry );
  27385. material = getMaterial( data.material );
  27386. object = new SkinnedMesh( geometry, material );
  27387. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27388. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27389. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27390. break;
  27391. case 'Mesh':
  27392. geometry = getGeometry( data.geometry );
  27393. material = getMaterial( data.material );
  27394. object = new Mesh( geometry, material );
  27395. break;
  27396. case 'InstancedMesh':
  27397. geometry = getGeometry( data.geometry );
  27398. material = getMaterial( data.material );
  27399. const count = data.count;
  27400. const instanceMatrix = data.instanceMatrix;
  27401. const instanceColor = data.instanceColor;
  27402. object = new InstancedMesh( geometry, material, count );
  27403. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27404. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27405. break;
  27406. case 'BatchedMesh':
  27407. geometry = getGeometry( data.geometry );
  27408. material = getMaterial( data.material );
  27409. object = new BatchedMesh( data.maxGeometryCount, data.maxVertexCount, data.maxIndexCount, material );
  27410. object.geometry = geometry;
  27411. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  27412. object.sortObjects = data.sortObjects;
  27413. object._drawRanges = data.drawRanges;
  27414. object._reservedRanges = data.reservedRanges;
  27415. object._visibility = data.visibility;
  27416. object._active = data.active;
  27417. object._bounds = data.bounds.map( bound => {
  27418. const box = new Box3();
  27419. box.min.fromArray( bound.boxMin );
  27420. box.max.fromArray( bound.boxMax );
  27421. const sphere = new Sphere();
  27422. sphere.radius = bound.sphereRadius;
  27423. sphere.center.fromArray( bound.sphereCenter );
  27424. return {
  27425. boxInitialized: bound.boxInitialized,
  27426. box: box,
  27427. sphereInitialized: bound.sphereInitialized,
  27428. sphere: sphere
  27429. };
  27430. } );
  27431. object._maxGeometryCount = data.maxGeometryCount;
  27432. object._maxVertexCount = data.maxVertexCount;
  27433. object._maxIndexCount = data.maxIndexCount;
  27434. object._geometryInitialized = data.geometryInitialized;
  27435. object._geometryCount = data.geometryCount;
  27436. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  27437. break;
  27438. case 'LOD':
  27439. object = new LOD();
  27440. break;
  27441. case 'Line':
  27442. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  27443. break;
  27444. case 'LineLoop':
  27445. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27446. break;
  27447. case 'LineSegments':
  27448. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27449. break;
  27450. case 'PointCloud':
  27451. case 'Points':
  27452. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27453. break;
  27454. case 'Sprite':
  27455. object = new Sprite( getMaterial( data.material ) );
  27456. break;
  27457. case 'Group':
  27458. object = new Group();
  27459. break;
  27460. case 'Bone':
  27461. object = new Bone();
  27462. break;
  27463. default:
  27464. object = new Object3D();
  27465. }
  27466. object.uuid = data.uuid;
  27467. if ( data.name !== undefined ) object.name = data.name;
  27468. if ( data.matrix !== undefined ) {
  27469. object.matrix.fromArray( data.matrix );
  27470. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27471. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27472. } else {
  27473. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27474. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27475. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27476. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27477. }
  27478. if ( data.up !== undefined ) object.up.fromArray( data.up );
  27479. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27480. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27481. if ( data.shadow ) {
  27482. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27483. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  27484. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27485. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27486. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27487. }
  27488. if ( data.visible !== undefined ) object.visible = data.visible;
  27489. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27490. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27491. if ( data.userData !== undefined ) object.userData = data.userData;
  27492. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27493. if ( data.children !== undefined ) {
  27494. const children = data.children;
  27495. for ( let i = 0; i < children.length; i ++ ) {
  27496. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  27497. }
  27498. }
  27499. if ( data.animations !== undefined ) {
  27500. const objectAnimations = data.animations;
  27501. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  27502. const uuid = objectAnimations[ i ];
  27503. object.animations.push( animations[ uuid ] );
  27504. }
  27505. }
  27506. if ( data.type === 'LOD' ) {
  27507. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  27508. const levels = data.levels;
  27509. for ( let l = 0; l < levels.length; l ++ ) {
  27510. const level = levels[ l ];
  27511. const child = object.getObjectByProperty( 'uuid', level.object );
  27512. if ( child !== undefined ) {
  27513. object.addLevel( child, level.distance, level.hysteresis );
  27514. }
  27515. }
  27516. }
  27517. return object;
  27518. }
  27519. bindSkeletons( object, skeletons ) {
  27520. if ( Object.keys( skeletons ).length === 0 ) return;
  27521. object.traverse( function ( child ) {
  27522. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  27523. const skeleton = skeletons[ child.skeleton ];
  27524. if ( skeleton === undefined ) {
  27525. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  27526. } else {
  27527. child.bind( skeleton, child.bindMatrix );
  27528. }
  27529. }
  27530. } );
  27531. }
  27532. }
  27533. const TEXTURE_MAPPING = {
  27534. UVMapping: UVMapping,
  27535. CubeReflectionMapping: CubeReflectionMapping,
  27536. CubeRefractionMapping: CubeRefractionMapping,
  27537. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27538. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27539. CubeUVReflectionMapping: CubeUVReflectionMapping
  27540. };
  27541. const TEXTURE_WRAPPING = {
  27542. RepeatWrapping: RepeatWrapping,
  27543. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27544. MirroredRepeatWrapping: MirroredRepeatWrapping
  27545. };
  27546. const TEXTURE_FILTER = {
  27547. NearestFilter: NearestFilter,
  27548. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  27549. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  27550. LinearFilter: LinearFilter,
  27551. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  27552. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  27553. };
  27554. class ImageBitmapLoader extends Loader {
  27555. constructor( manager ) {
  27556. super( manager );
  27557. this.isImageBitmapLoader = true;
  27558. if ( typeof createImageBitmap === 'undefined' ) {
  27559. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27560. }
  27561. if ( typeof fetch === 'undefined' ) {
  27562. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27563. }
  27564. this.options = { premultiplyAlpha: 'none' };
  27565. }
  27566. setOptions( options ) {
  27567. this.options = options;
  27568. return this;
  27569. }
  27570. load( url, onLoad, onProgress, onError ) {
  27571. if ( url === undefined ) url = '';
  27572. if ( this.path !== undefined ) url = this.path + url;
  27573. url = this.manager.resolveURL( url );
  27574. const scope = this;
  27575. const cached = Cache.get( url );
  27576. if ( cached !== undefined ) {
  27577. scope.manager.itemStart( url );
  27578. // If cached is a promise, wait for it to resolve
  27579. if ( cached.then ) {
  27580. cached.then( imageBitmap => {
  27581. if ( onLoad ) onLoad( imageBitmap );
  27582. scope.manager.itemEnd( url );
  27583. } ).catch( e => {
  27584. if ( onError ) onError( e );
  27585. } );
  27586. return;
  27587. }
  27588. // If cached is not a promise (i.e., it's already an imageBitmap)
  27589. setTimeout( function () {
  27590. if ( onLoad ) onLoad( cached );
  27591. scope.manager.itemEnd( url );
  27592. }, 0 );
  27593. return cached;
  27594. }
  27595. const fetchOptions = {};
  27596. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  27597. fetchOptions.headers = this.requestHeader;
  27598. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  27599. return res.blob();
  27600. } ).then( function ( blob ) {
  27601. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  27602. } ).then( function ( imageBitmap ) {
  27603. Cache.add( url, imageBitmap );
  27604. if ( onLoad ) onLoad( imageBitmap );
  27605. scope.manager.itemEnd( url );
  27606. return imageBitmap;
  27607. } ).catch( function ( e ) {
  27608. if ( onError ) onError( e );
  27609. Cache.remove( url );
  27610. scope.manager.itemError( url );
  27611. scope.manager.itemEnd( url );
  27612. } );
  27613. Cache.add( url, promise );
  27614. scope.manager.itemStart( url );
  27615. }
  27616. }
  27617. let _context;
  27618. class AudioContext {
  27619. static getContext() {
  27620. if ( _context === undefined ) {
  27621. _context = new ( window.AudioContext || window.webkitAudioContext )();
  27622. }
  27623. return _context;
  27624. }
  27625. static setContext( value ) {
  27626. _context = value;
  27627. }
  27628. }
  27629. class AudioLoader extends Loader {
  27630. constructor( manager ) {
  27631. super( manager );
  27632. }
  27633. load( url, onLoad, onProgress, onError ) {
  27634. const scope = this;
  27635. const loader = new FileLoader( this.manager );
  27636. loader.setResponseType( 'arraybuffer' );
  27637. loader.setPath( this.path );
  27638. loader.setRequestHeader( this.requestHeader );
  27639. loader.setWithCredentials( this.withCredentials );
  27640. loader.load( url, function ( buffer ) {
  27641. try {
  27642. // Create a copy of the buffer. The `decodeAudioData` method
  27643. // detaches the buffer when complete, preventing reuse.
  27644. const bufferCopy = buffer.slice( 0 );
  27645. const context = AudioContext.getContext();
  27646. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27647. onLoad( audioBuffer );
  27648. } ).catch( handleError );
  27649. } catch ( e ) {
  27650. handleError( e );
  27651. }
  27652. }, onProgress, onError );
  27653. function handleError( e ) {
  27654. if ( onError ) {
  27655. onError( e );
  27656. } else {
  27657. console.error( e );
  27658. }
  27659. scope.manager.itemError( url );
  27660. }
  27661. }
  27662. }
  27663. const _eyeRight = /*@__PURE__*/ new Matrix4();
  27664. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  27665. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  27666. class StereoCamera {
  27667. constructor() {
  27668. this.type = 'StereoCamera';
  27669. this.aspect = 1;
  27670. this.eyeSep = 0.064;
  27671. this.cameraL = new PerspectiveCamera();
  27672. this.cameraL.layers.enable( 1 );
  27673. this.cameraL.matrixAutoUpdate = false;
  27674. this.cameraR = new PerspectiveCamera();
  27675. this.cameraR.layers.enable( 2 );
  27676. this.cameraR.matrixAutoUpdate = false;
  27677. this._cache = {
  27678. focus: null,
  27679. fov: null,
  27680. aspect: null,
  27681. near: null,
  27682. far: null,
  27683. zoom: null,
  27684. eyeSep: null
  27685. };
  27686. }
  27687. update( camera ) {
  27688. const cache = this._cache;
  27689. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  27690. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  27691. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  27692. if ( needsUpdate ) {
  27693. cache.focus = camera.focus;
  27694. cache.fov = camera.fov;
  27695. cache.aspect = camera.aspect * this.aspect;
  27696. cache.near = camera.near;
  27697. cache.far = camera.far;
  27698. cache.zoom = camera.zoom;
  27699. cache.eyeSep = this.eyeSep;
  27700. // Off-axis stereoscopic effect based on
  27701. // http://paulbourke.net/stereographics/stereorender/
  27702. _projectionMatrix.copy( camera.projectionMatrix );
  27703. const eyeSepHalf = cache.eyeSep / 2;
  27704. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  27705. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  27706. let xmin, xmax;
  27707. // translate xOffset
  27708. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  27709. _eyeRight.elements[ 12 ] = eyeSepHalf;
  27710. // for left eye
  27711. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  27712. xmax = ymax * cache.aspect + eyeSepOnProjection;
  27713. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27714. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27715. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  27716. // for right eye
  27717. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  27718. xmax = ymax * cache.aspect - eyeSepOnProjection;
  27719. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27720. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27721. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  27722. }
  27723. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  27724. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  27725. }
  27726. }
  27727. class Clock {
  27728. constructor( autoStart = true ) {
  27729. this.autoStart = autoStart;
  27730. this.startTime = 0;
  27731. this.oldTime = 0;
  27732. this.elapsedTime = 0;
  27733. this.running = false;
  27734. }
  27735. start() {
  27736. this.startTime = now();
  27737. this.oldTime = this.startTime;
  27738. this.elapsedTime = 0;
  27739. this.running = true;
  27740. }
  27741. stop() {
  27742. this.getElapsedTime();
  27743. this.running = false;
  27744. this.autoStart = false;
  27745. }
  27746. getElapsedTime() {
  27747. this.getDelta();
  27748. return this.elapsedTime;
  27749. }
  27750. getDelta() {
  27751. let diff = 0;
  27752. if ( this.autoStart && ! this.running ) {
  27753. this.start();
  27754. return 0;
  27755. }
  27756. if ( this.running ) {
  27757. const newTime = now();
  27758. diff = ( newTime - this.oldTime ) / 1000;
  27759. this.oldTime = newTime;
  27760. this.elapsedTime += diff;
  27761. }
  27762. return diff;
  27763. }
  27764. }
  27765. function now() {
  27766. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  27767. }
  27768. const _position$1 = /*@__PURE__*/ new Vector3();
  27769. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  27770. const _scale$1 = /*@__PURE__*/ new Vector3();
  27771. const _orientation$1 = /*@__PURE__*/ new Vector3();
  27772. class AudioListener extends Object3D {
  27773. constructor() {
  27774. super();
  27775. this.type = 'AudioListener';
  27776. this.context = AudioContext.getContext();
  27777. this.gain = this.context.createGain();
  27778. this.gain.connect( this.context.destination );
  27779. this.filter = null;
  27780. this.timeDelta = 0;
  27781. // private
  27782. this._clock = new Clock();
  27783. }
  27784. getInput() {
  27785. return this.gain;
  27786. }
  27787. removeFilter() {
  27788. if ( this.filter !== null ) {
  27789. this.gain.disconnect( this.filter );
  27790. this.filter.disconnect( this.context.destination );
  27791. this.gain.connect( this.context.destination );
  27792. this.filter = null;
  27793. }
  27794. return this;
  27795. }
  27796. getFilter() {
  27797. return this.filter;
  27798. }
  27799. setFilter( value ) {
  27800. if ( this.filter !== null ) {
  27801. this.gain.disconnect( this.filter );
  27802. this.filter.disconnect( this.context.destination );
  27803. } else {
  27804. this.gain.disconnect( this.context.destination );
  27805. }
  27806. this.filter = value;
  27807. this.gain.connect( this.filter );
  27808. this.filter.connect( this.context.destination );
  27809. return this;
  27810. }
  27811. getMasterVolume() {
  27812. return this.gain.gain.value;
  27813. }
  27814. setMasterVolume( value ) {
  27815. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27816. return this;
  27817. }
  27818. updateMatrixWorld( force ) {
  27819. super.updateMatrixWorld( force );
  27820. const listener = this.context.listener;
  27821. const up = this.up;
  27822. this.timeDelta = this._clock.getDelta();
  27823. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  27824. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  27825. if ( listener.positionX ) {
  27826. // code path for Chrome (see #14393)
  27827. const endTime = this.context.currentTime + this.timeDelta;
  27828. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  27829. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  27830. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  27831. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  27832. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  27833. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  27834. listener.upX.linearRampToValueAtTime( up.x, endTime );
  27835. listener.upY.linearRampToValueAtTime( up.y, endTime );
  27836. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  27837. } else {
  27838. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  27839. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  27840. }
  27841. }
  27842. }
  27843. class Audio extends Object3D {
  27844. constructor( listener ) {
  27845. super();
  27846. this.type = 'Audio';
  27847. this.listener = listener;
  27848. this.context = listener.context;
  27849. this.gain = this.context.createGain();
  27850. this.gain.connect( listener.getInput() );
  27851. this.autoplay = false;
  27852. this.buffer = null;
  27853. this.detune = 0;
  27854. this.loop = false;
  27855. this.loopStart = 0;
  27856. this.loopEnd = 0;
  27857. this.offset = 0;
  27858. this.duration = undefined;
  27859. this.playbackRate = 1;
  27860. this.isPlaying = false;
  27861. this.hasPlaybackControl = true;
  27862. this.source = null;
  27863. this.sourceType = 'empty';
  27864. this._startedAt = 0;
  27865. this._progress = 0;
  27866. this._connected = false;
  27867. this.filters = [];
  27868. }
  27869. getOutput() {
  27870. return this.gain;
  27871. }
  27872. setNodeSource( audioNode ) {
  27873. this.hasPlaybackControl = false;
  27874. this.sourceType = 'audioNode';
  27875. this.source = audioNode;
  27876. this.connect();
  27877. return this;
  27878. }
  27879. setMediaElementSource( mediaElement ) {
  27880. this.hasPlaybackControl = false;
  27881. this.sourceType = 'mediaNode';
  27882. this.source = this.context.createMediaElementSource( mediaElement );
  27883. this.connect();
  27884. return this;
  27885. }
  27886. setMediaStreamSource( mediaStream ) {
  27887. this.hasPlaybackControl = false;
  27888. this.sourceType = 'mediaStreamNode';
  27889. this.source = this.context.createMediaStreamSource( mediaStream );
  27890. this.connect();
  27891. return this;
  27892. }
  27893. setBuffer( audioBuffer ) {
  27894. this.buffer = audioBuffer;
  27895. this.sourceType = 'buffer';
  27896. if ( this.autoplay ) this.play();
  27897. return this;
  27898. }
  27899. play( delay = 0 ) {
  27900. if ( this.isPlaying === true ) {
  27901. console.warn( 'THREE.Audio: Audio is already playing.' );
  27902. return;
  27903. }
  27904. if ( this.hasPlaybackControl === false ) {
  27905. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27906. return;
  27907. }
  27908. this._startedAt = this.context.currentTime + delay;
  27909. const source = this.context.createBufferSource();
  27910. source.buffer = this.buffer;
  27911. source.loop = this.loop;
  27912. source.loopStart = this.loopStart;
  27913. source.loopEnd = this.loopEnd;
  27914. source.onended = this.onEnded.bind( this );
  27915. source.start( this._startedAt, this._progress + this.offset, this.duration );
  27916. this.isPlaying = true;
  27917. this.source = source;
  27918. this.setDetune( this.detune );
  27919. this.setPlaybackRate( this.playbackRate );
  27920. return this.connect();
  27921. }
  27922. pause() {
  27923. if ( this.hasPlaybackControl === false ) {
  27924. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27925. return;
  27926. }
  27927. if ( this.isPlaying === true ) {
  27928. // update current progress
  27929. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  27930. if ( this.loop === true ) {
  27931. // ensure _progress does not exceed duration with looped audios
  27932. this._progress = this._progress % ( this.duration || this.buffer.duration );
  27933. }
  27934. this.source.stop();
  27935. this.source.onended = null;
  27936. this.isPlaying = false;
  27937. }
  27938. return this;
  27939. }
  27940. stop() {
  27941. if ( this.hasPlaybackControl === false ) {
  27942. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27943. return;
  27944. }
  27945. this._progress = 0;
  27946. if ( this.source !== null ) {
  27947. this.source.stop();
  27948. this.source.onended = null;
  27949. }
  27950. this.isPlaying = false;
  27951. return this;
  27952. }
  27953. connect() {
  27954. if ( this.filters.length > 0 ) {
  27955. this.source.connect( this.filters[ 0 ] );
  27956. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  27957. this.filters[ i - 1 ].connect( this.filters[ i ] );
  27958. }
  27959. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  27960. } else {
  27961. this.source.connect( this.getOutput() );
  27962. }
  27963. this._connected = true;
  27964. return this;
  27965. }
  27966. disconnect() {
  27967. if ( this._connected === false ) {
  27968. return;
  27969. }
  27970. if ( this.filters.length > 0 ) {
  27971. this.source.disconnect( this.filters[ 0 ] );
  27972. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  27973. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  27974. }
  27975. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27976. } else {
  27977. this.source.disconnect( this.getOutput() );
  27978. }
  27979. this._connected = false;
  27980. return this;
  27981. }
  27982. getFilters() {
  27983. return this.filters;
  27984. }
  27985. setFilters( value ) {
  27986. if ( ! value ) value = [];
  27987. if ( this._connected === true ) {
  27988. this.disconnect();
  27989. this.filters = value.slice();
  27990. this.connect();
  27991. } else {
  27992. this.filters = value.slice();
  27993. }
  27994. return this;
  27995. }
  27996. setDetune( value ) {
  27997. this.detune = value;
  27998. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  27999. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28000. }
  28001. return this;
  28002. }
  28003. getDetune() {
  28004. return this.detune;
  28005. }
  28006. getFilter() {
  28007. return this.getFilters()[ 0 ];
  28008. }
  28009. setFilter( filter ) {
  28010. return this.setFilters( filter ? [ filter ] : [] );
  28011. }
  28012. setPlaybackRate( value ) {
  28013. if ( this.hasPlaybackControl === false ) {
  28014. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28015. return;
  28016. }
  28017. this.playbackRate = value;
  28018. if ( this.isPlaying === true ) {
  28019. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28020. }
  28021. return this;
  28022. }
  28023. getPlaybackRate() {
  28024. return this.playbackRate;
  28025. }
  28026. onEnded() {
  28027. this.isPlaying = false;
  28028. }
  28029. getLoop() {
  28030. if ( this.hasPlaybackControl === false ) {
  28031. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28032. return false;
  28033. }
  28034. return this.loop;
  28035. }
  28036. setLoop( value ) {
  28037. if ( this.hasPlaybackControl === false ) {
  28038. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28039. return;
  28040. }
  28041. this.loop = value;
  28042. if ( this.isPlaying === true ) {
  28043. this.source.loop = this.loop;
  28044. }
  28045. return this;
  28046. }
  28047. setLoopStart( value ) {
  28048. this.loopStart = value;
  28049. return this;
  28050. }
  28051. setLoopEnd( value ) {
  28052. this.loopEnd = value;
  28053. return this;
  28054. }
  28055. getVolume() {
  28056. return this.gain.gain.value;
  28057. }
  28058. setVolume( value ) {
  28059. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28060. return this;
  28061. }
  28062. }
  28063. const _position = /*@__PURE__*/ new Vector3();
  28064. const _quaternion = /*@__PURE__*/ new Quaternion();
  28065. const _scale = /*@__PURE__*/ new Vector3();
  28066. const _orientation = /*@__PURE__*/ new Vector3();
  28067. class PositionalAudio extends Audio {
  28068. constructor( listener ) {
  28069. super( listener );
  28070. this.panner = this.context.createPanner();
  28071. this.panner.panningModel = 'HRTF';
  28072. this.panner.connect( this.gain );
  28073. }
  28074. connect() {
  28075. super.connect();
  28076. this.panner.connect( this.gain );
  28077. }
  28078. disconnect() {
  28079. super.disconnect();
  28080. this.panner.disconnect( this.gain );
  28081. }
  28082. getOutput() {
  28083. return this.panner;
  28084. }
  28085. getRefDistance() {
  28086. return this.panner.refDistance;
  28087. }
  28088. setRefDistance( value ) {
  28089. this.panner.refDistance = value;
  28090. return this;
  28091. }
  28092. getRolloffFactor() {
  28093. return this.panner.rolloffFactor;
  28094. }
  28095. setRolloffFactor( value ) {
  28096. this.panner.rolloffFactor = value;
  28097. return this;
  28098. }
  28099. getDistanceModel() {
  28100. return this.panner.distanceModel;
  28101. }
  28102. setDistanceModel( value ) {
  28103. this.panner.distanceModel = value;
  28104. return this;
  28105. }
  28106. getMaxDistance() {
  28107. return this.panner.maxDistance;
  28108. }
  28109. setMaxDistance( value ) {
  28110. this.panner.maxDistance = value;
  28111. return this;
  28112. }
  28113. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28114. this.panner.coneInnerAngle = coneInnerAngle;
  28115. this.panner.coneOuterAngle = coneOuterAngle;
  28116. this.panner.coneOuterGain = coneOuterGain;
  28117. return this;
  28118. }
  28119. updateMatrixWorld( force ) {
  28120. super.updateMatrixWorld( force );
  28121. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28122. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28123. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28124. const panner = this.panner;
  28125. if ( panner.positionX ) {
  28126. // code path for Chrome and Firefox (see #14393)
  28127. const endTime = this.context.currentTime + this.listener.timeDelta;
  28128. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28129. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28130. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28131. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28132. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28133. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28134. } else {
  28135. panner.setPosition( _position.x, _position.y, _position.z );
  28136. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28137. }
  28138. }
  28139. }
  28140. class AudioAnalyser {
  28141. constructor( audio, fftSize = 2048 ) {
  28142. this.analyser = audio.context.createAnalyser();
  28143. this.analyser.fftSize = fftSize;
  28144. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28145. audio.getOutput().connect( this.analyser );
  28146. }
  28147. getFrequencyData() {
  28148. this.analyser.getByteFrequencyData( this.data );
  28149. return this.data;
  28150. }
  28151. getAverageFrequency() {
  28152. let value = 0;
  28153. const data = this.getFrequencyData();
  28154. for ( let i = 0; i < data.length; i ++ ) {
  28155. value += data[ i ];
  28156. }
  28157. return value / data.length;
  28158. }
  28159. }
  28160. class PropertyMixer {
  28161. constructor( binding, typeName, valueSize ) {
  28162. this.binding = binding;
  28163. this.valueSize = valueSize;
  28164. let mixFunction,
  28165. mixFunctionAdditive,
  28166. setIdentity;
  28167. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28168. //
  28169. // interpolators can use .buffer as their .result
  28170. // the data then goes to 'incoming'
  28171. //
  28172. // 'accu0' and 'accu1' are used frame-interleaved for
  28173. // the cumulative result and are compared to detect
  28174. // changes
  28175. //
  28176. // 'orig' stores the original state of the property
  28177. //
  28178. // 'add' is used for additive cumulative results
  28179. //
  28180. // 'work' is optional and is only present for quaternion types. It is used
  28181. // to store intermediate quaternion multiplication results
  28182. switch ( typeName ) {
  28183. case 'quaternion':
  28184. mixFunction = this._slerp;
  28185. mixFunctionAdditive = this._slerpAdditive;
  28186. setIdentity = this._setAdditiveIdentityQuaternion;
  28187. this.buffer = new Float64Array( valueSize * 6 );
  28188. this._workIndex = 5;
  28189. break;
  28190. case 'string':
  28191. case 'bool':
  28192. mixFunction = this._select;
  28193. // Use the regular mix function and for additive on these types,
  28194. // additive is not relevant for non-numeric types
  28195. mixFunctionAdditive = this._select;
  28196. setIdentity = this._setAdditiveIdentityOther;
  28197. this.buffer = new Array( valueSize * 5 );
  28198. break;
  28199. default:
  28200. mixFunction = this._lerp;
  28201. mixFunctionAdditive = this._lerpAdditive;
  28202. setIdentity = this._setAdditiveIdentityNumeric;
  28203. this.buffer = new Float64Array( valueSize * 5 );
  28204. }
  28205. this._mixBufferRegion = mixFunction;
  28206. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28207. this._setIdentity = setIdentity;
  28208. this._origIndex = 3;
  28209. this._addIndex = 4;
  28210. this.cumulativeWeight = 0;
  28211. this.cumulativeWeightAdditive = 0;
  28212. this.useCount = 0;
  28213. this.referenceCount = 0;
  28214. }
  28215. // accumulate data in the 'incoming' region into 'accu<i>'
  28216. accumulate( accuIndex, weight ) {
  28217. // note: happily accumulating nothing when weight = 0, the caller knows
  28218. // the weight and shouldn't have made the call in the first place
  28219. const buffer = this.buffer,
  28220. stride = this.valueSize,
  28221. offset = accuIndex * stride + stride;
  28222. let currentWeight = this.cumulativeWeight;
  28223. if ( currentWeight === 0 ) {
  28224. // accuN := incoming * weight
  28225. for ( let i = 0; i !== stride; ++ i ) {
  28226. buffer[ offset + i ] = buffer[ i ];
  28227. }
  28228. currentWeight = weight;
  28229. } else {
  28230. // accuN := accuN + incoming * weight
  28231. currentWeight += weight;
  28232. const mix = weight / currentWeight;
  28233. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28234. }
  28235. this.cumulativeWeight = currentWeight;
  28236. }
  28237. // accumulate data in the 'incoming' region into 'add'
  28238. accumulateAdditive( weight ) {
  28239. const buffer = this.buffer,
  28240. stride = this.valueSize,
  28241. offset = stride * this._addIndex;
  28242. if ( this.cumulativeWeightAdditive === 0 ) {
  28243. // add = identity
  28244. this._setIdentity();
  28245. }
  28246. // add := add + incoming * weight
  28247. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28248. this.cumulativeWeightAdditive += weight;
  28249. }
  28250. // apply the state of 'accu<i>' to the binding when accus differ
  28251. apply( accuIndex ) {
  28252. const stride = this.valueSize,
  28253. buffer = this.buffer,
  28254. offset = accuIndex * stride + stride,
  28255. weight = this.cumulativeWeight,
  28256. weightAdditive = this.cumulativeWeightAdditive,
  28257. binding = this.binding;
  28258. this.cumulativeWeight = 0;
  28259. this.cumulativeWeightAdditive = 0;
  28260. if ( weight < 1 ) {
  28261. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28262. const originalValueOffset = stride * this._origIndex;
  28263. this._mixBufferRegion(
  28264. buffer, offset, originalValueOffset, 1 - weight, stride );
  28265. }
  28266. if ( weightAdditive > 0 ) {
  28267. // accuN := accuN + additive accuN
  28268. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28269. }
  28270. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28271. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28272. // value has changed -> update scene graph
  28273. binding.setValue( buffer, offset );
  28274. break;
  28275. }
  28276. }
  28277. }
  28278. // remember the state of the bound property and copy it to both accus
  28279. saveOriginalState() {
  28280. const binding = this.binding;
  28281. const buffer = this.buffer,
  28282. stride = this.valueSize,
  28283. originalValueOffset = stride * this._origIndex;
  28284. binding.getValue( buffer, originalValueOffset );
  28285. // accu[0..1] := orig -- initially detect changes against the original
  28286. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28287. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28288. }
  28289. // Add to identity for additive
  28290. this._setIdentity();
  28291. this.cumulativeWeight = 0;
  28292. this.cumulativeWeightAdditive = 0;
  28293. }
  28294. // apply the state previously taken via 'saveOriginalState' to the binding
  28295. restoreOriginalState() {
  28296. const originalValueOffset = this.valueSize * 3;
  28297. this.binding.setValue( this.buffer, originalValueOffset );
  28298. }
  28299. _setAdditiveIdentityNumeric() {
  28300. const startIndex = this._addIndex * this.valueSize;
  28301. const endIndex = startIndex + this.valueSize;
  28302. for ( let i = startIndex; i < endIndex; i ++ ) {
  28303. this.buffer[ i ] = 0;
  28304. }
  28305. }
  28306. _setAdditiveIdentityQuaternion() {
  28307. this._setAdditiveIdentityNumeric();
  28308. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  28309. }
  28310. _setAdditiveIdentityOther() {
  28311. const startIndex = this._origIndex * this.valueSize;
  28312. const targetIndex = this._addIndex * this.valueSize;
  28313. for ( let i = 0; i < this.valueSize; i ++ ) {
  28314. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  28315. }
  28316. }
  28317. // mix functions
  28318. _select( buffer, dstOffset, srcOffset, t, stride ) {
  28319. if ( t >= 0.5 ) {
  28320. for ( let i = 0; i !== stride; ++ i ) {
  28321. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  28322. }
  28323. }
  28324. }
  28325. _slerp( buffer, dstOffset, srcOffset, t ) {
  28326. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  28327. }
  28328. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28329. const workOffset = this._workIndex * stride;
  28330. // Store result in intermediate buffer offset
  28331. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  28332. // Slerp to the intermediate result
  28333. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  28334. }
  28335. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  28336. const s = 1 - t;
  28337. for ( let i = 0; i !== stride; ++ i ) {
  28338. const j = dstOffset + i;
  28339. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  28340. }
  28341. }
  28342. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28343. for ( let i = 0; i !== stride; ++ i ) {
  28344. const j = dstOffset + i;
  28345. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  28346. }
  28347. }
  28348. }
  28349. // Characters [].:/ are reserved for track binding syntax.
  28350. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  28351. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  28352. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  28353. // only latin characters, and the unicode \p{L} is not yet supported. So
  28354. // instead, we exclude reserved characters and match everything else.
  28355. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  28356. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28357. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28358. // be matched to parse the rest of the track name.
  28359. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  28360. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28361. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  28362. // Object on target node, and accessor. May not contain reserved
  28363. // characters. Accessor may contain any character except closing bracket.
  28364. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  28365. // Property and accessor. May not contain reserved characters. Accessor may
  28366. // contain any non-bracket characters.
  28367. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  28368. const _trackRe = new RegExp( ''
  28369. + '^'
  28370. + _directoryRe
  28371. + _nodeRe
  28372. + _objectRe
  28373. + _propertyRe
  28374. + '$'
  28375. );
  28376. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  28377. class Composite {
  28378. constructor( targetGroup, path, optionalParsedPath ) {
  28379. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  28380. this._targetGroup = targetGroup;
  28381. this._bindings = targetGroup.subscribe_( path, parsedPath );
  28382. }
  28383. getValue( array, offset ) {
  28384. this.bind(); // bind all binding
  28385. const firstValidIndex = this._targetGroup.nCachedObjects_,
  28386. binding = this._bindings[ firstValidIndex ];
  28387. // and only call .getValue on the first
  28388. if ( binding !== undefined ) binding.getValue( array, offset );
  28389. }
  28390. setValue( array, offset ) {
  28391. const bindings = this._bindings;
  28392. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28393. bindings[ i ].setValue( array, offset );
  28394. }
  28395. }
  28396. bind() {
  28397. const bindings = this._bindings;
  28398. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28399. bindings[ i ].bind();
  28400. }
  28401. }
  28402. unbind() {
  28403. const bindings = this._bindings;
  28404. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28405. bindings[ i ].unbind();
  28406. }
  28407. }
  28408. }
  28409. // Note: This class uses a State pattern on a per-method basis:
  28410. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28411. // prototype version of these methods with one that represents
  28412. // the bound state. When the property is not found, the methods
  28413. // become no-ops.
  28414. class PropertyBinding {
  28415. constructor( rootNode, path, parsedPath ) {
  28416. this.path = path;
  28417. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  28418. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  28419. this.rootNode = rootNode;
  28420. // initial state of these methods that calls 'bind'
  28421. this.getValue = this._getValue_unbound;
  28422. this.setValue = this._setValue_unbound;
  28423. }
  28424. static create( root, path, parsedPath ) {
  28425. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  28426. return new PropertyBinding( root, path, parsedPath );
  28427. } else {
  28428. return new PropertyBinding.Composite( root, path, parsedPath );
  28429. }
  28430. }
  28431. /**
  28432. * Replaces spaces with underscores and removes unsupported characters from
  28433. * node names, to ensure compatibility with parseTrackName().
  28434. *
  28435. * @param {string} name Node name to be sanitized.
  28436. * @return {string}
  28437. */
  28438. static sanitizeNodeName( name ) {
  28439. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  28440. }
  28441. static parseTrackName( trackName ) {
  28442. const matches = _trackRe.exec( trackName );
  28443. if ( matches === null ) {
  28444. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  28445. }
  28446. const results = {
  28447. // directoryName: matches[ 1 ], // (tschw) currently unused
  28448. nodeName: matches[ 2 ],
  28449. objectName: matches[ 3 ],
  28450. objectIndex: matches[ 4 ],
  28451. propertyName: matches[ 5 ], // required
  28452. propertyIndex: matches[ 6 ]
  28453. };
  28454. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  28455. if ( lastDot !== undefined && lastDot !== - 1 ) {
  28456. const objectName = results.nodeName.substring( lastDot + 1 );
  28457. // Object names must be checked against an allowlist. Otherwise, there
  28458. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  28459. // 'bar' could be the objectName, or part of a nodeName (which can
  28460. // include '.' characters).
  28461. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  28462. results.nodeName = results.nodeName.substring( 0, lastDot );
  28463. results.objectName = objectName;
  28464. }
  28465. }
  28466. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  28467. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  28468. }
  28469. return results;
  28470. }
  28471. static findNode( root, nodeName ) {
  28472. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  28473. return root;
  28474. }
  28475. // search into skeleton bones.
  28476. if ( root.skeleton ) {
  28477. const bone = root.skeleton.getBoneByName( nodeName );
  28478. if ( bone !== undefined ) {
  28479. return bone;
  28480. }
  28481. }
  28482. // search into node subtree.
  28483. if ( root.children ) {
  28484. const searchNodeSubtree = function ( children ) {
  28485. for ( let i = 0; i < children.length; i ++ ) {
  28486. const childNode = children[ i ];
  28487. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  28488. return childNode;
  28489. }
  28490. const result = searchNodeSubtree( childNode.children );
  28491. if ( result ) return result;
  28492. }
  28493. return null;
  28494. };
  28495. const subTreeNode = searchNodeSubtree( root.children );
  28496. if ( subTreeNode ) {
  28497. return subTreeNode;
  28498. }
  28499. }
  28500. return null;
  28501. }
  28502. // these are used to "bind" a nonexistent property
  28503. _getValue_unavailable() {}
  28504. _setValue_unavailable() {}
  28505. // Getters
  28506. _getValue_direct( buffer, offset ) {
  28507. buffer[ offset ] = this.targetObject[ this.propertyName ];
  28508. }
  28509. _getValue_array( buffer, offset ) {
  28510. const source = this.resolvedProperty;
  28511. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  28512. buffer[ offset ++ ] = source[ i ];
  28513. }
  28514. }
  28515. _getValue_arrayElement( buffer, offset ) {
  28516. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  28517. }
  28518. _getValue_toArray( buffer, offset ) {
  28519. this.resolvedProperty.toArray( buffer, offset );
  28520. }
  28521. // Direct
  28522. _setValue_direct( buffer, offset ) {
  28523. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28524. }
  28525. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  28526. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28527. this.targetObject.needsUpdate = true;
  28528. }
  28529. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28530. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28531. this.targetObject.matrixWorldNeedsUpdate = true;
  28532. }
  28533. // EntireArray
  28534. _setValue_array( buffer, offset ) {
  28535. const dest = this.resolvedProperty;
  28536. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28537. dest[ i ] = buffer[ offset ++ ];
  28538. }
  28539. }
  28540. _setValue_array_setNeedsUpdate( buffer, offset ) {
  28541. const dest = this.resolvedProperty;
  28542. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28543. dest[ i ] = buffer[ offset ++ ];
  28544. }
  28545. this.targetObject.needsUpdate = true;
  28546. }
  28547. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28548. const dest = this.resolvedProperty;
  28549. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28550. dest[ i ] = buffer[ offset ++ ];
  28551. }
  28552. this.targetObject.matrixWorldNeedsUpdate = true;
  28553. }
  28554. // ArrayElement
  28555. _setValue_arrayElement( buffer, offset ) {
  28556. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28557. }
  28558. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28559. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28560. this.targetObject.needsUpdate = true;
  28561. }
  28562. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28563. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28564. this.targetObject.matrixWorldNeedsUpdate = true;
  28565. }
  28566. // HasToFromArray
  28567. _setValue_fromArray( buffer, offset ) {
  28568. this.resolvedProperty.fromArray( buffer, offset );
  28569. }
  28570. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28571. this.resolvedProperty.fromArray( buffer, offset );
  28572. this.targetObject.needsUpdate = true;
  28573. }
  28574. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28575. this.resolvedProperty.fromArray( buffer, offset );
  28576. this.targetObject.matrixWorldNeedsUpdate = true;
  28577. }
  28578. _getValue_unbound( targetArray, offset ) {
  28579. this.bind();
  28580. this.getValue( targetArray, offset );
  28581. }
  28582. _setValue_unbound( sourceArray, offset ) {
  28583. this.bind();
  28584. this.setValue( sourceArray, offset );
  28585. }
  28586. // create getter / setter pair for a property in the scene graph
  28587. bind() {
  28588. let targetObject = this.node;
  28589. const parsedPath = this.parsedPath;
  28590. const objectName = parsedPath.objectName;
  28591. const propertyName = parsedPath.propertyName;
  28592. let propertyIndex = parsedPath.propertyIndex;
  28593. if ( ! targetObject ) {
  28594. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  28595. this.node = targetObject;
  28596. }
  28597. // set fail state so we can just 'return' on error
  28598. this.getValue = this._getValue_unavailable;
  28599. this.setValue = this._setValue_unavailable;
  28600. // ensure there is a value node
  28601. if ( ! targetObject ) {
  28602. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  28603. return;
  28604. }
  28605. if ( objectName ) {
  28606. let objectIndex = parsedPath.objectIndex;
  28607. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28608. switch ( objectName ) {
  28609. case 'materials':
  28610. if ( ! targetObject.material ) {
  28611. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28612. return;
  28613. }
  28614. if ( ! targetObject.material.materials ) {
  28615. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28616. return;
  28617. }
  28618. targetObject = targetObject.material.materials;
  28619. break;
  28620. case 'bones':
  28621. if ( ! targetObject.skeleton ) {
  28622. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28623. return;
  28624. }
  28625. // potential future optimization: skip this if propertyIndex is already an integer
  28626. // and convert the integer string to a true integer.
  28627. targetObject = targetObject.skeleton.bones;
  28628. // support resolving morphTarget names into indices.
  28629. for ( let i = 0; i < targetObject.length; i ++ ) {
  28630. if ( targetObject[ i ].name === objectIndex ) {
  28631. objectIndex = i;
  28632. break;
  28633. }
  28634. }
  28635. break;
  28636. case 'map':
  28637. if ( 'map' in targetObject ) {
  28638. targetObject = targetObject.map;
  28639. break;
  28640. }
  28641. if ( ! targetObject.material ) {
  28642. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28643. return;
  28644. }
  28645. if ( ! targetObject.material.map ) {
  28646. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  28647. return;
  28648. }
  28649. targetObject = targetObject.material.map;
  28650. break;
  28651. default:
  28652. if ( targetObject[ objectName ] === undefined ) {
  28653. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28654. return;
  28655. }
  28656. targetObject = targetObject[ objectName ];
  28657. }
  28658. if ( objectIndex !== undefined ) {
  28659. if ( targetObject[ objectIndex ] === undefined ) {
  28660. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28661. return;
  28662. }
  28663. targetObject = targetObject[ objectIndex ];
  28664. }
  28665. }
  28666. // resolve property
  28667. const nodeProperty = targetObject[ propertyName ];
  28668. if ( nodeProperty === undefined ) {
  28669. const nodeName = parsedPath.nodeName;
  28670. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28671. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28672. return;
  28673. }
  28674. // determine versioning scheme
  28675. let versioning = this.Versioning.None;
  28676. this.targetObject = targetObject;
  28677. if ( targetObject.needsUpdate !== undefined ) { // material
  28678. versioning = this.Versioning.NeedsUpdate;
  28679. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28680. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28681. }
  28682. // determine how the property gets bound
  28683. let bindingType = this.BindingType.Direct;
  28684. if ( propertyIndex !== undefined ) {
  28685. // access a sub element of the property array (only primitives are supported right now)
  28686. if ( propertyName === 'morphTargetInfluences' ) {
  28687. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28688. // support resolving morphTarget names into indices.
  28689. if ( ! targetObject.geometry ) {
  28690. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28691. return;
  28692. }
  28693. if ( ! targetObject.geometry.morphAttributes ) {
  28694. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28695. return;
  28696. }
  28697. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  28698. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  28699. }
  28700. }
  28701. bindingType = this.BindingType.ArrayElement;
  28702. this.resolvedProperty = nodeProperty;
  28703. this.propertyIndex = propertyIndex;
  28704. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28705. // must use copy for Object3D.Euler/Quaternion
  28706. bindingType = this.BindingType.HasFromToArray;
  28707. this.resolvedProperty = nodeProperty;
  28708. } else if ( Array.isArray( nodeProperty ) ) {
  28709. bindingType = this.BindingType.EntireArray;
  28710. this.resolvedProperty = nodeProperty;
  28711. } else {
  28712. this.propertyName = propertyName;
  28713. }
  28714. // select getter / setter
  28715. this.getValue = this.GetterByBindingType[ bindingType ];
  28716. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28717. }
  28718. unbind() {
  28719. this.node = null;
  28720. // back to the prototype version of getValue / setValue
  28721. // note: avoiding to mutate the shape of 'this' via 'delete'
  28722. this.getValue = this._getValue_unbound;
  28723. this.setValue = this._setValue_unbound;
  28724. }
  28725. }
  28726. PropertyBinding.Composite = Composite;
  28727. PropertyBinding.prototype.BindingType = {
  28728. Direct: 0,
  28729. EntireArray: 1,
  28730. ArrayElement: 2,
  28731. HasFromToArray: 3
  28732. };
  28733. PropertyBinding.prototype.Versioning = {
  28734. None: 0,
  28735. NeedsUpdate: 1,
  28736. MatrixWorldNeedsUpdate: 2
  28737. };
  28738. PropertyBinding.prototype.GetterByBindingType = [
  28739. PropertyBinding.prototype._getValue_direct,
  28740. PropertyBinding.prototype._getValue_array,
  28741. PropertyBinding.prototype._getValue_arrayElement,
  28742. PropertyBinding.prototype._getValue_toArray,
  28743. ];
  28744. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  28745. [
  28746. // Direct
  28747. PropertyBinding.prototype._setValue_direct,
  28748. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  28749. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  28750. ], [
  28751. // EntireArray
  28752. PropertyBinding.prototype._setValue_array,
  28753. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  28754. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  28755. ], [
  28756. // ArrayElement
  28757. PropertyBinding.prototype._setValue_arrayElement,
  28758. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  28759. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  28760. ], [
  28761. // HasToFromArray
  28762. PropertyBinding.prototype._setValue_fromArray,
  28763. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  28764. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  28765. ]
  28766. ];
  28767. /**
  28768. *
  28769. * A group of objects that receives a shared animation state.
  28770. *
  28771. * Usage:
  28772. *
  28773. * - Add objects you would otherwise pass as 'root' to the
  28774. * constructor or the .clipAction method of AnimationMixer.
  28775. *
  28776. * - Instead pass this object as 'root'.
  28777. *
  28778. * - You can also add and remove objects later when the mixer
  28779. * is running.
  28780. *
  28781. * Note:
  28782. *
  28783. * Objects of this class appear as one object to the mixer,
  28784. * so cache control of the individual objects must be done
  28785. * on the group.
  28786. *
  28787. * Limitation:
  28788. *
  28789. * - The animated properties must be compatible among the
  28790. * all objects in the group.
  28791. *
  28792. * - A single property can either be controlled through a
  28793. * target group or directly, but not both.
  28794. */
  28795. class AnimationObjectGroup {
  28796. constructor() {
  28797. this.isAnimationObjectGroup = true;
  28798. this.uuid = generateUUID();
  28799. // cached objects followed by the active ones
  28800. this._objects = Array.prototype.slice.call( arguments );
  28801. this.nCachedObjects_ = 0; // threshold
  28802. // note: read by PropertyBinding.Composite
  28803. const indices = {};
  28804. this._indicesByUUID = indices; // for bookkeeping
  28805. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28806. indices[ arguments[ i ].uuid ] = i;
  28807. }
  28808. this._paths = []; // inside: string
  28809. this._parsedPaths = []; // inside: { we don't care, here }
  28810. this._bindings = []; // inside: Array< PropertyBinding >
  28811. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  28812. const scope = this;
  28813. this.stats = {
  28814. objects: {
  28815. get total() {
  28816. return scope._objects.length;
  28817. },
  28818. get inUse() {
  28819. return this.total - scope.nCachedObjects_;
  28820. }
  28821. },
  28822. get bindingsPerObject() {
  28823. return scope._bindings.length;
  28824. }
  28825. };
  28826. }
  28827. add() {
  28828. const objects = this._objects,
  28829. indicesByUUID = this._indicesByUUID,
  28830. paths = this._paths,
  28831. parsedPaths = this._parsedPaths,
  28832. bindings = this._bindings,
  28833. nBindings = bindings.length;
  28834. let knownObject = undefined,
  28835. nObjects = objects.length,
  28836. nCachedObjects = this.nCachedObjects_;
  28837. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28838. const object = arguments[ i ],
  28839. uuid = object.uuid;
  28840. let index = indicesByUUID[ uuid ];
  28841. if ( index === undefined ) {
  28842. // unknown object -> add it to the ACTIVE region
  28843. index = nObjects ++;
  28844. indicesByUUID[ uuid ] = index;
  28845. objects.push( object );
  28846. // accounting is done, now do the same for all bindings
  28847. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28848. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28849. }
  28850. } else if ( index < nCachedObjects ) {
  28851. knownObject = objects[ index ];
  28852. // move existing object to the ACTIVE region
  28853. const firstActiveIndex = -- nCachedObjects,
  28854. lastCachedObject = objects[ firstActiveIndex ];
  28855. indicesByUUID[ lastCachedObject.uuid ] = index;
  28856. objects[ index ] = lastCachedObject;
  28857. indicesByUUID[ uuid ] = firstActiveIndex;
  28858. objects[ firstActiveIndex ] = object;
  28859. // accounting is done, now do the same for all bindings
  28860. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28861. const bindingsForPath = bindings[ j ],
  28862. lastCached = bindingsForPath[ firstActiveIndex ];
  28863. let binding = bindingsForPath[ index ];
  28864. bindingsForPath[ index ] = lastCached;
  28865. if ( binding === undefined ) {
  28866. // since we do not bother to create new bindings
  28867. // for objects that are cached, the binding may
  28868. // or may not exist
  28869. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  28870. }
  28871. bindingsForPath[ firstActiveIndex ] = binding;
  28872. }
  28873. } else if ( objects[ index ] !== knownObject ) {
  28874. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  28875. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  28876. } // else the object is already where we want it to be
  28877. } // for arguments
  28878. this.nCachedObjects_ = nCachedObjects;
  28879. }
  28880. remove() {
  28881. const objects = this._objects,
  28882. indicesByUUID = this._indicesByUUID,
  28883. bindings = this._bindings,
  28884. nBindings = bindings.length;
  28885. let nCachedObjects = this.nCachedObjects_;
  28886. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28887. const object = arguments[ i ],
  28888. uuid = object.uuid,
  28889. index = indicesByUUID[ uuid ];
  28890. if ( index !== undefined && index >= nCachedObjects ) {
  28891. // move existing object into the CACHED region
  28892. const lastCachedIndex = nCachedObjects ++,
  28893. firstActiveObject = objects[ lastCachedIndex ];
  28894. indicesByUUID[ firstActiveObject.uuid ] = index;
  28895. objects[ index ] = firstActiveObject;
  28896. indicesByUUID[ uuid ] = lastCachedIndex;
  28897. objects[ lastCachedIndex ] = object;
  28898. // accounting is done, now do the same for all bindings
  28899. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28900. const bindingsForPath = bindings[ j ],
  28901. firstActive = bindingsForPath[ lastCachedIndex ],
  28902. binding = bindingsForPath[ index ];
  28903. bindingsForPath[ index ] = firstActive;
  28904. bindingsForPath[ lastCachedIndex ] = binding;
  28905. }
  28906. }
  28907. } // for arguments
  28908. this.nCachedObjects_ = nCachedObjects;
  28909. }
  28910. // remove & forget
  28911. uncache() {
  28912. const objects = this._objects,
  28913. indicesByUUID = this._indicesByUUID,
  28914. bindings = this._bindings,
  28915. nBindings = bindings.length;
  28916. let nCachedObjects = this.nCachedObjects_,
  28917. nObjects = objects.length;
  28918. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28919. const object = arguments[ i ],
  28920. uuid = object.uuid,
  28921. index = indicesByUUID[ uuid ];
  28922. if ( index !== undefined ) {
  28923. delete indicesByUUID[ uuid ];
  28924. if ( index < nCachedObjects ) {
  28925. // object is cached, shrink the CACHED region
  28926. const firstActiveIndex = -- nCachedObjects,
  28927. lastCachedObject = objects[ firstActiveIndex ],
  28928. lastIndex = -- nObjects,
  28929. lastObject = objects[ lastIndex ];
  28930. // last cached object takes this object's place
  28931. indicesByUUID[ lastCachedObject.uuid ] = index;
  28932. objects[ index ] = lastCachedObject;
  28933. // last object goes to the activated slot and pop
  28934. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  28935. objects[ firstActiveIndex ] = lastObject;
  28936. objects.pop();
  28937. // accounting is done, now do the same for all bindings
  28938. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28939. const bindingsForPath = bindings[ j ],
  28940. lastCached = bindingsForPath[ firstActiveIndex ],
  28941. last = bindingsForPath[ lastIndex ];
  28942. bindingsForPath[ index ] = lastCached;
  28943. bindingsForPath[ firstActiveIndex ] = last;
  28944. bindingsForPath.pop();
  28945. }
  28946. } else {
  28947. // object is active, just swap with the last and pop
  28948. const lastIndex = -- nObjects,
  28949. lastObject = objects[ lastIndex ];
  28950. if ( lastIndex > 0 ) {
  28951. indicesByUUID[ lastObject.uuid ] = index;
  28952. }
  28953. objects[ index ] = lastObject;
  28954. objects.pop();
  28955. // accounting is done, now do the same for all bindings
  28956. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28957. const bindingsForPath = bindings[ j ];
  28958. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  28959. bindingsForPath.pop();
  28960. }
  28961. } // cached or active
  28962. } // if object is known
  28963. } // for arguments
  28964. this.nCachedObjects_ = nCachedObjects;
  28965. }
  28966. // Internal interface used by befriended PropertyBinding.Composite:
  28967. subscribe_( path, parsedPath ) {
  28968. // returns an array of bindings for the given path that is changed
  28969. // according to the contained objects in the group
  28970. const indicesByPath = this._bindingsIndicesByPath;
  28971. let index = indicesByPath[ path ];
  28972. const bindings = this._bindings;
  28973. if ( index !== undefined ) return bindings[ index ];
  28974. const paths = this._paths,
  28975. parsedPaths = this._parsedPaths,
  28976. objects = this._objects,
  28977. nObjects = objects.length,
  28978. nCachedObjects = this.nCachedObjects_,
  28979. bindingsForPath = new Array( nObjects );
  28980. index = bindings.length;
  28981. indicesByPath[ path ] = index;
  28982. paths.push( path );
  28983. parsedPaths.push( parsedPath );
  28984. bindings.push( bindingsForPath );
  28985. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  28986. const object = objects[ i ];
  28987. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  28988. }
  28989. return bindingsForPath;
  28990. }
  28991. unsubscribe_( path ) {
  28992. // tells the group to forget about a property path and no longer
  28993. // update the array previously obtained with 'subscribe_'
  28994. const indicesByPath = this._bindingsIndicesByPath,
  28995. index = indicesByPath[ path ];
  28996. if ( index !== undefined ) {
  28997. const paths = this._paths,
  28998. parsedPaths = this._parsedPaths,
  28999. bindings = this._bindings,
  29000. lastBindingsIndex = bindings.length - 1,
  29001. lastBindings = bindings[ lastBindingsIndex ],
  29002. lastBindingsPath = path[ lastBindingsIndex ];
  29003. indicesByPath[ lastBindingsPath ] = index;
  29004. bindings[ index ] = lastBindings;
  29005. bindings.pop();
  29006. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29007. parsedPaths.pop();
  29008. paths[ index ] = paths[ lastBindingsIndex ];
  29009. paths.pop();
  29010. }
  29011. }
  29012. }
  29013. class AnimationAction {
  29014. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29015. this._mixer = mixer;
  29016. this._clip = clip;
  29017. this._localRoot = localRoot;
  29018. this.blendMode = blendMode;
  29019. const tracks = clip.tracks,
  29020. nTracks = tracks.length,
  29021. interpolants = new Array( nTracks );
  29022. const interpolantSettings = {
  29023. endingStart: ZeroCurvatureEnding,
  29024. endingEnd: ZeroCurvatureEnding
  29025. };
  29026. for ( let i = 0; i !== nTracks; ++ i ) {
  29027. const interpolant = tracks[ i ].createInterpolant( null );
  29028. interpolants[ i ] = interpolant;
  29029. interpolant.settings = interpolantSettings;
  29030. }
  29031. this._interpolantSettings = interpolantSettings;
  29032. this._interpolants = interpolants; // bound by the mixer
  29033. // inside: PropertyMixer (managed by the mixer)
  29034. this._propertyBindings = new Array( nTracks );
  29035. this._cacheIndex = null; // for the memory manager
  29036. this._byClipCacheIndex = null; // for the memory manager
  29037. this._timeScaleInterpolant = null;
  29038. this._weightInterpolant = null;
  29039. this.loop = LoopRepeat;
  29040. this._loopCount = - 1;
  29041. // global mixer time when the action is to be started
  29042. // it's set back to 'null' upon start of the action
  29043. this._startTime = null;
  29044. // scaled local time of the action
  29045. // gets clamped or wrapped to 0..clip.duration according to loop
  29046. this.time = 0;
  29047. this.timeScale = 1;
  29048. this._effectiveTimeScale = 1;
  29049. this.weight = 1;
  29050. this._effectiveWeight = 1;
  29051. this.repetitions = Infinity; // no. of repetitions when looping
  29052. this.paused = false; // true -> zero effective time scale
  29053. this.enabled = true; // false -> zero effective weight
  29054. this.clampWhenFinished = false;// keep feeding the last frame?
  29055. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29056. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29057. }
  29058. // State & Scheduling
  29059. play() {
  29060. this._mixer._activateAction( this );
  29061. return this;
  29062. }
  29063. stop() {
  29064. this._mixer._deactivateAction( this );
  29065. return this.reset();
  29066. }
  29067. reset() {
  29068. this.paused = false;
  29069. this.enabled = true;
  29070. this.time = 0; // restart clip
  29071. this._loopCount = - 1;// forget previous loops
  29072. this._startTime = null;// forget scheduling
  29073. return this.stopFading().stopWarping();
  29074. }
  29075. isRunning() {
  29076. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29077. this._startTime === null && this._mixer._isActiveAction( this );
  29078. }
  29079. // return true when play has been called
  29080. isScheduled() {
  29081. return this._mixer._isActiveAction( this );
  29082. }
  29083. startAt( time ) {
  29084. this._startTime = time;
  29085. return this;
  29086. }
  29087. setLoop( mode, repetitions ) {
  29088. this.loop = mode;
  29089. this.repetitions = repetitions;
  29090. return this;
  29091. }
  29092. // Weight
  29093. // set the weight stopping any scheduled fading
  29094. // although .enabled = false yields an effective weight of zero, this
  29095. // method does *not* change .enabled, because it would be confusing
  29096. setEffectiveWeight( weight ) {
  29097. this.weight = weight;
  29098. // note: same logic as when updated at runtime
  29099. this._effectiveWeight = this.enabled ? weight : 0;
  29100. return this.stopFading();
  29101. }
  29102. // return the weight considering fading and .enabled
  29103. getEffectiveWeight() {
  29104. return this._effectiveWeight;
  29105. }
  29106. fadeIn( duration ) {
  29107. return this._scheduleFading( duration, 0, 1 );
  29108. }
  29109. fadeOut( duration ) {
  29110. return this._scheduleFading( duration, 1, 0 );
  29111. }
  29112. crossFadeFrom( fadeOutAction, duration, warp ) {
  29113. fadeOutAction.fadeOut( duration );
  29114. this.fadeIn( duration );
  29115. if ( warp ) {
  29116. const fadeInDuration = this._clip.duration,
  29117. fadeOutDuration = fadeOutAction._clip.duration,
  29118. startEndRatio = fadeOutDuration / fadeInDuration,
  29119. endStartRatio = fadeInDuration / fadeOutDuration;
  29120. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29121. this.warp( endStartRatio, 1.0, duration );
  29122. }
  29123. return this;
  29124. }
  29125. crossFadeTo( fadeInAction, duration, warp ) {
  29126. return fadeInAction.crossFadeFrom( this, duration, warp );
  29127. }
  29128. stopFading() {
  29129. const weightInterpolant = this._weightInterpolant;
  29130. if ( weightInterpolant !== null ) {
  29131. this._weightInterpolant = null;
  29132. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29133. }
  29134. return this;
  29135. }
  29136. // Time Scale Control
  29137. // set the time scale stopping any scheduled warping
  29138. // although .paused = true yields an effective time scale of zero, this
  29139. // method does *not* change .paused, because it would be confusing
  29140. setEffectiveTimeScale( timeScale ) {
  29141. this.timeScale = timeScale;
  29142. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29143. return this.stopWarping();
  29144. }
  29145. // return the time scale considering warping and .paused
  29146. getEffectiveTimeScale() {
  29147. return this._effectiveTimeScale;
  29148. }
  29149. setDuration( duration ) {
  29150. this.timeScale = this._clip.duration / duration;
  29151. return this.stopWarping();
  29152. }
  29153. syncWith( action ) {
  29154. this.time = action.time;
  29155. this.timeScale = action.timeScale;
  29156. return this.stopWarping();
  29157. }
  29158. halt( duration ) {
  29159. return this.warp( this._effectiveTimeScale, 0, duration );
  29160. }
  29161. warp( startTimeScale, endTimeScale, duration ) {
  29162. const mixer = this._mixer,
  29163. now = mixer.time,
  29164. timeScale = this.timeScale;
  29165. let interpolant = this._timeScaleInterpolant;
  29166. if ( interpolant === null ) {
  29167. interpolant = mixer._lendControlInterpolant();
  29168. this._timeScaleInterpolant = interpolant;
  29169. }
  29170. const times = interpolant.parameterPositions,
  29171. values = interpolant.sampleValues;
  29172. times[ 0 ] = now;
  29173. times[ 1 ] = now + duration;
  29174. values[ 0 ] = startTimeScale / timeScale;
  29175. values[ 1 ] = endTimeScale / timeScale;
  29176. return this;
  29177. }
  29178. stopWarping() {
  29179. const timeScaleInterpolant = this._timeScaleInterpolant;
  29180. if ( timeScaleInterpolant !== null ) {
  29181. this._timeScaleInterpolant = null;
  29182. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29183. }
  29184. return this;
  29185. }
  29186. // Object Accessors
  29187. getMixer() {
  29188. return this._mixer;
  29189. }
  29190. getClip() {
  29191. return this._clip;
  29192. }
  29193. getRoot() {
  29194. return this._localRoot || this._mixer._root;
  29195. }
  29196. // Interna
  29197. _update( time, deltaTime, timeDirection, accuIndex ) {
  29198. // called by the mixer
  29199. if ( ! this.enabled ) {
  29200. // call ._updateWeight() to update ._effectiveWeight
  29201. this._updateWeight( time );
  29202. return;
  29203. }
  29204. const startTime = this._startTime;
  29205. if ( startTime !== null ) {
  29206. // check for scheduled start of action
  29207. const timeRunning = ( time - startTime ) * timeDirection;
  29208. if ( timeRunning < 0 || timeDirection === 0 ) {
  29209. deltaTime = 0;
  29210. } else {
  29211. this._startTime = null; // unschedule
  29212. deltaTime = timeDirection * timeRunning;
  29213. }
  29214. }
  29215. // apply time scale and advance time
  29216. deltaTime *= this._updateTimeScale( time );
  29217. const clipTime = this._updateTime( deltaTime );
  29218. // note: _updateTime may disable the action resulting in
  29219. // an effective weight of 0
  29220. const weight = this._updateWeight( time );
  29221. if ( weight > 0 ) {
  29222. const interpolants = this._interpolants;
  29223. const propertyMixers = this._propertyBindings;
  29224. switch ( this.blendMode ) {
  29225. case AdditiveAnimationBlendMode:
  29226. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29227. interpolants[ j ].evaluate( clipTime );
  29228. propertyMixers[ j ].accumulateAdditive( weight );
  29229. }
  29230. break;
  29231. case NormalAnimationBlendMode:
  29232. default:
  29233. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29234. interpolants[ j ].evaluate( clipTime );
  29235. propertyMixers[ j ].accumulate( accuIndex, weight );
  29236. }
  29237. }
  29238. }
  29239. }
  29240. _updateWeight( time ) {
  29241. let weight = 0;
  29242. if ( this.enabled ) {
  29243. weight = this.weight;
  29244. const interpolant = this._weightInterpolant;
  29245. if ( interpolant !== null ) {
  29246. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29247. weight *= interpolantValue;
  29248. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29249. this.stopFading();
  29250. if ( interpolantValue === 0 ) {
  29251. // faded out, disable
  29252. this.enabled = false;
  29253. }
  29254. }
  29255. }
  29256. }
  29257. this._effectiveWeight = weight;
  29258. return weight;
  29259. }
  29260. _updateTimeScale( time ) {
  29261. let timeScale = 0;
  29262. if ( ! this.paused ) {
  29263. timeScale = this.timeScale;
  29264. const interpolant = this._timeScaleInterpolant;
  29265. if ( interpolant !== null ) {
  29266. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29267. timeScale *= interpolantValue;
  29268. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29269. this.stopWarping();
  29270. if ( timeScale === 0 ) {
  29271. // motion has halted, pause
  29272. this.paused = true;
  29273. } else {
  29274. // warp done - apply final time scale
  29275. this.timeScale = timeScale;
  29276. }
  29277. }
  29278. }
  29279. }
  29280. this._effectiveTimeScale = timeScale;
  29281. return timeScale;
  29282. }
  29283. _updateTime( deltaTime ) {
  29284. const duration = this._clip.duration;
  29285. const loop = this.loop;
  29286. let time = this.time + deltaTime;
  29287. let loopCount = this._loopCount;
  29288. const pingPong = ( loop === LoopPingPong );
  29289. if ( deltaTime === 0 ) {
  29290. if ( loopCount === - 1 ) return time;
  29291. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29292. }
  29293. if ( loop === LoopOnce ) {
  29294. if ( loopCount === - 1 ) {
  29295. // just started
  29296. this._loopCount = 0;
  29297. this._setEndings( true, true, false );
  29298. }
  29299. handle_stop: {
  29300. if ( time >= duration ) {
  29301. time = duration;
  29302. } else if ( time < 0 ) {
  29303. time = 0;
  29304. } else {
  29305. this.time = time;
  29306. break handle_stop;
  29307. }
  29308. if ( this.clampWhenFinished ) this.paused = true;
  29309. else this.enabled = false;
  29310. this.time = time;
  29311. this._mixer.dispatchEvent( {
  29312. type: 'finished', action: this,
  29313. direction: deltaTime < 0 ? - 1 : 1
  29314. } );
  29315. }
  29316. } else { // repetitive Repeat or PingPong
  29317. if ( loopCount === - 1 ) {
  29318. // just started
  29319. if ( deltaTime >= 0 ) {
  29320. loopCount = 0;
  29321. this._setEndings( true, this.repetitions === 0, pingPong );
  29322. } else {
  29323. // when looping in reverse direction, the initial
  29324. // transition through zero counts as a repetition,
  29325. // so leave loopCount at -1
  29326. this._setEndings( this.repetitions === 0, true, pingPong );
  29327. }
  29328. }
  29329. if ( time >= duration || time < 0 ) {
  29330. // wrap around
  29331. const loopDelta = Math.floor( time / duration ); // signed
  29332. time -= duration * loopDelta;
  29333. loopCount += Math.abs( loopDelta );
  29334. const pending = this.repetitions - loopCount;
  29335. if ( pending <= 0 ) {
  29336. // have to stop (switch state, clamp time, fire event)
  29337. if ( this.clampWhenFinished ) this.paused = true;
  29338. else this.enabled = false;
  29339. time = deltaTime > 0 ? duration : 0;
  29340. this.time = time;
  29341. this._mixer.dispatchEvent( {
  29342. type: 'finished', action: this,
  29343. direction: deltaTime > 0 ? 1 : - 1
  29344. } );
  29345. } else {
  29346. // keep running
  29347. if ( pending === 1 ) {
  29348. // entering the last round
  29349. const atStart = deltaTime < 0;
  29350. this._setEndings( atStart, ! atStart, pingPong );
  29351. } else {
  29352. this._setEndings( false, false, pingPong );
  29353. }
  29354. this._loopCount = loopCount;
  29355. this.time = time;
  29356. this._mixer.dispatchEvent( {
  29357. type: 'loop', action: this, loopDelta: loopDelta
  29358. } );
  29359. }
  29360. } else {
  29361. this.time = time;
  29362. }
  29363. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  29364. // invert time for the "pong round"
  29365. return duration - time;
  29366. }
  29367. }
  29368. return time;
  29369. }
  29370. _setEndings( atStart, atEnd, pingPong ) {
  29371. const settings = this._interpolantSettings;
  29372. if ( pingPong ) {
  29373. settings.endingStart = ZeroSlopeEnding;
  29374. settings.endingEnd = ZeroSlopeEnding;
  29375. } else {
  29376. // assuming for LoopOnce atStart == atEnd == true
  29377. if ( atStart ) {
  29378. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29379. } else {
  29380. settings.endingStart = WrapAroundEnding;
  29381. }
  29382. if ( atEnd ) {
  29383. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29384. } else {
  29385. settings.endingEnd = WrapAroundEnding;
  29386. }
  29387. }
  29388. }
  29389. _scheduleFading( duration, weightNow, weightThen ) {
  29390. const mixer = this._mixer, now = mixer.time;
  29391. let interpolant = this._weightInterpolant;
  29392. if ( interpolant === null ) {
  29393. interpolant = mixer._lendControlInterpolant();
  29394. this._weightInterpolant = interpolant;
  29395. }
  29396. const times = interpolant.parameterPositions,
  29397. values = interpolant.sampleValues;
  29398. times[ 0 ] = now;
  29399. values[ 0 ] = weightNow;
  29400. times[ 1 ] = now + duration;
  29401. values[ 1 ] = weightThen;
  29402. return this;
  29403. }
  29404. }
  29405. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  29406. class AnimationMixer extends EventDispatcher {
  29407. constructor( root ) {
  29408. super();
  29409. this._root = root;
  29410. this._initMemoryManager();
  29411. this._accuIndex = 0;
  29412. this.time = 0;
  29413. this.timeScale = 1.0;
  29414. }
  29415. _bindAction( action, prototypeAction ) {
  29416. const root = action._localRoot || this._root,
  29417. tracks = action._clip.tracks,
  29418. nTracks = tracks.length,
  29419. bindings = action._propertyBindings,
  29420. interpolants = action._interpolants,
  29421. rootUuid = root.uuid,
  29422. bindingsByRoot = this._bindingsByRootAndName;
  29423. let bindingsByName = bindingsByRoot[ rootUuid ];
  29424. if ( bindingsByName === undefined ) {
  29425. bindingsByName = {};
  29426. bindingsByRoot[ rootUuid ] = bindingsByName;
  29427. }
  29428. for ( let i = 0; i !== nTracks; ++ i ) {
  29429. const track = tracks[ i ],
  29430. trackName = track.name;
  29431. let binding = bindingsByName[ trackName ];
  29432. if ( binding !== undefined ) {
  29433. ++ binding.referenceCount;
  29434. bindings[ i ] = binding;
  29435. } else {
  29436. binding = bindings[ i ];
  29437. if ( binding !== undefined ) {
  29438. // existing binding, make sure the cache knows
  29439. if ( binding._cacheIndex === null ) {
  29440. ++ binding.referenceCount;
  29441. this._addInactiveBinding( binding, rootUuid, trackName );
  29442. }
  29443. continue;
  29444. }
  29445. const path = prototypeAction && prototypeAction.
  29446. _propertyBindings[ i ].binding.parsedPath;
  29447. binding = new PropertyMixer(
  29448. PropertyBinding.create( root, trackName, path ),
  29449. track.ValueTypeName, track.getValueSize() );
  29450. ++ binding.referenceCount;
  29451. this._addInactiveBinding( binding, rootUuid, trackName );
  29452. bindings[ i ] = binding;
  29453. }
  29454. interpolants[ i ].resultBuffer = binding.buffer;
  29455. }
  29456. }
  29457. _activateAction( action ) {
  29458. if ( ! this._isActiveAction( action ) ) {
  29459. if ( action._cacheIndex === null ) {
  29460. // this action has been forgotten by the cache, but the user
  29461. // appears to be still using it -> rebind
  29462. const rootUuid = ( action._localRoot || this._root ).uuid,
  29463. clipUuid = action._clip.uuid,
  29464. actionsForClip = this._actionsByClip[ clipUuid ];
  29465. this._bindAction( action,
  29466. actionsForClip && actionsForClip.knownActions[ 0 ] );
  29467. this._addInactiveAction( action, clipUuid, rootUuid );
  29468. }
  29469. const bindings = action._propertyBindings;
  29470. // increment reference counts / sort out state
  29471. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29472. const binding = bindings[ i ];
  29473. if ( binding.useCount ++ === 0 ) {
  29474. this._lendBinding( binding );
  29475. binding.saveOriginalState();
  29476. }
  29477. }
  29478. this._lendAction( action );
  29479. }
  29480. }
  29481. _deactivateAction( action ) {
  29482. if ( this._isActiveAction( action ) ) {
  29483. const bindings = action._propertyBindings;
  29484. // decrement reference counts / sort out state
  29485. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29486. const binding = bindings[ i ];
  29487. if ( -- binding.useCount === 0 ) {
  29488. binding.restoreOriginalState();
  29489. this._takeBackBinding( binding );
  29490. }
  29491. }
  29492. this._takeBackAction( action );
  29493. }
  29494. }
  29495. // Memory manager
  29496. _initMemoryManager() {
  29497. this._actions = []; // 'nActiveActions' followed by inactive ones
  29498. this._nActiveActions = 0;
  29499. this._actionsByClip = {};
  29500. // inside:
  29501. // {
  29502. // knownActions: Array< AnimationAction > - used as prototypes
  29503. // actionByRoot: AnimationAction - lookup
  29504. // }
  29505. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  29506. this._nActiveBindings = 0;
  29507. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  29508. this._controlInterpolants = []; // same game as above
  29509. this._nActiveControlInterpolants = 0;
  29510. const scope = this;
  29511. this.stats = {
  29512. actions: {
  29513. get total() {
  29514. return scope._actions.length;
  29515. },
  29516. get inUse() {
  29517. return scope._nActiveActions;
  29518. }
  29519. },
  29520. bindings: {
  29521. get total() {
  29522. return scope._bindings.length;
  29523. },
  29524. get inUse() {
  29525. return scope._nActiveBindings;
  29526. }
  29527. },
  29528. controlInterpolants: {
  29529. get total() {
  29530. return scope._controlInterpolants.length;
  29531. },
  29532. get inUse() {
  29533. return scope._nActiveControlInterpolants;
  29534. }
  29535. }
  29536. };
  29537. }
  29538. // Memory management for AnimationAction objects
  29539. _isActiveAction( action ) {
  29540. const index = action._cacheIndex;
  29541. return index !== null && index < this._nActiveActions;
  29542. }
  29543. _addInactiveAction( action, clipUuid, rootUuid ) {
  29544. const actions = this._actions,
  29545. actionsByClip = this._actionsByClip;
  29546. let actionsForClip = actionsByClip[ clipUuid ];
  29547. if ( actionsForClip === undefined ) {
  29548. actionsForClip = {
  29549. knownActions: [ action ],
  29550. actionByRoot: {}
  29551. };
  29552. action._byClipCacheIndex = 0;
  29553. actionsByClip[ clipUuid ] = actionsForClip;
  29554. } else {
  29555. const knownActions = actionsForClip.knownActions;
  29556. action._byClipCacheIndex = knownActions.length;
  29557. knownActions.push( action );
  29558. }
  29559. action._cacheIndex = actions.length;
  29560. actions.push( action );
  29561. actionsForClip.actionByRoot[ rootUuid ] = action;
  29562. }
  29563. _removeInactiveAction( action ) {
  29564. const actions = this._actions,
  29565. lastInactiveAction = actions[ actions.length - 1 ],
  29566. cacheIndex = action._cacheIndex;
  29567. lastInactiveAction._cacheIndex = cacheIndex;
  29568. actions[ cacheIndex ] = lastInactiveAction;
  29569. actions.pop();
  29570. action._cacheIndex = null;
  29571. const clipUuid = action._clip.uuid,
  29572. actionsByClip = this._actionsByClip,
  29573. actionsForClip = actionsByClip[ clipUuid ],
  29574. knownActionsForClip = actionsForClip.knownActions,
  29575. lastKnownAction =
  29576. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29577. byClipCacheIndex = action._byClipCacheIndex;
  29578. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29579. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29580. knownActionsForClip.pop();
  29581. action._byClipCacheIndex = null;
  29582. const actionByRoot = actionsForClip.actionByRoot,
  29583. rootUuid = ( action._localRoot || this._root ).uuid;
  29584. delete actionByRoot[ rootUuid ];
  29585. if ( knownActionsForClip.length === 0 ) {
  29586. delete actionsByClip[ clipUuid ];
  29587. }
  29588. this._removeInactiveBindingsForAction( action );
  29589. }
  29590. _removeInactiveBindingsForAction( action ) {
  29591. const bindings = action._propertyBindings;
  29592. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29593. const binding = bindings[ i ];
  29594. if ( -- binding.referenceCount === 0 ) {
  29595. this._removeInactiveBinding( binding );
  29596. }
  29597. }
  29598. }
  29599. _lendAction( action ) {
  29600. // [ active actions | inactive actions ]
  29601. // [ active actions >| inactive actions ]
  29602. // s a
  29603. // <-swap->
  29604. // a s
  29605. const actions = this._actions,
  29606. prevIndex = action._cacheIndex,
  29607. lastActiveIndex = this._nActiveActions ++,
  29608. firstInactiveAction = actions[ lastActiveIndex ];
  29609. action._cacheIndex = lastActiveIndex;
  29610. actions[ lastActiveIndex ] = action;
  29611. firstInactiveAction._cacheIndex = prevIndex;
  29612. actions[ prevIndex ] = firstInactiveAction;
  29613. }
  29614. _takeBackAction( action ) {
  29615. // [ active actions | inactive actions ]
  29616. // [ active actions |< inactive actions ]
  29617. // a s
  29618. // <-swap->
  29619. // s a
  29620. const actions = this._actions,
  29621. prevIndex = action._cacheIndex,
  29622. firstInactiveIndex = -- this._nActiveActions,
  29623. lastActiveAction = actions[ firstInactiveIndex ];
  29624. action._cacheIndex = firstInactiveIndex;
  29625. actions[ firstInactiveIndex ] = action;
  29626. lastActiveAction._cacheIndex = prevIndex;
  29627. actions[ prevIndex ] = lastActiveAction;
  29628. }
  29629. // Memory management for PropertyMixer objects
  29630. _addInactiveBinding( binding, rootUuid, trackName ) {
  29631. const bindingsByRoot = this._bindingsByRootAndName,
  29632. bindings = this._bindings;
  29633. let bindingByName = bindingsByRoot[ rootUuid ];
  29634. if ( bindingByName === undefined ) {
  29635. bindingByName = {};
  29636. bindingsByRoot[ rootUuid ] = bindingByName;
  29637. }
  29638. bindingByName[ trackName ] = binding;
  29639. binding._cacheIndex = bindings.length;
  29640. bindings.push( binding );
  29641. }
  29642. _removeInactiveBinding( binding ) {
  29643. const bindings = this._bindings,
  29644. propBinding = binding.binding,
  29645. rootUuid = propBinding.rootNode.uuid,
  29646. trackName = propBinding.path,
  29647. bindingsByRoot = this._bindingsByRootAndName,
  29648. bindingByName = bindingsByRoot[ rootUuid ],
  29649. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29650. cacheIndex = binding._cacheIndex;
  29651. lastInactiveBinding._cacheIndex = cacheIndex;
  29652. bindings[ cacheIndex ] = lastInactiveBinding;
  29653. bindings.pop();
  29654. delete bindingByName[ trackName ];
  29655. if ( Object.keys( bindingByName ).length === 0 ) {
  29656. delete bindingsByRoot[ rootUuid ];
  29657. }
  29658. }
  29659. _lendBinding( binding ) {
  29660. const bindings = this._bindings,
  29661. prevIndex = binding._cacheIndex,
  29662. lastActiveIndex = this._nActiveBindings ++,
  29663. firstInactiveBinding = bindings[ lastActiveIndex ];
  29664. binding._cacheIndex = lastActiveIndex;
  29665. bindings[ lastActiveIndex ] = binding;
  29666. firstInactiveBinding._cacheIndex = prevIndex;
  29667. bindings[ prevIndex ] = firstInactiveBinding;
  29668. }
  29669. _takeBackBinding( binding ) {
  29670. const bindings = this._bindings,
  29671. prevIndex = binding._cacheIndex,
  29672. firstInactiveIndex = -- this._nActiveBindings,
  29673. lastActiveBinding = bindings[ firstInactiveIndex ];
  29674. binding._cacheIndex = firstInactiveIndex;
  29675. bindings[ firstInactiveIndex ] = binding;
  29676. lastActiveBinding._cacheIndex = prevIndex;
  29677. bindings[ prevIndex ] = lastActiveBinding;
  29678. }
  29679. // Memory management of Interpolants for weight and time scale
  29680. _lendControlInterpolant() {
  29681. const interpolants = this._controlInterpolants,
  29682. lastActiveIndex = this._nActiveControlInterpolants ++;
  29683. let interpolant = interpolants[ lastActiveIndex ];
  29684. if ( interpolant === undefined ) {
  29685. interpolant = new LinearInterpolant(
  29686. new Float32Array( 2 ), new Float32Array( 2 ),
  29687. 1, _controlInterpolantsResultBuffer );
  29688. interpolant.__cacheIndex = lastActiveIndex;
  29689. interpolants[ lastActiveIndex ] = interpolant;
  29690. }
  29691. return interpolant;
  29692. }
  29693. _takeBackControlInterpolant( interpolant ) {
  29694. const interpolants = this._controlInterpolants,
  29695. prevIndex = interpolant.__cacheIndex,
  29696. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29697. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29698. interpolant.__cacheIndex = firstInactiveIndex;
  29699. interpolants[ firstInactiveIndex ] = interpolant;
  29700. lastActiveInterpolant.__cacheIndex = prevIndex;
  29701. interpolants[ prevIndex ] = lastActiveInterpolant;
  29702. }
  29703. // return an action for a clip optionally using a custom root target
  29704. // object (this method allocates a lot of dynamic memory in case a
  29705. // previously unknown clip/root combination is specified)
  29706. clipAction( clip, optionalRoot, blendMode ) {
  29707. const root = optionalRoot || this._root,
  29708. rootUuid = root.uuid;
  29709. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  29710. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  29711. const actionsForClip = this._actionsByClip[ clipUuid ];
  29712. let prototypeAction = null;
  29713. if ( blendMode === undefined ) {
  29714. if ( clipObject !== null ) {
  29715. blendMode = clipObject.blendMode;
  29716. } else {
  29717. blendMode = NormalAnimationBlendMode;
  29718. }
  29719. }
  29720. if ( actionsForClip !== undefined ) {
  29721. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  29722. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  29723. return existingAction;
  29724. }
  29725. // we know the clip, so we don't have to parse all
  29726. // the bindings again but can just copy
  29727. prototypeAction = actionsForClip.knownActions[ 0 ];
  29728. // also, take the clip from the prototype action
  29729. if ( clipObject === null )
  29730. clipObject = prototypeAction._clip;
  29731. }
  29732. // clip must be known when specified via string
  29733. if ( clipObject === null ) return null;
  29734. // allocate all resources required to run it
  29735. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  29736. this._bindAction( newAction, prototypeAction );
  29737. // and make the action known to the memory manager
  29738. this._addInactiveAction( newAction, clipUuid, rootUuid );
  29739. return newAction;
  29740. }
  29741. // get an existing action
  29742. existingAction( clip, optionalRoot ) {
  29743. const root = optionalRoot || this._root,
  29744. rootUuid = root.uuid,
  29745. clipObject = typeof clip === 'string' ?
  29746. AnimationClip.findByName( root, clip ) : clip,
  29747. clipUuid = clipObject ? clipObject.uuid : clip,
  29748. actionsForClip = this._actionsByClip[ clipUuid ];
  29749. if ( actionsForClip !== undefined ) {
  29750. return actionsForClip.actionByRoot[ rootUuid ] || null;
  29751. }
  29752. return null;
  29753. }
  29754. // deactivates all previously scheduled actions
  29755. stopAllAction() {
  29756. const actions = this._actions,
  29757. nActions = this._nActiveActions;
  29758. for ( let i = nActions - 1; i >= 0; -- i ) {
  29759. actions[ i ].stop();
  29760. }
  29761. return this;
  29762. }
  29763. // advance the time and update apply the animation
  29764. update( deltaTime ) {
  29765. deltaTime *= this.timeScale;
  29766. const actions = this._actions,
  29767. nActions = this._nActiveActions,
  29768. time = this.time += deltaTime,
  29769. timeDirection = Math.sign( deltaTime ),
  29770. accuIndex = this._accuIndex ^= 1;
  29771. // run active actions
  29772. for ( let i = 0; i !== nActions; ++ i ) {
  29773. const action = actions[ i ];
  29774. action._update( time, deltaTime, timeDirection, accuIndex );
  29775. }
  29776. // update scene graph
  29777. const bindings = this._bindings,
  29778. nBindings = this._nActiveBindings;
  29779. for ( let i = 0; i !== nBindings; ++ i ) {
  29780. bindings[ i ].apply( accuIndex );
  29781. }
  29782. return this;
  29783. }
  29784. // Allows you to seek to a specific time in an animation.
  29785. setTime( timeInSeconds ) {
  29786. this.time = 0; // Zero out time attribute for AnimationMixer object;
  29787. for ( let i = 0; i < this._actions.length; i ++ ) {
  29788. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  29789. }
  29790. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  29791. }
  29792. // return this mixer's root target object
  29793. getRoot() {
  29794. return this._root;
  29795. }
  29796. // free all resources specific to a particular clip
  29797. uncacheClip( clip ) {
  29798. const actions = this._actions,
  29799. clipUuid = clip.uuid,
  29800. actionsByClip = this._actionsByClip,
  29801. actionsForClip = actionsByClip[ clipUuid ];
  29802. if ( actionsForClip !== undefined ) {
  29803. // note: just calling _removeInactiveAction would mess up the
  29804. // iteration state and also require updating the state we can
  29805. // just throw away
  29806. const actionsToRemove = actionsForClip.knownActions;
  29807. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  29808. const action = actionsToRemove[ i ];
  29809. this._deactivateAction( action );
  29810. const cacheIndex = action._cacheIndex,
  29811. lastInactiveAction = actions[ actions.length - 1 ];
  29812. action._cacheIndex = null;
  29813. action._byClipCacheIndex = null;
  29814. lastInactiveAction._cacheIndex = cacheIndex;
  29815. actions[ cacheIndex ] = lastInactiveAction;
  29816. actions.pop();
  29817. this._removeInactiveBindingsForAction( action );
  29818. }
  29819. delete actionsByClip[ clipUuid ];
  29820. }
  29821. }
  29822. // free all resources specific to a particular root target object
  29823. uncacheRoot( root ) {
  29824. const rootUuid = root.uuid,
  29825. actionsByClip = this._actionsByClip;
  29826. for ( const clipUuid in actionsByClip ) {
  29827. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  29828. action = actionByRoot[ rootUuid ];
  29829. if ( action !== undefined ) {
  29830. this._deactivateAction( action );
  29831. this._removeInactiveAction( action );
  29832. }
  29833. }
  29834. const bindingsByRoot = this._bindingsByRootAndName,
  29835. bindingByName = bindingsByRoot[ rootUuid ];
  29836. if ( bindingByName !== undefined ) {
  29837. for ( const trackName in bindingByName ) {
  29838. const binding = bindingByName[ trackName ];
  29839. binding.restoreOriginalState();
  29840. this._removeInactiveBinding( binding );
  29841. }
  29842. }
  29843. }
  29844. // remove a targeted clip from the cache
  29845. uncacheAction( clip, optionalRoot ) {
  29846. const action = this.existingAction( clip, optionalRoot );
  29847. if ( action !== null ) {
  29848. this._deactivateAction( action );
  29849. this._removeInactiveAction( action );
  29850. }
  29851. }
  29852. }
  29853. class Uniform {
  29854. constructor( value ) {
  29855. this.value = value;
  29856. }
  29857. clone() {
  29858. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29859. }
  29860. }
  29861. let _id = 0;
  29862. class UniformsGroup extends EventDispatcher {
  29863. constructor() {
  29864. super();
  29865. this.isUniformsGroup = true;
  29866. Object.defineProperty( this, 'id', { value: _id ++ } );
  29867. this.name = '';
  29868. this.usage = StaticDrawUsage;
  29869. this.uniforms = [];
  29870. }
  29871. add( uniform ) {
  29872. this.uniforms.push( uniform );
  29873. return this;
  29874. }
  29875. remove( uniform ) {
  29876. const index = this.uniforms.indexOf( uniform );
  29877. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  29878. return this;
  29879. }
  29880. setName( name ) {
  29881. this.name = name;
  29882. return this;
  29883. }
  29884. setUsage( value ) {
  29885. this.usage = value;
  29886. return this;
  29887. }
  29888. dispose() {
  29889. this.dispatchEvent( { type: 'dispose' } );
  29890. return this;
  29891. }
  29892. copy( source ) {
  29893. this.name = source.name;
  29894. this.usage = source.usage;
  29895. const uniformsSource = source.uniforms;
  29896. this.uniforms.length = 0;
  29897. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  29898. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  29899. for ( let j = 0; j < uniforms.length; j ++ ) {
  29900. this.uniforms.push( uniforms[ j ].clone() );
  29901. }
  29902. }
  29903. return this;
  29904. }
  29905. clone() {
  29906. return new this.constructor().copy( this );
  29907. }
  29908. }
  29909. class InstancedInterleavedBuffer extends InterleavedBuffer {
  29910. constructor( array, stride, meshPerAttribute = 1 ) {
  29911. super( array, stride );
  29912. this.isInstancedInterleavedBuffer = true;
  29913. this.meshPerAttribute = meshPerAttribute;
  29914. }
  29915. copy( source ) {
  29916. super.copy( source );
  29917. this.meshPerAttribute = source.meshPerAttribute;
  29918. return this;
  29919. }
  29920. clone( data ) {
  29921. const ib = super.clone( data );
  29922. ib.meshPerAttribute = this.meshPerAttribute;
  29923. return ib;
  29924. }
  29925. toJSON( data ) {
  29926. const json = super.toJSON( data );
  29927. json.isInstancedInterleavedBuffer = true;
  29928. json.meshPerAttribute = this.meshPerAttribute;
  29929. return json;
  29930. }
  29931. }
  29932. class GLBufferAttribute {
  29933. constructor( buffer, type, itemSize, elementSize, count ) {
  29934. this.isGLBufferAttribute = true;
  29935. this.name = '';
  29936. this.buffer = buffer;
  29937. this.type = type;
  29938. this.itemSize = itemSize;
  29939. this.elementSize = elementSize;
  29940. this.count = count;
  29941. this.version = 0;
  29942. }
  29943. set needsUpdate( value ) {
  29944. if ( value === true ) this.version ++;
  29945. }
  29946. setBuffer( buffer ) {
  29947. this.buffer = buffer;
  29948. return this;
  29949. }
  29950. setType( type, elementSize ) {
  29951. this.type = type;
  29952. this.elementSize = elementSize;
  29953. return this;
  29954. }
  29955. setItemSize( itemSize ) {
  29956. this.itemSize = itemSize;
  29957. return this;
  29958. }
  29959. setCount( count ) {
  29960. this.count = count;
  29961. return this;
  29962. }
  29963. }
  29964. const _matrix = /*@__PURE__*/ new Matrix4();
  29965. class Raycaster {
  29966. constructor( origin, direction, near = 0, far = Infinity ) {
  29967. this.ray = new Ray( origin, direction );
  29968. // direction is assumed to be normalized (for accurate distance calculations)
  29969. this.near = near;
  29970. this.far = far;
  29971. this.camera = null;
  29972. this.layers = new Layers();
  29973. this.params = {
  29974. Mesh: {},
  29975. Line: { threshold: 1 },
  29976. LOD: {},
  29977. Points: { threshold: 1 },
  29978. Sprite: {}
  29979. };
  29980. }
  29981. set( origin, direction ) {
  29982. // direction is assumed to be normalized (for accurate distance calculations)
  29983. this.ray.set( origin, direction );
  29984. }
  29985. setFromCamera( coords, camera ) {
  29986. if ( camera.isPerspectiveCamera ) {
  29987. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  29988. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  29989. this.camera = camera;
  29990. } else if ( camera.isOrthographicCamera ) {
  29991. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  29992. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  29993. this.camera = camera;
  29994. } else {
  29995. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  29996. }
  29997. }
  29998. setFromXRController( controller ) {
  29999. _matrix.identity().extractRotation( controller.matrixWorld );
  30000. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  30001. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  30002. return this;
  30003. }
  30004. intersectObject( object, recursive = true, intersects = [] ) {
  30005. intersect( object, this, intersects, recursive );
  30006. intersects.sort( ascSort );
  30007. return intersects;
  30008. }
  30009. intersectObjects( objects, recursive = true, intersects = [] ) {
  30010. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30011. intersect( objects[ i ], this, intersects, recursive );
  30012. }
  30013. intersects.sort( ascSort );
  30014. return intersects;
  30015. }
  30016. }
  30017. function ascSort( a, b ) {
  30018. return a.distance - b.distance;
  30019. }
  30020. function intersect( object, raycaster, intersects, recursive ) {
  30021. if ( object.layers.test( raycaster.layers ) ) {
  30022. object.raycast( raycaster, intersects );
  30023. }
  30024. if ( recursive === true ) {
  30025. const children = object.children;
  30026. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30027. intersect( children[ i ], raycaster, intersects, true );
  30028. }
  30029. }
  30030. }
  30031. /**
  30032. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30033. *
  30034. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  30035. * theta (the azimuthal angle) is measured from the positive z-axis.
  30036. */
  30037. class Spherical {
  30038. constructor( radius = 1, phi = 0, theta = 0 ) {
  30039. this.radius = radius;
  30040. this.phi = phi; // polar angle
  30041. this.theta = theta; // azimuthal angle
  30042. return this;
  30043. }
  30044. set( radius, phi, theta ) {
  30045. this.radius = radius;
  30046. this.phi = phi;
  30047. this.theta = theta;
  30048. return this;
  30049. }
  30050. copy( other ) {
  30051. this.radius = other.radius;
  30052. this.phi = other.phi;
  30053. this.theta = other.theta;
  30054. return this;
  30055. }
  30056. // restrict phi to be between EPS and PI-EPS
  30057. makeSafe() {
  30058. const EPS = 0.000001;
  30059. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30060. return this;
  30061. }
  30062. setFromVector3( v ) {
  30063. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30064. }
  30065. setFromCartesianCoords( x, y, z ) {
  30066. this.radius = Math.sqrt( x * x + y * y + z * z );
  30067. if ( this.radius === 0 ) {
  30068. this.theta = 0;
  30069. this.phi = 0;
  30070. } else {
  30071. this.theta = Math.atan2( x, z );
  30072. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  30073. }
  30074. return this;
  30075. }
  30076. clone() {
  30077. return new this.constructor().copy( this );
  30078. }
  30079. }
  30080. /**
  30081. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30082. */
  30083. class Cylindrical {
  30084. constructor( radius = 1, theta = 0, y = 0 ) {
  30085. this.radius = radius; // distance from the origin to a point in the x-z plane
  30086. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30087. this.y = y; // height above the x-z plane
  30088. return this;
  30089. }
  30090. set( radius, theta, y ) {
  30091. this.radius = radius;
  30092. this.theta = theta;
  30093. this.y = y;
  30094. return this;
  30095. }
  30096. copy( other ) {
  30097. this.radius = other.radius;
  30098. this.theta = other.theta;
  30099. this.y = other.y;
  30100. return this;
  30101. }
  30102. setFromVector3( v ) {
  30103. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30104. }
  30105. setFromCartesianCoords( x, y, z ) {
  30106. this.radius = Math.sqrt( x * x + z * z );
  30107. this.theta = Math.atan2( x, z );
  30108. this.y = y;
  30109. return this;
  30110. }
  30111. clone() {
  30112. return new this.constructor().copy( this );
  30113. }
  30114. }
  30115. const _vector$4 = /*@__PURE__*/ new Vector2();
  30116. class Box2 {
  30117. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  30118. this.isBox2 = true;
  30119. this.min = min;
  30120. this.max = max;
  30121. }
  30122. set( min, max ) {
  30123. this.min.copy( min );
  30124. this.max.copy( max );
  30125. return this;
  30126. }
  30127. setFromPoints( points ) {
  30128. this.makeEmpty();
  30129. for ( let i = 0, il = points.length; i < il; i ++ ) {
  30130. this.expandByPoint( points[ i ] );
  30131. }
  30132. return this;
  30133. }
  30134. setFromCenterAndSize( center, size ) {
  30135. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  30136. this.min.copy( center ).sub( halfSize );
  30137. this.max.copy( center ).add( halfSize );
  30138. return this;
  30139. }
  30140. clone() {
  30141. return new this.constructor().copy( this );
  30142. }
  30143. copy( box ) {
  30144. this.min.copy( box.min );
  30145. this.max.copy( box.max );
  30146. return this;
  30147. }
  30148. makeEmpty() {
  30149. this.min.x = this.min.y = + Infinity;
  30150. this.max.x = this.max.y = - Infinity;
  30151. return this;
  30152. }
  30153. isEmpty() {
  30154. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30155. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30156. }
  30157. getCenter( target ) {
  30158. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30159. }
  30160. getSize( target ) {
  30161. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30162. }
  30163. expandByPoint( point ) {
  30164. this.min.min( point );
  30165. this.max.max( point );
  30166. return this;
  30167. }
  30168. expandByVector( vector ) {
  30169. this.min.sub( vector );
  30170. this.max.add( vector );
  30171. return this;
  30172. }
  30173. expandByScalar( scalar ) {
  30174. this.min.addScalar( - scalar );
  30175. this.max.addScalar( scalar );
  30176. return this;
  30177. }
  30178. containsPoint( point ) {
  30179. return point.x < this.min.x || point.x > this.max.x ||
  30180. point.y < this.min.y || point.y > this.max.y ? false : true;
  30181. }
  30182. containsBox( box ) {
  30183. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30184. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30185. }
  30186. getParameter( point, target ) {
  30187. // This can potentially have a divide by zero if the box
  30188. // has a size dimension of 0.
  30189. return target.set(
  30190. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30191. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30192. );
  30193. }
  30194. intersectsBox( box ) {
  30195. // using 4 splitting planes to rule out intersections
  30196. return box.max.x < this.min.x || box.min.x > this.max.x ||
  30197. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  30198. }
  30199. clampPoint( point, target ) {
  30200. return target.copy( point ).clamp( this.min, this.max );
  30201. }
  30202. distanceToPoint( point ) {
  30203. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  30204. }
  30205. intersect( box ) {
  30206. this.min.max( box.min );
  30207. this.max.min( box.max );
  30208. if ( this.isEmpty() ) this.makeEmpty();
  30209. return this;
  30210. }
  30211. union( box ) {
  30212. this.min.min( box.min );
  30213. this.max.max( box.max );
  30214. return this;
  30215. }
  30216. translate( offset ) {
  30217. this.min.add( offset );
  30218. this.max.add( offset );
  30219. return this;
  30220. }
  30221. equals( box ) {
  30222. return box.min.equals( this.min ) && box.max.equals( this.max );
  30223. }
  30224. }
  30225. const _startP = /*@__PURE__*/ new Vector3();
  30226. const _startEnd = /*@__PURE__*/ new Vector3();
  30227. class Line3 {
  30228. constructor( start = new Vector3(), end = new Vector3() ) {
  30229. this.start = start;
  30230. this.end = end;
  30231. }
  30232. set( start, end ) {
  30233. this.start.copy( start );
  30234. this.end.copy( end );
  30235. return this;
  30236. }
  30237. copy( line ) {
  30238. this.start.copy( line.start );
  30239. this.end.copy( line.end );
  30240. return this;
  30241. }
  30242. getCenter( target ) {
  30243. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30244. }
  30245. delta( target ) {
  30246. return target.subVectors( this.end, this.start );
  30247. }
  30248. distanceSq() {
  30249. return this.start.distanceToSquared( this.end );
  30250. }
  30251. distance() {
  30252. return this.start.distanceTo( this.end );
  30253. }
  30254. at( t, target ) {
  30255. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30256. }
  30257. closestPointToPointParameter( point, clampToLine ) {
  30258. _startP.subVectors( point, this.start );
  30259. _startEnd.subVectors( this.end, this.start );
  30260. const startEnd2 = _startEnd.dot( _startEnd );
  30261. const startEnd_startP = _startEnd.dot( _startP );
  30262. let t = startEnd_startP / startEnd2;
  30263. if ( clampToLine ) {
  30264. t = clamp( t, 0, 1 );
  30265. }
  30266. return t;
  30267. }
  30268. closestPointToPoint( point, clampToLine, target ) {
  30269. const t = this.closestPointToPointParameter( point, clampToLine );
  30270. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30271. }
  30272. applyMatrix4( matrix ) {
  30273. this.start.applyMatrix4( matrix );
  30274. this.end.applyMatrix4( matrix );
  30275. return this;
  30276. }
  30277. equals( line ) {
  30278. return line.start.equals( this.start ) && line.end.equals( this.end );
  30279. }
  30280. clone() {
  30281. return new this.constructor().copy( this );
  30282. }
  30283. }
  30284. const _vector$3 = /*@__PURE__*/ new Vector3();
  30285. class SpotLightHelper extends Object3D {
  30286. constructor( light, color ) {
  30287. super();
  30288. this.light = light;
  30289. this.matrixAutoUpdate = false;
  30290. this.color = color;
  30291. this.type = 'SpotLightHelper';
  30292. const geometry = new BufferGeometry();
  30293. const positions = [
  30294. 0, 0, 0, 0, 0, 1,
  30295. 0, 0, 0, 1, 0, 1,
  30296. 0, 0, 0, - 1, 0, 1,
  30297. 0, 0, 0, 0, 1, 1,
  30298. 0, 0, 0, 0, - 1, 1
  30299. ];
  30300. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30301. const p1 = ( i / l ) * Math.PI * 2;
  30302. const p2 = ( j / l ) * Math.PI * 2;
  30303. positions.push(
  30304. Math.cos( p1 ), Math.sin( p1 ), 1,
  30305. Math.cos( p2 ), Math.sin( p2 ), 1
  30306. );
  30307. }
  30308. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30309. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30310. this.cone = new LineSegments( geometry, material );
  30311. this.add( this.cone );
  30312. this.update();
  30313. }
  30314. dispose() {
  30315. this.cone.geometry.dispose();
  30316. this.cone.material.dispose();
  30317. }
  30318. update() {
  30319. this.light.updateWorldMatrix( true, false );
  30320. this.light.target.updateWorldMatrix( true, false );
  30321. // update the local matrix based on the parent and light target transforms
  30322. if ( this.parent ) {
  30323. this.parent.updateWorldMatrix( true );
  30324. this.matrix
  30325. .copy( this.parent.matrixWorld )
  30326. .invert()
  30327. .multiply( this.light.matrixWorld );
  30328. } else {
  30329. this.matrix.copy( this.light.matrixWorld );
  30330. }
  30331. this.matrixWorld.copy( this.light.matrixWorld );
  30332. const coneLength = this.light.distance ? this.light.distance : 1000;
  30333. const coneWidth = coneLength * Math.tan( this.light.angle );
  30334. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30335. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  30336. this.cone.lookAt( _vector$3 );
  30337. if ( this.color !== undefined ) {
  30338. this.cone.material.color.set( this.color );
  30339. } else {
  30340. this.cone.material.color.copy( this.light.color );
  30341. }
  30342. }
  30343. }
  30344. const _vector$2 = /*@__PURE__*/ new Vector3();
  30345. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  30346. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  30347. class SkeletonHelper extends LineSegments {
  30348. constructor( object ) {
  30349. const bones = getBoneList( object );
  30350. const geometry = new BufferGeometry();
  30351. const vertices = [];
  30352. const colors = [];
  30353. const color1 = new Color( 0, 0, 1 );
  30354. const color2 = new Color( 0, 1, 0 );
  30355. for ( let i = 0; i < bones.length; i ++ ) {
  30356. const bone = bones[ i ];
  30357. if ( bone.parent && bone.parent.isBone ) {
  30358. vertices.push( 0, 0, 0 );
  30359. vertices.push( 0, 0, 0 );
  30360. colors.push( color1.r, color1.g, color1.b );
  30361. colors.push( color2.r, color2.g, color2.b );
  30362. }
  30363. }
  30364. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30365. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30366. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  30367. super( geometry, material );
  30368. this.isSkeletonHelper = true;
  30369. this.type = 'SkeletonHelper';
  30370. this.root = object;
  30371. this.bones = bones;
  30372. this.matrix = object.matrixWorld;
  30373. this.matrixAutoUpdate = false;
  30374. }
  30375. updateMatrixWorld( force ) {
  30376. const bones = this.bones;
  30377. const geometry = this.geometry;
  30378. const position = geometry.getAttribute( 'position' );
  30379. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  30380. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  30381. const bone = bones[ i ];
  30382. if ( bone.parent && bone.parent.isBone ) {
  30383. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  30384. _vector$2.setFromMatrixPosition( _boneMatrix );
  30385. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  30386. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  30387. _vector$2.setFromMatrixPosition( _boneMatrix );
  30388. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  30389. j += 2;
  30390. }
  30391. }
  30392. geometry.getAttribute( 'position' ).needsUpdate = true;
  30393. super.updateMatrixWorld( force );
  30394. }
  30395. dispose() {
  30396. this.geometry.dispose();
  30397. this.material.dispose();
  30398. }
  30399. }
  30400. function getBoneList( object ) {
  30401. const boneList = [];
  30402. if ( object.isBone === true ) {
  30403. boneList.push( object );
  30404. }
  30405. for ( let i = 0; i < object.children.length; i ++ ) {
  30406. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  30407. }
  30408. return boneList;
  30409. }
  30410. class PointLightHelper extends Mesh {
  30411. constructor( light, sphereSize, color ) {
  30412. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  30413. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30414. super( geometry, material );
  30415. this.light = light;
  30416. this.color = color;
  30417. this.type = 'PointLightHelper';
  30418. this.matrix = this.light.matrixWorld;
  30419. this.matrixAutoUpdate = false;
  30420. this.update();
  30421. /*
  30422. // TODO: delete this comment?
  30423. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  30424. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30425. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30426. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30427. const d = light.distance;
  30428. if ( d === 0.0 ) {
  30429. this.lightDistance.visible = false;
  30430. } else {
  30431. this.lightDistance.scale.set( d, d, d );
  30432. }
  30433. this.add( this.lightDistance );
  30434. */
  30435. }
  30436. dispose() {
  30437. this.geometry.dispose();
  30438. this.material.dispose();
  30439. }
  30440. update() {
  30441. this.light.updateWorldMatrix( true, false );
  30442. if ( this.color !== undefined ) {
  30443. this.material.color.set( this.color );
  30444. } else {
  30445. this.material.color.copy( this.light.color );
  30446. }
  30447. /*
  30448. const d = this.light.distance;
  30449. if ( d === 0.0 ) {
  30450. this.lightDistance.visible = false;
  30451. } else {
  30452. this.lightDistance.visible = true;
  30453. this.lightDistance.scale.set( d, d, d );
  30454. }
  30455. */
  30456. }
  30457. }
  30458. const _vector$1 = /*@__PURE__*/ new Vector3();
  30459. const _color1 = /*@__PURE__*/ new Color();
  30460. const _color2 = /*@__PURE__*/ new Color();
  30461. class HemisphereLightHelper extends Object3D {
  30462. constructor( light, size, color ) {
  30463. super();
  30464. this.light = light;
  30465. this.matrix = light.matrixWorld;
  30466. this.matrixAutoUpdate = false;
  30467. this.color = color;
  30468. this.type = 'HemisphereLightHelper';
  30469. const geometry = new OctahedronGeometry( size );
  30470. geometry.rotateY( Math.PI * 0.5 );
  30471. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30472. if ( this.color === undefined ) this.material.vertexColors = true;
  30473. const position = geometry.getAttribute( 'position' );
  30474. const colors = new Float32Array( position.count * 3 );
  30475. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30476. this.add( new Mesh( geometry, this.material ) );
  30477. this.update();
  30478. }
  30479. dispose() {
  30480. this.children[ 0 ].geometry.dispose();
  30481. this.children[ 0 ].material.dispose();
  30482. }
  30483. update() {
  30484. const mesh = this.children[ 0 ];
  30485. if ( this.color !== undefined ) {
  30486. this.material.color.set( this.color );
  30487. } else {
  30488. const colors = mesh.geometry.getAttribute( 'color' );
  30489. _color1.copy( this.light.color );
  30490. _color2.copy( this.light.groundColor );
  30491. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  30492. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  30493. colors.setXYZ( i, color.r, color.g, color.b );
  30494. }
  30495. colors.needsUpdate = true;
  30496. }
  30497. this.light.updateWorldMatrix( true, false );
  30498. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30499. }
  30500. }
  30501. class GridHelper extends LineSegments {
  30502. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  30503. color1 = new Color( color1 );
  30504. color2 = new Color( color2 );
  30505. const center = divisions / 2;
  30506. const step = size / divisions;
  30507. const halfSize = size / 2;
  30508. const vertices = [], colors = [];
  30509. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30510. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30511. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30512. const color = i === center ? color1 : color2;
  30513. color.toArray( colors, j ); j += 3;
  30514. color.toArray( colors, j ); j += 3;
  30515. color.toArray( colors, j ); j += 3;
  30516. color.toArray( colors, j ); j += 3;
  30517. }
  30518. const geometry = new BufferGeometry();
  30519. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30520. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30521. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30522. super( geometry, material );
  30523. this.type = 'GridHelper';
  30524. }
  30525. dispose() {
  30526. this.geometry.dispose();
  30527. this.material.dispose();
  30528. }
  30529. }
  30530. class PolarGridHelper extends LineSegments {
  30531. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  30532. color1 = new Color( color1 );
  30533. color2 = new Color( color2 );
  30534. const vertices = [];
  30535. const colors = [];
  30536. // create the sectors
  30537. if ( sectors > 1 ) {
  30538. for ( let i = 0; i < sectors; i ++ ) {
  30539. const v = ( i / sectors ) * ( Math.PI * 2 );
  30540. const x = Math.sin( v ) * radius;
  30541. const z = Math.cos( v ) * radius;
  30542. vertices.push( 0, 0, 0 );
  30543. vertices.push( x, 0, z );
  30544. const color = ( i & 1 ) ? color1 : color2;
  30545. colors.push( color.r, color.g, color.b );
  30546. colors.push( color.r, color.g, color.b );
  30547. }
  30548. }
  30549. // create the rings
  30550. for ( let i = 0; i < rings; i ++ ) {
  30551. const color = ( i & 1 ) ? color1 : color2;
  30552. const r = radius - ( radius / rings * i );
  30553. for ( let j = 0; j < divisions; j ++ ) {
  30554. // first vertex
  30555. let v = ( j / divisions ) * ( Math.PI * 2 );
  30556. let x = Math.sin( v ) * r;
  30557. let z = Math.cos( v ) * r;
  30558. vertices.push( x, 0, z );
  30559. colors.push( color.r, color.g, color.b );
  30560. // second vertex
  30561. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30562. x = Math.sin( v ) * r;
  30563. z = Math.cos( v ) * r;
  30564. vertices.push( x, 0, z );
  30565. colors.push( color.r, color.g, color.b );
  30566. }
  30567. }
  30568. const geometry = new BufferGeometry();
  30569. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30570. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30571. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30572. super( geometry, material );
  30573. this.type = 'PolarGridHelper';
  30574. }
  30575. dispose() {
  30576. this.geometry.dispose();
  30577. this.material.dispose();
  30578. }
  30579. }
  30580. const _v1 = /*@__PURE__*/ new Vector3();
  30581. const _v2 = /*@__PURE__*/ new Vector3();
  30582. const _v3 = /*@__PURE__*/ new Vector3();
  30583. class DirectionalLightHelper extends Object3D {
  30584. constructor( light, size, color ) {
  30585. super();
  30586. this.light = light;
  30587. this.matrix = light.matrixWorld;
  30588. this.matrixAutoUpdate = false;
  30589. this.color = color;
  30590. this.type = 'DirectionalLightHelper';
  30591. if ( size === undefined ) size = 1;
  30592. let geometry = new BufferGeometry();
  30593. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  30594. - size, size, 0,
  30595. size, size, 0,
  30596. size, - size, 0,
  30597. - size, - size, 0,
  30598. - size, size, 0
  30599. ], 3 ) );
  30600. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30601. this.lightPlane = new Line( geometry, material );
  30602. this.add( this.lightPlane );
  30603. geometry = new BufferGeometry();
  30604. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30605. this.targetLine = new Line( geometry, material );
  30606. this.add( this.targetLine );
  30607. this.update();
  30608. }
  30609. dispose() {
  30610. this.lightPlane.geometry.dispose();
  30611. this.lightPlane.material.dispose();
  30612. this.targetLine.geometry.dispose();
  30613. this.targetLine.material.dispose();
  30614. }
  30615. update() {
  30616. this.light.updateWorldMatrix( true, false );
  30617. this.light.target.updateWorldMatrix( true, false );
  30618. _v1.setFromMatrixPosition( this.light.matrixWorld );
  30619. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30620. _v3.subVectors( _v2, _v1 );
  30621. this.lightPlane.lookAt( _v2 );
  30622. if ( this.color !== undefined ) {
  30623. this.lightPlane.material.color.set( this.color );
  30624. this.targetLine.material.color.set( this.color );
  30625. } else {
  30626. this.lightPlane.material.color.copy( this.light.color );
  30627. this.targetLine.material.color.copy( this.light.color );
  30628. }
  30629. this.targetLine.lookAt( _v2 );
  30630. this.targetLine.scale.z = _v3.length();
  30631. }
  30632. }
  30633. const _vector = /*@__PURE__*/ new Vector3();
  30634. const _camera = /*@__PURE__*/ new Camera();
  30635. /**
  30636. * - shows frustum, line of sight and up of the camera
  30637. * - suitable for fast updates
  30638. * - based on frustum visualization in lightgl.js shadowmap example
  30639. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  30640. */
  30641. class CameraHelper extends LineSegments {
  30642. constructor( camera ) {
  30643. const geometry = new BufferGeometry();
  30644. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  30645. const vertices = [];
  30646. const colors = [];
  30647. const pointMap = {};
  30648. // near
  30649. addLine( 'n1', 'n2' );
  30650. addLine( 'n2', 'n4' );
  30651. addLine( 'n4', 'n3' );
  30652. addLine( 'n3', 'n1' );
  30653. // far
  30654. addLine( 'f1', 'f2' );
  30655. addLine( 'f2', 'f4' );
  30656. addLine( 'f4', 'f3' );
  30657. addLine( 'f3', 'f1' );
  30658. // sides
  30659. addLine( 'n1', 'f1' );
  30660. addLine( 'n2', 'f2' );
  30661. addLine( 'n3', 'f3' );
  30662. addLine( 'n4', 'f4' );
  30663. // cone
  30664. addLine( 'p', 'n1' );
  30665. addLine( 'p', 'n2' );
  30666. addLine( 'p', 'n3' );
  30667. addLine( 'p', 'n4' );
  30668. // up
  30669. addLine( 'u1', 'u2' );
  30670. addLine( 'u2', 'u3' );
  30671. addLine( 'u3', 'u1' );
  30672. // target
  30673. addLine( 'c', 't' );
  30674. addLine( 'p', 'c' );
  30675. // cross
  30676. addLine( 'cn1', 'cn2' );
  30677. addLine( 'cn3', 'cn4' );
  30678. addLine( 'cf1', 'cf2' );
  30679. addLine( 'cf3', 'cf4' );
  30680. function addLine( a, b ) {
  30681. addPoint( a );
  30682. addPoint( b );
  30683. }
  30684. function addPoint( id ) {
  30685. vertices.push( 0, 0, 0 );
  30686. colors.push( 0, 0, 0 );
  30687. if ( pointMap[ id ] === undefined ) {
  30688. pointMap[ id ] = [];
  30689. }
  30690. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30691. }
  30692. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30693. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30694. super( geometry, material );
  30695. this.type = 'CameraHelper';
  30696. this.camera = camera;
  30697. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30698. this.matrix = camera.matrixWorld;
  30699. this.matrixAutoUpdate = false;
  30700. this.pointMap = pointMap;
  30701. this.update();
  30702. // colors
  30703. const colorFrustum = new Color( 0xffaa00 );
  30704. const colorCone = new Color( 0xff0000 );
  30705. const colorUp = new Color( 0x00aaff );
  30706. const colorTarget = new Color( 0xffffff );
  30707. const colorCross = new Color( 0x333333 );
  30708. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  30709. }
  30710. setColors( frustum, cone, up, target, cross ) {
  30711. const geometry = this.geometry;
  30712. const colorAttribute = geometry.getAttribute( 'color' );
  30713. // near
  30714. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  30715. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  30716. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  30717. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  30718. // far
  30719. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  30720. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  30721. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  30722. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  30723. // sides
  30724. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  30725. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  30726. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  30727. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  30728. // cone
  30729. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  30730. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  30731. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  30732. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  30733. // up
  30734. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  30735. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  30736. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  30737. // target
  30738. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  30739. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  30740. // cross
  30741. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  30742. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  30743. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  30744. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  30745. colorAttribute.needsUpdate = true;
  30746. }
  30747. update() {
  30748. const geometry = this.geometry;
  30749. const pointMap = this.pointMap;
  30750. const w = 1, h = 1;
  30751. // we need just camera projection matrix inverse
  30752. // world matrix must be identity
  30753. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  30754. // center / target
  30755. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  30756. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  30757. // near
  30758. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  30759. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  30760. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  30761. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  30762. // far
  30763. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  30764. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  30765. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  30766. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  30767. // up
  30768. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  30769. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  30770. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  30771. // cross
  30772. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  30773. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  30774. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  30775. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  30776. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  30777. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  30778. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  30779. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  30780. geometry.getAttribute( 'position' ).needsUpdate = true;
  30781. }
  30782. dispose() {
  30783. this.geometry.dispose();
  30784. this.material.dispose();
  30785. }
  30786. }
  30787. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  30788. _vector.set( x, y, z ).unproject( camera );
  30789. const points = pointMap[ point ];
  30790. if ( points !== undefined ) {
  30791. const position = geometry.getAttribute( 'position' );
  30792. for ( let i = 0, l = points.length; i < l; i ++ ) {
  30793. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  30794. }
  30795. }
  30796. }
  30797. const _box = /*@__PURE__*/ new Box3();
  30798. class BoxHelper extends LineSegments {
  30799. constructor( object, color = 0xffff00 ) {
  30800. 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 ] );
  30801. const positions = new Float32Array( 8 * 3 );
  30802. const geometry = new BufferGeometry();
  30803. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30804. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  30805. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30806. this.object = object;
  30807. this.type = 'BoxHelper';
  30808. this.matrixAutoUpdate = false;
  30809. this.update();
  30810. }
  30811. update( object ) {
  30812. if ( object !== undefined ) {
  30813. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  30814. }
  30815. if ( this.object !== undefined ) {
  30816. _box.setFromObject( this.object );
  30817. }
  30818. if ( _box.isEmpty() ) return;
  30819. const min = _box.min;
  30820. const max = _box.max;
  30821. /*
  30822. 5____4
  30823. 1/___0/|
  30824. | 6__|_7
  30825. 2/___3/
  30826. 0: max.x, max.y, max.z
  30827. 1: min.x, max.y, max.z
  30828. 2: min.x, min.y, max.z
  30829. 3: max.x, min.y, max.z
  30830. 4: max.x, max.y, min.z
  30831. 5: min.x, max.y, min.z
  30832. 6: min.x, min.y, min.z
  30833. 7: max.x, min.y, min.z
  30834. */
  30835. const position = this.geometry.attributes.position;
  30836. const array = position.array;
  30837. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  30838. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  30839. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  30840. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  30841. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  30842. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  30843. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  30844. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  30845. position.needsUpdate = true;
  30846. this.geometry.computeBoundingSphere();
  30847. }
  30848. setFromObject( object ) {
  30849. this.object = object;
  30850. this.update();
  30851. return this;
  30852. }
  30853. copy( source, recursive ) {
  30854. super.copy( source, recursive );
  30855. this.object = source.object;
  30856. return this;
  30857. }
  30858. dispose() {
  30859. this.geometry.dispose();
  30860. this.material.dispose();
  30861. }
  30862. }
  30863. class Box3Helper extends LineSegments {
  30864. constructor( box, color = 0xffff00 ) {
  30865. 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 ] );
  30866. 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 ];
  30867. const geometry = new BufferGeometry();
  30868. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30869. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30870. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30871. this.box = box;
  30872. this.type = 'Box3Helper';
  30873. this.geometry.computeBoundingSphere();
  30874. }
  30875. updateMatrixWorld( force ) {
  30876. const box = this.box;
  30877. if ( box.isEmpty() ) return;
  30878. box.getCenter( this.position );
  30879. box.getSize( this.scale );
  30880. this.scale.multiplyScalar( 0.5 );
  30881. super.updateMatrixWorld( force );
  30882. }
  30883. dispose() {
  30884. this.geometry.dispose();
  30885. this.material.dispose();
  30886. }
  30887. }
  30888. class PlaneHelper extends Line {
  30889. constructor( plane, size = 1, hex = 0xffff00 ) {
  30890. const color = hex;
  30891. 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 ];
  30892. const geometry = new BufferGeometry();
  30893. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30894. geometry.computeBoundingSphere();
  30895. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30896. this.type = 'PlaneHelper';
  30897. this.plane = plane;
  30898. this.size = size;
  30899. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  30900. const geometry2 = new BufferGeometry();
  30901. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  30902. geometry2.computeBoundingSphere();
  30903. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  30904. }
  30905. updateMatrixWorld( force ) {
  30906. this.position.set( 0, 0, 0 );
  30907. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  30908. this.lookAt( this.plane.normal );
  30909. this.translateZ( - this.plane.constant );
  30910. super.updateMatrixWorld( force );
  30911. }
  30912. dispose() {
  30913. this.geometry.dispose();
  30914. this.material.dispose();
  30915. this.children[ 0 ].geometry.dispose();
  30916. this.children[ 0 ].material.dispose();
  30917. }
  30918. }
  30919. const _axis = /*@__PURE__*/ new Vector3();
  30920. let _lineGeometry, _coneGeometry;
  30921. class ArrowHelper extends Object3D {
  30922. // dir is assumed to be normalized
  30923. 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 ) {
  30924. super();
  30925. this.type = 'ArrowHelper';
  30926. if ( _lineGeometry === undefined ) {
  30927. _lineGeometry = new BufferGeometry();
  30928. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  30929. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  30930. _coneGeometry.translate( 0, - 0.5, 0 );
  30931. }
  30932. this.position.copy( origin );
  30933. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30934. this.line.matrixAutoUpdate = false;
  30935. this.add( this.line );
  30936. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  30937. this.cone.matrixAutoUpdate = false;
  30938. this.add( this.cone );
  30939. this.setDirection( dir );
  30940. this.setLength( length, headLength, headWidth );
  30941. }
  30942. setDirection( dir ) {
  30943. // dir is assumed to be normalized
  30944. if ( dir.y > 0.99999 ) {
  30945. this.quaternion.set( 0, 0, 0, 1 );
  30946. } else if ( dir.y < - 0.99999 ) {
  30947. this.quaternion.set( 1, 0, 0, 0 );
  30948. } else {
  30949. _axis.set( dir.z, 0, - dir.x ).normalize();
  30950. const radians = Math.acos( dir.y );
  30951. this.quaternion.setFromAxisAngle( _axis, radians );
  30952. }
  30953. }
  30954. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  30955. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  30956. this.line.updateMatrix();
  30957. this.cone.scale.set( headWidth, headLength, headWidth );
  30958. this.cone.position.y = length;
  30959. this.cone.updateMatrix();
  30960. }
  30961. setColor( color ) {
  30962. this.line.material.color.set( color );
  30963. this.cone.material.color.set( color );
  30964. }
  30965. copy( source ) {
  30966. super.copy( source, false );
  30967. this.line.copy( source.line );
  30968. this.cone.copy( source.cone );
  30969. return this;
  30970. }
  30971. dispose() {
  30972. this.line.geometry.dispose();
  30973. this.line.material.dispose();
  30974. this.cone.geometry.dispose();
  30975. this.cone.material.dispose();
  30976. }
  30977. }
  30978. class AxesHelper extends LineSegments {
  30979. constructor( size = 1 ) {
  30980. const vertices = [
  30981. 0, 0, 0, size, 0, 0,
  30982. 0, 0, 0, 0, size, 0,
  30983. 0, 0, 0, 0, 0, size
  30984. ];
  30985. const colors = [
  30986. 1, 0, 0, 1, 0.6, 0,
  30987. 0, 1, 0, 0.6, 1, 0,
  30988. 0, 0, 1, 0, 0.6, 1
  30989. ];
  30990. const geometry = new BufferGeometry();
  30991. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30992. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30993. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30994. super( geometry, material );
  30995. this.type = 'AxesHelper';
  30996. }
  30997. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  30998. const color = new Color();
  30999. const array = this.geometry.attributes.color.array;
  31000. color.set( xAxisColor );
  31001. color.toArray( array, 0 );
  31002. color.toArray( array, 3 );
  31003. color.set( yAxisColor );
  31004. color.toArray( array, 6 );
  31005. color.toArray( array, 9 );
  31006. color.set( zAxisColor );
  31007. color.toArray( array, 12 );
  31008. color.toArray( array, 15 );
  31009. this.geometry.attributes.color.needsUpdate = true;
  31010. return this;
  31011. }
  31012. dispose() {
  31013. this.geometry.dispose();
  31014. this.material.dispose();
  31015. }
  31016. }
  31017. class ShapePath {
  31018. constructor() {
  31019. this.type = 'ShapePath';
  31020. this.color = new Color();
  31021. this.subPaths = [];
  31022. this.currentPath = null;
  31023. }
  31024. moveTo( x, y ) {
  31025. this.currentPath = new Path();
  31026. this.subPaths.push( this.currentPath );
  31027. this.currentPath.moveTo( x, y );
  31028. return this;
  31029. }
  31030. lineTo( x, y ) {
  31031. this.currentPath.lineTo( x, y );
  31032. return this;
  31033. }
  31034. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  31035. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  31036. return this;
  31037. }
  31038. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  31039. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  31040. return this;
  31041. }
  31042. splineThru( pts ) {
  31043. this.currentPath.splineThru( pts );
  31044. return this;
  31045. }
  31046. toShapes( isCCW ) {
  31047. function toShapesNoHoles( inSubpaths ) {
  31048. const shapes = [];
  31049. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  31050. const tmpPath = inSubpaths[ i ];
  31051. const tmpShape = new Shape();
  31052. tmpShape.curves = tmpPath.curves;
  31053. shapes.push( tmpShape );
  31054. }
  31055. return shapes;
  31056. }
  31057. function isPointInsidePolygon( inPt, inPolygon ) {
  31058. const polyLen = inPolygon.length;
  31059. // inPt on polygon contour => immediate success or
  31060. // toggling of inside/outside at every single! intersection point of an edge
  31061. // with the horizontal line through inPt, left of inPt
  31062. // not counting lowerY endpoints of edges and whole edges on that line
  31063. let inside = false;
  31064. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  31065. let edgeLowPt = inPolygon[ p ];
  31066. let edgeHighPt = inPolygon[ q ];
  31067. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  31068. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  31069. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  31070. // not parallel
  31071. if ( edgeDy < 0 ) {
  31072. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  31073. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  31074. }
  31075. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  31076. if ( inPt.y === edgeLowPt.y ) {
  31077. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  31078. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31079. } else {
  31080. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  31081. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  31082. if ( perpEdge < 0 ) continue;
  31083. inside = ! inside; // true intersection left of inPt
  31084. }
  31085. } else {
  31086. // parallel or collinear
  31087. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  31088. // edge lies on the same horizontal line as inPt
  31089. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  31090. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  31091. // continue;
  31092. }
  31093. }
  31094. return inside;
  31095. }
  31096. const isClockWise = ShapeUtils.isClockWise;
  31097. const subPaths = this.subPaths;
  31098. if ( subPaths.length === 0 ) return [];
  31099. let solid, tmpPath, tmpShape;
  31100. const shapes = [];
  31101. if ( subPaths.length === 1 ) {
  31102. tmpPath = subPaths[ 0 ];
  31103. tmpShape = new Shape();
  31104. tmpShape.curves = tmpPath.curves;
  31105. shapes.push( tmpShape );
  31106. return shapes;
  31107. }
  31108. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  31109. holesFirst = isCCW ? ! holesFirst : holesFirst;
  31110. // console.log("Holes first", holesFirst);
  31111. const betterShapeHoles = [];
  31112. const newShapes = [];
  31113. let newShapeHoles = [];
  31114. let mainIdx = 0;
  31115. let tmpPoints;
  31116. newShapes[ mainIdx ] = undefined;
  31117. newShapeHoles[ mainIdx ] = [];
  31118. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  31119. tmpPath = subPaths[ i ];
  31120. tmpPoints = tmpPath.getPoints();
  31121. solid = isClockWise( tmpPoints );
  31122. solid = isCCW ? ! solid : solid;
  31123. if ( solid ) {
  31124. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  31125. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  31126. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  31127. if ( holesFirst ) mainIdx ++;
  31128. newShapeHoles[ mainIdx ] = [];
  31129. //console.log('cw', i);
  31130. } else {
  31131. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  31132. //console.log('ccw', i);
  31133. }
  31134. }
  31135. // only Holes? -> probably all Shapes with wrong orientation
  31136. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  31137. if ( newShapes.length > 1 ) {
  31138. let ambiguous = false;
  31139. let toChange = 0;
  31140. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31141. betterShapeHoles[ sIdx ] = [];
  31142. }
  31143. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31144. const sho = newShapeHoles[ sIdx ];
  31145. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  31146. const ho = sho[ hIdx ];
  31147. let hole_unassigned = true;
  31148. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  31149. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  31150. if ( sIdx !== s2Idx ) toChange ++;
  31151. if ( hole_unassigned ) {
  31152. hole_unassigned = false;
  31153. betterShapeHoles[ s2Idx ].push( ho );
  31154. } else {
  31155. ambiguous = true;
  31156. }
  31157. }
  31158. }
  31159. if ( hole_unassigned ) {
  31160. betterShapeHoles[ sIdx ].push( ho );
  31161. }
  31162. }
  31163. }
  31164. if ( toChange > 0 && ambiguous === false ) {
  31165. newShapeHoles = betterShapeHoles;
  31166. }
  31167. }
  31168. let tmpHoles;
  31169. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  31170. tmpShape = newShapes[ i ].s;
  31171. shapes.push( tmpShape );
  31172. tmpHoles = newShapeHoles[ i ];
  31173. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  31174. tmpShape.holes.push( tmpHoles[ j ].h );
  31175. }
  31176. }
  31177. //console.log("shape", shapes);
  31178. return shapes;
  31179. }
  31180. }
  31181. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  31182. constructor( width = 1, height = 1, count = 1, options = {} ) {
  31183. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  31184. super( width, height, { ...options, count } );
  31185. this.isWebGLMultipleRenderTargets = true;
  31186. }
  31187. get texture() {
  31188. return this.textures;
  31189. }
  31190. }
  31191. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31192. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31193. revision: REVISION,
  31194. } } ) );
  31195. }
  31196. if ( typeof window !== 'undefined' ) {
  31197. if ( window.__THREE__ ) {
  31198. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  31199. } else {
  31200. window.__THREE__ = REVISION;
  31201. }
  31202. }
  31203. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, createCanvasElement };