three.module.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '157dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const TwoPassDoubleSide = 2; // r149
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const NeverDepth = 0;
  44. const AlwaysDepth = 1;
  45. const LessDepth = 2;
  46. const LessEqualDepth = 3;
  47. const EqualDepth = 4;
  48. const GreaterEqualDepth = 5;
  49. const GreaterDepth = 6;
  50. const NotEqualDepth = 7;
  51. const MultiplyOperation = 0;
  52. const MixOperation = 1;
  53. const AddOperation = 2;
  54. const NoToneMapping = 0;
  55. const LinearToneMapping = 1;
  56. const ReinhardToneMapping = 2;
  57. const CineonToneMapping = 3;
  58. const ACESFilmicToneMapping = 4;
  59. const CustomToneMapping = 5;
  60. const UVMapping = 300;
  61. const CubeReflectionMapping = 301;
  62. const CubeRefractionMapping = 302;
  63. const EquirectangularReflectionMapping = 303;
  64. const EquirectangularRefractionMapping = 304;
  65. const CubeUVReflectionMapping = 306;
  66. const RepeatWrapping = 1000;
  67. const ClampToEdgeWrapping = 1001;
  68. const MirroredRepeatWrapping = 1002;
  69. const NearestFilter = 1003;
  70. const NearestMipmapNearestFilter = 1004;
  71. const NearestMipMapNearestFilter = 1004;
  72. const NearestMipmapLinearFilter = 1005;
  73. const NearestMipMapLinearFilter = 1005;
  74. const LinearFilter = 1006;
  75. const LinearMipmapNearestFilter = 1007;
  76. const LinearMipMapNearestFilter = 1007;
  77. const LinearMipmapLinearFilter = 1008;
  78. const LinearMipMapLinearFilter = 1008;
  79. const UnsignedByteType = 1009;
  80. const ByteType = 1010;
  81. const ShortType = 1011;
  82. const UnsignedShortType = 1012;
  83. const IntType = 1013;
  84. const UnsignedIntType = 1014;
  85. const FloatType = 1015;
  86. const HalfFloatType = 1016;
  87. const UnsignedShort4444Type = 1017;
  88. const UnsignedShort5551Type = 1018;
  89. const UnsignedInt248Type = 1020;
  90. const AlphaFormat = 1021;
  91. const RGBAFormat = 1023;
  92. const LuminanceFormat = 1024;
  93. const LuminanceAlphaFormat = 1025;
  94. const DepthFormat = 1026;
  95. const DepthStencilFormat = 1027;
  96. const RedFormat = 1028;
  97. const RedIntegerFormat = 1029;
  98. const RGFormat = 1030;
  99. const RGIntegerFormat = 1031;
  100. const RGBAIntegerFormat = 1033;
  101. const RGB_S3TC_DXT1_Format = 33776;
  102. const RGBA_S3TC_DXT1_Format = 33777;
  103. const RGBA_S3TC_DXT3_Format = 33778;
  104. const RGBA_S3TC_DXT5_Format = 33779;
  105. const RGB_PVRTC_4BPPV1_Format = 35840;
  106. const RGB_PVRTC_2BPPV1_Format = 35841;
  107. const RGBA_PVRTC_4BPPV1_Format = 35842;
  108. const RGBA_PVRTC_2BPPV1_Format = 35843;
  109. const RGB_ETC1_Format = 36196;
  110. const RGB_ETC2_Format = 37492;
  111. const RGBA_ETC2_EAC_Format = 37496;
  112. const RGBA_ASTC_4x4_Format = 37808;
  113. const RGBA_ASTC_5x4_Format = 37809;
  114. const RGBA_ASTC_5x5_Format = 37810;
  115. const RGBA_ASTC_6x5_Format = 37811;
  116. const RGBA_ASTC_6x6_Format = 37812;
  117. const RGBA_ASTC_8x5_Format = 37813;
  118. const RGBA_ASTC_8x6_Format = 37814;
  119. const RGBA_ASTC_8x8_Format = 37815;
  120. const RGBA_ASTC_10x5_Format = 37816;
  121. const RGBA_ASTC_10x6_Format = 37817;
  122. const RGBA_ASTC_10x8_Format = 37818;
  123. const RGBA_ASTC_10x10_Format = 37819;
  124. const RGBA_ASTC_12x10_Format = 37820;
  125. const RGBA_ASTC_12x12_Format = 37821;
  126. const RGBA_BPTC_Format = 36492;
  127. const RGB_BPTC_SIGNED_Format = 36494;
  128. const RGB_BPTC_UNSIGNED_Format = 36495;
  129. const RED_RGTC1_Format = 36283;
  130. const SIGNED_RED_RGTC1_Format = 36284;
  131. const RED_GREEN_RGTC2_Format = 36285;
  132. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  133. const LoopOnce = 2200;
  134. const LoopRepeat = 2201;
  135. const LoopPingPong = 2202;
  136. const InterpolateDiscrete = 2300;
  137. const InterpolateLinear = 2301;
  138. const InterpolateSmooth = 2302;
  139. const ZeroCurvatureEnding = 2400;
  140. const ZeroSlopeEnding = 2401;
  141. const WrapAroundEnding = 2402;
  142. const NormalAnimationBlendMode = 2500;
  143. const AdditiveAnimationBlendMode = 2501;
  144. const TrianglesDrawMode = 0;
  145. const TriangleStripDrawMode = 1;
  146. const TriangleFanDrawMode = 2;
  147. /** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */
  148. const LinearEncoding = 3000;
  149. /** @deprecated Use SRGBColorSpace in three.js r152+. */
  150. const sRGBEncoding = 3001;
  151. const BasicDepthPacking = 3200;
  152. const RGBADepthPacking = 3201;
  153. const TangentSpaceNormalMap = 0;
  154. const ObjectSpaceNormalMap = 1;
  155. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  156. const NoColorSpace = '';
  157. const SRGBColorSpace = 'srgb';
  158. const LinearSRGBColorSpace = 'srgb-linear';
  159. const DisplayP3ColorSpace = 'display-p3';
  160. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  161. const LinearTransfer = 'linear';
  162. const SRGBTransfer = 'srgb';
  163. const Rec709Primaries = 'rec709';
  164. const P3Primaries = 'p3';
  165. const ZeroStencilOp = 0;
  166. const KeepStencilOp = 7680;
  167. const ReplaceStencilOp = 7681;
  168. const IncrementStencilOp = 7682;
  169. const DecrementStencilOp = 7683;
  170. const IncrementWrapStencilOp = 34055;
  171. const DecrementWrapStencilOp = 34056;
  172. const InvertStencilOp = 5386;
  173. const NeverStencilFunc = 512;
  174. const LessStencilFunc = 513;
  175. const EqualStencilFunc = 514;
  176. const LessEqualStencilFunc = 515;
  177. const GreaterStencilFunc = 516;
  178. const NotEqualStencilFunc = 517;
  179. const GreaterEqualStencilFunc = 518;
  180. const AlwaysStencilFunc = 519;
  181. const NeverCompare = 512;
  182. const LessCompare = 513;
  183. const EqualCompare = 514;
  184. const LessEqualCompare = 515;
  185. const GreaterCompare = 516;
  186. const NotEqualCompare = 517;
  187. const GreaterEqualCompare = 518;
  188. const AlwaysCompare = 519;
  189. const StaticDrawUsage = 35044;
  190. const DynamicDrawUsage = 35048;
  191. const StreamDrawUsage = 35040;
  192. const StaticReadUsage = 35045;
  193. const DynamicReadUsage = 35049;
  194. const StreamReadUsage = 35041;
  195. const StaticCopyUsage = 35046;
  196. const DynamicCopyUsage = 35050;
  197. const StreamCopyUsage = 35042;
  198. const GLSL1 = '100';
  199. const GLSL3 = '300 es';
  200. const _SRGBAFormat = 1035; // fallback for WebGL 1
  201. const WebGLCoordinateSystem = 2000;
  202. const WebGPUCoordinateSystem = 2001;
  203. /**
  204. * https://github.com/mrdoob/eventdispatcher.js/
  205. */
  206. class EventDispatcher {
  207. addEventListener( type, listener ) {
  208. if ( this._listeners === undefined ) this._listeners = {};
  209. const listeners = this._listeners;
  210. if ( listeners[ type ] === undefined ) {
  211. listeners[ type ] = [];
  212. }
  213. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  214. listeners[ type ].push( listener );
  215. }
  216. }
  217. hasEventListener( type, listener ) {
  218. if ( this._listeners === undefined ) return false;
  219. const listeners = this._listeners;
  220. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  221. }
  222. removeEventListener( type, listener ) {
  223. if ( this._listeners === undefined ) return;
  224. const listeners = this._listeners;
  225. const listenerArray = listeners[ type ];
  226. if ( listenerArray !== undefined ) {
  227. const index = listenerArray.indexOf( listener );
  228. if ( index !== - 1 ) {
  229. listenerArray.splice( index, 1 );
  230. }
  231. }
  232. }
  233. dispatchEvent( event ) {
  234. if ( this._listeners === undefined ) return;
  235. const listeners = this._listeners;
  236. const listenerArray = listeners[ event.type ];
  237. if ( listenerArray !== undefined ) {
  238. event.target = this;
  239. // Make a copy, in case listeners are removed while iterating.
  240. const array = listenerArray.slice( 0 );
  241. for ( let i = 0, l = array.length; i < l; i ++ ) {
  242. array[ i ].call( this, event );
  243. }
  244. event.target = null;
  245. }
  246. }
  247. }
  248. 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' ];
  249. let _seed = 1234567;
  250. const DEG2RAD = Math.PI / 180;
  251. const RAD2DEG = 180 / Math.PI;
  252. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  253. function generateUUID() {
  254. const d0 = Math.random() * 0xffffffff | 0;
  255. const d1 = Math.random() * 0xffffffff | 0;
  256. const d2 = Math.random() * 0xffffffff | 0;
  257. const d3 = Math.random() * 0xffffffff | 0;
  258. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  259. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  260. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  261. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  262. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  263. return uuid.toLowerCase();
  264. }
  265. function clamp( value, min, max ) {
  266. return Math.max( min, Math.min( max, value ) );
  267. }
  268. // compute euclidean modulo of m % n
  269. // https://en.wikipedia.org/wiki/Modulo_operation
  270. function euclideanModulo( n, m ) {
  271. return ( ( n % m ) + m ) % m;
  272. }
  273. // Linear mapping from range <a1, a2> to range <b1, b2>
  274. function mapLinear( x, a1, a2, b1, b2 ) {
  275. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  276. }
  277. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  278. function inverseLerp( x, y, value ) {
  279. if ( x !== y ) {
  280. return ( value - x ) / ( y - x );
  281. } else {
  282. return 0;
  283. }
  284. }
  285. // https://en.wikipedia.org/wiki/Linear_interpolation
  286. function lerp( x, y, t ) {
  287. return ( 1 - t ) * x + t * y;
  288. }
  289. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  290. function damp( x, y, lambda, dt ) {
  291. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  292. }
  293. // https://www.desmos.com/calculator/vcsjnyz7x4
  294. function pingpong( x, length = 1 ) {
  295. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  296. }
  297. // http://en.wikipedia.org/wiki/Smoothstep
  298. function smoothstep( x, min, max ) {
  299. if ( x <= min ) return 0;
  300. if ( x >= max ) return 1;
  301. x = ( x - min ) / ( max - min );
  302. return x * x * ( 3 - 2 * x );
  303. }
  304. function smootherstep( x, min, max ) {
  305. if ( x <= min ) return 0;
  306. if ( x >= max ) return 1;
  307. x = ( x - min ) / ( max - min );
  308. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  309. }
  310. // Random integer from <low, high> interval
  311. function randInt( low, high ) {
  312. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  313. }
  314. // Random float from <low, high> interval
  315. function randFloat( low, high ) {
  316. return low + Math.random() * ( high - low );
  317. }
  318. // Random float from <-range/2, range/2> interval
  319. function randFloatSpread( range ) {
  320. return range * ( 0.5 - Math.random() );
  321. }
  322. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom( s ) {
  324. if ( s !== undefined ) _seed = s;
  325. // Mulberry32 generator
  326. let t = _seed += 0x6D2B79F5;
  327. t = Math.imul( t ^ t >>> 15, t | 1 );
  328. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  329. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  330. }
  331. function degToRad( degrees ) {
  332. return degrees * DEG2RAD;
  333. }
  334. function radToDeg( radians ) {
  335. return radians * RAD2DEG;
  336. }
  337. function isPowerOfTwo( value ) {
  338. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  339. }
  340. function ceilPowerOfTwo( value ) {
  341. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  342. }
  343. function floorPowerOfTwo( value ) {
  344. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  345. }
  346. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  347. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  348. // rotations are applied to the axes in the order specified by 'order'
  349. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  350. // angles are in radians
  351. const cos = Math.cos;
  352. const sin = Math.sin;
  353. const c2 = cos( b / 2 );
  354. const s2 = sin( b / 2 );
  355. const c13 = cos( ( a + c ) / 2 );
  356. const s13 = sin( ( a + c ) / 2 );
  357. const c1_3 = cos( ( a - c ) / 2 );
  358. const s1_3 = sin( ( a - c ) / 2 );
  359. const c3_1 = cos( ( c - a ) / 2 );
  360. const s3_1 = sin( ( c - a ) / 2 );
  361. switch ( order ) {
  362. case 'XYX':
  363. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  364. break;
  365. case 'YZY':
  366. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  367. break;
  368. case 'ZXZ':
  369. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  370. break;
  371. case 'XZX':
  372. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  373. break;
  374. case 'YXY':
  375. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  376. break;
  377. case 'ZYZ':
  378. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  379. break;
  380. default:
  381. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  382. }
  383. }
  384. function denormalize( value, array ) {
  385. switch ( array.constructor ) {
  386. case Float32Array:
  387. return value;
  388. case Uint32Array:
  389. return value / 4294967295.0;
  390. case Uint16Array:
  391. return value / 65535.0;
  392. case Uint8Array:
  393. return value / 255.0;
  394. case Int32Array:
  395. return Math.max( value / 2147483647.0, - 1.0 );
  396. case Int16Array:
  397. return Math.max( value / 32767.0, - 1.0 );
  398. case Int8Array:
  399. return Math.max( value / 127.0, - 1.0 );
  400. default:
  401. throw new Error( 'Invalid component type.' );
  402. }
  403. }
  404. function normalize( value, array ) {
  405. switch ( array.constructor ) {
  406. case Float32Array:
  407. return value;
  408. case Uint32Array:
  409. return Math.round( value * 4294967295.0 );
  410. case Uint16Array:
  411. return Math.round( value * 65535.0 );
  412. case Uint8Array:
  413. return Math.round( value * 255.0 );
  414. case Int32Array:
  415. return Math.round( value * 2147483647.0 );
  416. case Int16Array:
  417. return Math.round( value * 32767.0 );
  418. case Int8Array:
  419. return Math.round( value * 127.0 );
  420. default:
  421. throw new Error( 'Invalid component type.' );
  422. }
  423. }
  424. const MathUtils = {
  425. DEG2RAD: DEG2RAD,
  426. RAD2DEG: RAD2DEG,
  427. generateUUID: generateUUID,
  428. clamp: clamp,
  429. euclideanModulo: euclideanModulo,
  430. mapLinear: mapLinear,
  431. inverseLerp: inverseLerp,
  432. lerp: lerp,
  433. damp: damp,
  434. pingpong: pingpong,
  435. smoothstep: smoothstep,
  436. smootherstep: smootherstep,
  437. randInt: randInt,
  438. randFloat: randFloat,
  439. randFloatSpread: randFloatSpread,
  440. seededRandom: seededRandom,
  441. degToRad: degToRad,
  442. radToDeg: radToDeg,
  443. isPowerOfTwo: isPowerOfTwo,
  444. ceilPowerOfTwo: ceilPowerOfTwo,
  445. floorPowerOfTwo: floorPowerOfTwo,
  446. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  447. normalize: normalize,
  448. denormalize: denormalize
  449. };
  450. class Vector2 {
  451. constructor( x = 0, y = 0 ) {
  452. Vector2.prototype.isVector2 = true;
  453. this.x = x;
  454. this.y = y;
  455. }
  456. get width() {
  457. return this.x;
  458. }
  459. set width( value ) {
  460. this.x = value;
  461. }
  462. get height() {
  463. return this.y;
  464. }
  465. set height( value ) {
  466. this.y = value;
  467. }
  468. set( x, y ) {
  469. this.x = x;
  470. this.y = y;
  471. return this;
  472. }
  473. setScalar( scalar ) {
  474. this.x = scalar;
  475. this.y = scalar;
  476. return this;
  477. }
  478. setX( x ) {
  479. this.x = x;
  480. return this;
  481. }
  482. setY( y ) {
  483. this.y = y;
  484. return this;
  485. }
  486. setComponent( index, value ) {
  487. switch ( index ) {
  488. case 0: this.x = value; break;
  489. case 1: this.y = value; break;
  490. default: throw new Error( 'index is out of range: ' + index );
  491. }
  492. return this;
  493. }
  494. getComponent( index ) {
  495. switch ( index ) {
  496. case 0: return this.x;
  497. case 1: return this.y;
  498. default: throw new Error( 'index is out of range: ' + index );
  499. }
  500. }
  501. clone() {
  502. return new this.constructor( this.x, this.y );
  503. }
  504. copy( v ) {
  505. this.x = v.x;
  506. this.y = v.y;
  507. return this;
  508. }
  509. add( v ) {
  510. this.x += v.x;
  511. this.y += v.y;
  512. return this;
  513. }
  514. addScalar( s ) {
  515. this.x += s;
  516. this.y += s;
  517. return this;
  518. }
  519. addVectors( a, b ) {
  520. this.x = a.x + b.x;
  521. this.y = a.y + b.y;
  522. return this;
  523. }
  524. addScaledVector( v, s ) {
  525. this.x += v.x * s;
  526. this.y += v.y * s;
  527. return this;
  528. }
  529. sub( v ) {
  530. this.x -= v.x;
  531. this.y -= v.y;
  532. return this;
  533. }
  534. subScalar( s ) {
  535. this.x -= s;
  536. this.y -= s;
  537. return this;
  538. }
  539. subVectors( a, b ) {
  540. this.x = a.x - b.x;
  541. this.y = a.y - b.y;
  542. return this;
  543. }
  544. multiply( v ) {
  545. this.x *= v.x;
  546. this.y *= v.y;
  547. return this;
  548. }
  549. multiplyScalar( scalar ) {
  550. this.x *= scalar;
  551. this.y *= scalar;
  552. return this;
  553. }
  554. divide( v ) {
  555. this.x /= v.x;
  556. this.y /= v.y;
  557. return this;
  558. }
  559. divideScalar( scalar ) {
  560. return this.multiplyScalar( 1 / scalar );
  561. }
  562. applyMatrix3( m ) {
  563. const x = this.x, y = this.y;
  564. const e = m.elements;
  565. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  566. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  567. return this;
  568. }
  569. min( v ) {
  570. this.x = Math.min( this.x, v.x );
  571. this.y = Math.min( this.y, v.y );
  572. return this;
  573. }
  574. max( v ) {
  575. this.x = Math.max( this.x, v.x );
  576. this.y = Math.max( this.y, v.y );
  577. return this;
  578. }
  579. clamp( min, max ) {
  580. // assumes min < max, componentwise
  581. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  582. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  583. return this;
  584. }
  585. clampScalar( minVal, maxVal ) {
  586. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  587. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  588. return this;
  589. }
  590. clampLength( min, max ) {
  591. const length = this.length();
  592. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  593. }
  594. floor() {
  595. this.x = Math.floor( this.x );
  596. this.y = Math.floor( this.y );
  597. return this;
  598. }
  599. ceil() {
  600. this.x = Math.ceil( this.x );
  601. this.y = Math.ceil( this.y );
  602. return this;
  603. }
  604. round() {
  605. this.x = Math.round( this.x );
  606. this.y = Math.round( this.y );
  607. return this;
  608. }
  609. roundToZero() {
  610. this.x = Math.trunc( this.x );
  611. this.y = Math.trunc( this.y );
  612. return this;
  613. }
  614. negate() {
  615. this.x = - this.x;
  616. this.y = - this.y;
  617. return this;
  618. }
  619. dot( v ) {
  620. return this.x * v.x + this.y * v.y;
  621. }
  622. cross( v ) {
  623. return this.x * v.y - this.y * v.x;
  624. }
  625. lengthSq() {
  626. return this.x * this.x + this.y * this.y;
  627. }
  628. length() {
  629. return Math.sqrt( this.x * this.x + this.y * this.y );
  630. }
  631. manhattanLength() {
  632. return Math.abs( this.x ) + Math.abs( this.y );
  633. }
  634. normalize() {
  635. return this.divideScalar( this.length() || 1 );
  636. }
  637. angle() {
  638. // computes the angle in radians with respect to the positive x-axis
  639. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  640. return angle;
  641. }
  642. angleTo( v ) {
  643. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  644. if ( denominator === 0 ) return Math.PI / 2;
  645. const theta = this.dot( v ) / denominator;
  646. // clamp, to handle numerical problems
  647. return Math.acos( clamp( theta, - 1, 1 ) );
  648. }
  649. distanceTo( v ) {
  650. return Math.sqrt( this.distanceToSquared( v ) );
  651. }
  652. distanceToSquared( v ) {
  653. const dx = this.x - v.x, dy = this.y - v.y;
  654. return dx * dx + dy * dy;
  655. }
  656. manhattanDistanceTo( v ) {
  657. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  658. }
  659. setLength( length ) {
  660. return this.normalize().multiplyScalar( length );
  661. }
  662. lerp( v, alpha ) {
  663. this.x += ( v.x - this.x ) * alpha;
  664. this.y += ( v.y - this.y ) * alpha;
  665. return this;
  666. }
  667. lerpVectors( v1, v2, alpha ) {
  668. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  669. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  670. return this;
  671. }
  672. equals( v ) {
  673. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  674. }
  675. fromArray( array, offset = 0 ) {
  676. this.x = array[ offset ];
  677. this.y = array[ offset + 1 ];
  678. return this;
  679. }
  680. toArray( array = [], offset = 0 ) {
  681. array[ offset ] = this.x;
  682. array[ offset + 1 ] = this.y;
  683. return array;
  684. }
  685. fromBufferAttribute( attribute, index ) {
  686. this.x = attribute.getX( index );
  687. this.y = attribute.getY( index );
  688. return this;
  689. }
  690. rotateAround( center, angle ) {
  691. const c = Math.cos( angle ), s = Math.sin( angle );
  692. const x = this.x - center.x;
  693. const y = this.y - center.y;
  694. this.x = x * c - y * s + center.x;
  695. this.y = x * s + y * c + center.y;
  696. return this;
  697. }
  698. random() {
  699. this.x = Math.random();
  700. this.y = Math.random();
  701. return this;
  702. }
  703. *[ Symbol.iterator ]() {
  704. yield this.x;
  705. yield this.y;
  706. }
  707. }
  708. class Matrix3 {
  709. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  710. Matrix3.prototype.isMatrix3 = true;
  711. this.elements = [
  712. 1, 0, 0,
  713. 0, 1, 0,
  714. 0, 0, 1
  715. ];
  716. if ( n11 !== undefined ) {
  717. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  718. }
  719. }
  720. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  721. const te = this.elements;
  722. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  723. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  724. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  725. return this;
  726. }
  727. identity() {
  728. this.set(
  729. 1, 0, 0,
  730. 0, 1, 0,
  731. 0, 0, 1
  732. );
  733. return this;
  734. }
  735. copy( m ) {
  736. const te = this.elements;
  737. const me = m.elements;
  738. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  739. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  740. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  741. return this;
  742. }
  743. extractBasis( xAxis, yAxis, zAxis ) {
  744. xAxis.setFromMatrix3Column( this, 0 );
  745. yAxis.setFromMatrix3Column( this, 1 );
  746. zAxis.setFromMatrix3Column( this, 2 );
  747. return this;
  748. }
  749. setFromMatrix4( m ) {
  750. const me = m.elements;
  751. this.set(
  752. me[ 0 ], me[ 4 ], me[ 8 ],
  753. me[ 1 ], me[ 5 ], me[ 9 ],
  754. me[ 2 ], me[ 6 ], me[ 10 ]
  755. );
  756. return this;
  757. }
  758. multiply( m ) {
  759. return this.multiplyMatrices( this, m );
  760. }
  761. premultiply( m ) {
  762. return this.multiplyMatrices( m, this );
  763. }
  764. multiplyMatrices( a, b ) {
  765. const ae = a.elements;
  766. const be = b.elements;
  767. const te = this.elements;
  768. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  769. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  770. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  771. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  772. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  773. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  774. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  775. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  776. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  777. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  778. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  779. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  780. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  781. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  782. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  783. return this;
  784. }
  785. multiplyScalar( s ) {
  786. const te = this.elements;
  787. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  788. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  789. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  790. return this;
  791. }
  792. determinant() {
  793. const te = this.elements;
  794. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  795. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  796. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  797. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  798. }
  799. invert() {
  800. const te = this.elements,
  801. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  802. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  803. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  804. t11 = n33 * n22 - n32 * n23,
  805. t12 = n32 * n13 - n33 * n12,
  806. t13 = n23 * n12 - n22 * n13,
  807. det = n11 * t11 + n21 * t12 + n31 * t13;
  808. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  809. const detInv = 1 / det;
  810. te[ 0 ] = t11 * detInv;
  811. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  812. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  813. te[ 3 ] = t12 * detInv;
  814. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  815. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  816. te[ 6 ] = t13 * detInv;
  817. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  818. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  819. return this;
  820. }
  821. transpose() {
  822. let tmp;
  823. const m = this.elements;
  824. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  825. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  826. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  827. return this;
  828. }
  829. getNormalMatrix( matrix4 ) {
  830. return this.setFromMatrix4( matrix4 ).invert().transpose();
  831. }
  832. transposeIntoArray( r ) {
  833. const m = this.elements;
  834. r[ 0 ] = m[ 0 ];
  835. r[ 1 ] = m[ 3 ];
  836. r[ 2 ] = m[ 6 ];
  837. r[ 3 ] = m[ 1 ];
  838. r[ 4 ] = m[ 4 ];
  839. r[ 5 ] = m[ 7 ];
  840. r[ 6 ] = m[ 2 ];
  841. r[ 7 ] = m[ 5 ];
  842. r[ 8 ] = m[ 8 ];
  843. return this;
  844. }
  845. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  846. const c = Math.cos( rotation );
  847. const s = Math.sin( rotation );
  848. this.set(
  849. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  850. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  851. 0, 0, 1
  852. );
  853. return this;
  854. }
  855. //
  856. scale( sx, sy ) {
  857. this.premultiply( _m3.makeScale( sx, sy ) );
  858. return this;
  859. }
  860. rotate( theta ) {
  861. this.premultiply( _m3.makeRotation( - theta ) );
  862. return this;
  863. }
  864. translate( tx, ty ) {
  865. this.premultiply( _m3.makeTranslation( tx, ty ) );
  866. return this;
  867. }
  868. // for 2D Transforms
  869. makeTranslation( x, y ) {
  870. if ( x.isVector2 ) {
  871. this.set(
  872. 1, 0, x.x,
  873. 0, 1, x.y,
  874. 0, 0, 1
  875. );
  876. } else {
  877. this.set(
  878. 1, 0, x,
  879. 0, 1, y,
  880. 0, 0, 1
  881. );
  882. }
  883. return this;
  884. }
  885. makeRotation( theta ) {
  886. // counterclockwise
  887. const c = Math.cos( theta );
  888. const s = Math.sin( theta );
  889. this.set(
  890. c, - s, 0,
  891. s, c, 0,
  892. 0, 0, 1
  893. );
  894. return this;
  895. }
  896. makeScale( x, y ) {
  897. this.set(
  898. x, 0, 0,
  899. 0, y, 0,
  900. 0, 0, 1
  901. );
  902. return this;
  903. }
  904. //
  905. equals( matrix ) {
  906. const te = this.elements;
  907. const me = matrix.elements;
  908. for ( let i = 0; i < 9; i ++ ) {
  909. if ( te[ i ] !== me[ i ] ) return false;
  910. }
  911. return true;
  912. }
  913. fromArray( array, offset = 0 ) {
  914. for ( let i = 0; i < 9; i ++ ) {
  915. this.elements[ i ] = array[ i + offset ];
  916. }
  917. return this;
  918. }
  919. toArray( array = [], offset = 0 ) {
  920. const te = this.elements;
  921. array[ offset ] = te[ 0 ];
  922. array[ offset + 1 ] = te[ 1 ];
  923. array[ offset + 2 ] = te[ 2 ];
  924. array[ offset + 3 ] = te[ 3 ];
  925. array[ offset + 4 ] = te[ 4 ];
  926. array[ offset + 5 ] = te[ 5 ];
  927. array[ offset + 6 ] = te[ 6 ];
  928. array[ offset + 7 ] = te[ 7 ];
  929. array[ offset + 8 ] = te[ 8 ];
  930. return array;
  931. }
  932. clone() {
  933. return new this.constructor().fromArray( this.elements );
  934. }
  935. }
  936. const _m3 = /*@__PURE__*/ new Matrix3();
  937. function arrayNeedsUint32( array ) {
  938. // assumes larger values usually on last
  939. for ( let i = array.length - 1; i >= 0; -- i ) {
  940. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  941. }
  942. return false;
  943. }
  944. const TYPED_ARRAYS = {
  945. Int8Array: Int8Array,
  946. Uint8Array: Uint8Array,
  947. Uint8ClampedArray: Uint8ClampedArray,
  948. Int16Array: Int16Array,
  949. Uint16Array: Uint16Array,
  950. Int32Array: Int32Array,
  951. Uint32Array: Uint32Array,
  952. Float32Array: Float32Array,
  953. Float64Array: Float64Array
  954. };
  955. function getTypedArray( type, buffer ) {
  956. return new TYPED_ARRAYS[ type ]( buffer );
  957. }
  958. function createElementNS( name ) {
  959. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  960. }
  961. function createCanvasElement() {
  962. const canvas = createElementNS( 'canvas' );
  963. canvas.style.display = 'block';
  964. return canvas;
  965. }
  966. const _cache = {};
  967. function warnOnce( message ) {
  968. if ( message in _cache ) return;
  969. _cache[ message ] = true;
  970. console.warn( message );
  971. }
  972. /**
  973. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  974. * or clipping. Based on W3C specifications for sRGB and Display P3,
  975. * and ICC specifications for the D50 connection space. Values in/out
  976. * are _linear_ sRGB and _linear_ Display P3.
  977. *
  978. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  979. *
  980. * Reference:
  981. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  982. */
  983. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  984. 0.8224621, 0.177538, 0.0,
  985. 0.0331941, 0.9668058, 0.0,
  986. 0.0170827, 0.0723974, 0.9105199,
  987. );
  988. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  989. 1.2249401, - 0.2249404, 0.0,
  990. - 0.0420569, 1.0420571, 0.0,
  991. - 0.0196376, - 0.0786361, 1.0982735
  992. );
  993. /**
  994. * Defines supported color spaces by transfer function and primaries,
  995. * and provides conversions to/from the Linear-sRGB reference space.
  996. */
  997. const COLOR_SPACES = {
  998. [ LinearSRGBColorSpace ]: {
  999. transfer: LinearTransfer,
  1000. primaries: Rec709Primaries,
  1001. toReference: ( color ) => color,
  1002. fromReference: ( color ) => color,
  1003. },
  1004. [ SRGBColorSpace ]: {
  1005. transfer: SRGBTransfer,
  1006. primaries: Rec709Primaries,
  1007. toReference: ( color ) => color.convertSRGBToLinear(),
  1008. fromReference: ( color ) => color.convertLinearToSRGB(),
  1009. },
  1010. [ LinearDisplayP3ColorSpace ]: {
  1011. transfer: LinearTransfer,
  1012. primaries: P3Primaries,
  1013. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1014. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1015. },
  1016. [ DisplayP3ColorSpace ]: {
  1017. transfer: SRGBTransfer,
  1018. primaries: P3Primaries,
  1019. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1020. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1021. },
  1022. };
  1023. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1024. const ColorManagement = {
  1025. enabled: true,
  1026. _workingColorSpace: LinearSRGBColorSpace,
  1027. get legacyMode() {
  1028. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1029. return ! this.enabled;
  1030. },
  1031. set legacyMode( legacyMode ) {
  1032. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1033. this.enabled = ! legacyMode;
  1034. },
  1035. get workingColorSpace() {
  1036. return this._workingColorSpace;
  1037. },
  1038. set workingColorSpace( colorSpace ) {
  1039. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1040. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1041. }
  1042. this._workingColorSpace = colorSpace;
  1043. },
  1044. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1045. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1046. return color;
  1047. }
  1048. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1049. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1050. return targetFromReference( sourceToReference( color ) );
  1051. },
  1052. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1053. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1054. },
  1055. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1056. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1057. },
  1058. getPrimaries: function ( colorSpace ) {
  1059. return COLOR_SPACES[ colorSpace ].primaries;
  1060. },
  1061. getTransfer: function ( colorSpace ) {
  1062. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1063. return COLOR_SPACES[ colorSpace ].transfer;
  1064. },
  1065. };
  1066. function SRGBToLinear( c ) {
  1067. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1068. }
  1069. function LinearToSRGB( c ) {
  1070. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1071. }
  1072. let _canvas;
  1073. class ImageUtils {
  1074. static getDataURL( image ) {
  1075. if ( /^data:/i.test( image.src ) ) {
  1076. return image.src;
  1077. }
  1078. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1079. return image.src;
  1080. }
  1081. let canvas;
  1082. if ( image instanceof HTMLCanvasElement ) {
  1083. canvas = image;
  1084. } else {
  1085. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1086. _canvas.width = image.width;
  1087. _canvas.height = image.height;
  1088. const context = _canvas.getContext( '2d' );
  1089. if ( image instanceof ImageData ) {
  1090. context.putImageData( image, 0, 0 );
  1091. } else {
  1092. context.drawImage( image, 0, 0, image.width, image.height );
  1093. }
  1094. canvas = _canvas;
  1095. }
  1096. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1097. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1098. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1099. } else {
  1100. return canvas.toDataURL( 'image/png' );
  1101. }
  1102. }
  1103. static sRGBToLinear( image ) {
  1104. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1105. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1106. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1107. const canvas = createElementNS( 'canvas' );
  1108. canvas.width = image.width;
  1109. canvas.height = image.height;
  1110. const context = canvas.getContext( '2d' );
  1111. context.drawImage( image, 0, 0, image.width, image.height );
  1112. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1113. const data = imageData.data;
  1114. for ( let i = 0; i < data.length; i ++ ) {
  1115. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1116. }
  1117. context.putImageData( imageData, 0, 0 );
  1118. return canvas;
  1119. } else if ( image.data ) {
  1120. const data = image.data.slice( 0 );
  1121. for ( let i = 0; i < data.length; i ++ ) {
  1122. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1123. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1124. } else {
  1125. // assuming float
  1126. data[ i ] = SRGBToLinear( data[ i ] );
  1127. }
  1128. }
  1129. return {
  1130. data: data,
  1131. width: image.width,
  1132. height: image.height
  1133. };
  1134. } else {
  1135. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1136. return image;
  1137. }
  1138. }
  1139. }
  1140. let _sourceId = 0;
  1141. class Source {
  1142. constructor( data = null ) {
  1143. this.isSource = true;
  1144. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1145. this.uuid = generateUUID();
  1146. this.data = data;
  1147. this.version = 0;
  1148. }
  1149. set needsUpdate( value ) {
  1150. if ( value === true ) this.version ++;
  1151. }
  1152. toJSON( meta ) {
  1153. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1154. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1155. return meta.images[ this.uuid ];
  1156. }
  1157. const output = {
  1158. uuid: this.uuid,
  1159. url: ''
  1160. };
  1161. const data = this.data;
  1162. if ( data !== null ) {
  1163. let url;
  1164. if ( Array.isArray( data ) ) {
  1165. // cube texture
  1166. url = [];
  1167. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1168. if ( data[ i ].isDataTexture ) {
  1169. url.push( serializeImage( data[ i ].image ) );
  1170. } else {
  1171. url.push( serializeImage( data[ i ] ) );
  1172. }
  1173. }
  1174. } else {
  1175. // texture
  1176. url = serializeImage( data );
  1177. }
  1178. output.url = url;
  1179. }
  1180. if ( ! isRootObject ) {
  1181. meta.images[ this.uuid ] = output;
  1182. }
  1183. return output;
  1184. }
  1185. }
  1186. function serializeImage( image ) {
  1187. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1188. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1189. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1190. // default images
  1191. return ImageUtils.getDataURL( image );
  1192. } else {
  1193. if ( image.data ) {
  1194. // images of DataTexture
  1195. return {
  1196. data: Array.from( image.data ),
  1197. width: image.width,
  1198. height: image.height,
  1199. type: image.data.constructor.name
  1200. };
  1201. } else {
  1202. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1203. return {};
  1204. }
  1205. }
  1206. }
  1207. let _textureId = 0;
  1208. class Texture extends EventDispatcher {
  1209. 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 ) {
  1210. super();
  1211. this.isTexture = true;
  1212. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1213. this.uuid = generateUUID();
  1214. this.name = '';
  1215. this.source = new Source( image );
  1216. this.mipmaps = [];
  1217. this.mapping = mapping;
  1218. this.channel = 0;
  1219. this.wrapS = wrapS;
  1220. this.wrapT = wrapT;
  1221. this.magFilter = magFilter;
  1222. this.minFilter = minFilter;
  1223. this.anisotropy = anisotropy;
  1224. this.format = format;
  1225. this.internalFormat = null;
  1226. this.type = type;
  1227. this.offset = new Vector2( 0, 0 );
  1228. this.repeat = new Vector2( 1, 1 );
  1229. this.center = new Vector2( 0, 0 );
  1230. this.rotation = 0;
  1231. this.matrixAutoUpdate = true;
  1232. this.matrix = new Matrix3();
  1233. this.generateMipmaps = true;
  1234. this.premultiplyAlpha = false;
  1235. this.flipY = true;
  1236. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1237. if ( typeof colorSpace === 'string' ) {
  1238. this.colorSpace = colorSpace;
  1239. } else { // @deprecated, r152
  1240. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1241. this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1242. }
  1243. this.userData = {};
  1244. this.version = 0;
  1245. this.onUpdate = null;
  1246. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1247. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1248. }
  1249. get image() {
  1250. return this.source.data;
  1251. }
  1252. set image( value = null ) {
  1253. this.source.data = value;
  1254. }
  1255. updateMatrix() {
  1256. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1257. }
  1258. clone() {
  1259. return new this.constructor().copy( this );
  1260. }
  1261. copy( source ) {
  1262. this.name = source.name;
  1263. this.source = source.source;
  1264. this.mipmaps = source.mipmaps.slice( 0 );
  1265. this.mapping = source.mapping;
  1266. this.channel = source.channel;
  1267. this.wrapS = source.wrapS;
  1268. this.wrapT = source.wrapT;
  1269. this.magFilter = source.magFilter;
  1270. this.minFilter = source.minFilter;
  1271. this.anisotropy = source.anisotropy;
  1272. this.format = source.format;
  1273. this.internalFormat = source.internalFormat;
  1274. this.type = source.type;
  1275. this.offset.copy( source.offset );
  1276. this.repeat.copy( source.repeat );
  1277. this.center.copy( source.center );
  1278. this.rotation = source.rotation;
  1279. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1280. this.matrix.copy( source.matrix );
  1281. this.generateMipmaps = source.generateMipmaps;
  1282. this.premultiplyAlpha = source.premultiplyAlpha;
  1283. this.flipY = source.flipY;
  1284. this.unpackAlignment = source.unpackAlignment;
  1285. this.colorSpace = source.colorSpace;
  1286. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1287. this.needsUpdate = true;
  1288. return this;
  1289. }
  1290. toJSON( meta ) {
  1291. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1292. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1293. return meta.textures[ this.uuid ];
  1294. }
  1295. const output = {
  1296. metadata: {
  1297. version: 4.6,
  1298. type: 'Texture',
  1299. generator: 'Texture.toJSON'
  1300. },
  1301. uuid: this.uuid,
  1302. name: this.name,
  1303. image: this.source.toJSON( meta ).uuid,
  1304. mapping: this.mapping,
  1305. channel: this.channel,
  1306. repeat: [ this.repeat.x, this.repeat.y ],
  1307. offset: [ this.offset.x, this.offset.y ],
  1308. center: [ this.center.x, this.center.y ],
  1309. rotation: this.rotation,
  1310. wrap: [ this.wrapS, this.wrapT ],
  1311. format: this.format,
  1312. internalFormat: this.internalFormat,
  1313. type: this.type,
  1314. colorSpace: this.colorSpace,
  1315. minFilter: this.minFilter,
  1316. magFilter: this.magFilter,
  1317. anisotropy: this.anisotropy,
  1318. flipY: this.flipY,
  1319. generateMipmaps: this.generateMipmaps,
  1320. premultiplyAlpha: this.premultiplyAlpha,
  1321. unpackAlignment: this.unpackAlignment
  1322. };
  1323. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1324. if ( ! isRootObject ) {
  1325. meta.textures[ this.uuid ] = output;
  1326. }
  1327. return output;
  1328. }
  1329. dispose() {
  1330. this.dispatchEvent( { type: 'dispose' } );
  1331. }
  1332. transformUv( uv ) {
  1333. if ( this.mapping !== UVMapping ) return uv;
  1334. uv.applyMatrix3( this.matrix );
  1335. if ( uv.x < 0 || uv.x > 1 ) {
  1336. switch ( this.wrapS ) {
  1337. case RepeatWrapping:
  1338. uv.x = uv.x - Math.floor( uv.x );
  1339. break;
  1340. case ClampToEdgeWrapping:
  1341. uv.x = uv.x < 0 ? 0 : 1;
  1342. break;
  1343. case MirroredRepeatWrapping:
  1344. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1345. uv.x = Math.ceil( uv.x ) - uv.x;
  1346. } else {
  1347. uv.x = uv.x - Math.floor( uv.x );
  1348. }
  1349. break;
  1350. }
  1351. }
  1352. if ( uv.y < 0 || uv.y > 1 ) {
  1353. switch ( this.wrapT ) {
  1354. case RepeatWrapping:
  1355. uv.y = uv.y - Math.floor( uv.y );
  1356. break;
  1357. case ClampToEdgeWrapping:
  1358. uv.y = uv.y < 0 ? 0 : 1;
  1359. break;
  1360. case MirroredRepeatWrapping:
  1361. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1362. uv.y = Math.ceil( uv.y ) - uv.y;
  1363. } else {
  1364. uv.y = uv.y - Math.floor( uv.y );
  1365. }
  1366. break;
  1367. }
  1368. }
  1369. if ( this.flipY ) {
  1370. uv.y = 1 - uv.y;
  1371. }
  1372. return uv;
  1373. }
  1374. set needsUpdate( value ) {
  1375. if ( value === true ) {
  1376. this.version ++;
  1377. this.source.needsUpdate = true;
  1378. }
  1379. }
  1380. get encoding() { // @deprecated, r152
  1381. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1382. return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  1383. }
  1384. set encoding( encoding ) { // @deprecated, r152
  1385. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1386. this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1387. }
  1388. }
  1389. Texture.DEFAULT_IMAGE = null;
  1390. Texture.DEFAULT_MAPPING = UVMapping;
  1391. Texture.DEFAULT_ANISOTROPY = 1;
  1392. class Vector4 {
  1393. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1394. Vector4.prototype.isVector4 = true;
  1395. this.x = x;
  1396. this.y = y;
  1397. this.z = z;
  1398. this.w = w;
  1399. }
  1400. get width() {
  1401. return this.z;
  1402. }
  1403. set width( value ) {
  1404. this.z = value;
  1405. }
  1406. get height() {
  1407. return this.w;
  1408. }
  1409. set height( value ) {
  1410. this.w = value;
  1411. }
  1412. set( x, y, z, w ) {
  1413. this.x = x;
  1414. this.y = y;
  1415. this.z = z;
  1416. this.w = w;
  1417. return this;
  1418. }
  1419. setScalar( scalar ) {
  1420. this.x = scalar;
  1421. this.y = scalar;
  1422. this.z = scalar;
  1423. this.w = scalar;
  1424. return this;
  1425. }
  1426. setX( x ) {
  1427. this.x = x;
  1428. return this;
  1429. }
  1430. setY( y ) {
  1431. this.y = y;
  1432. return this;
  1433. }
  1434. setZ( z ) {
  1435. this.z = z;
  1436. return this;
  1437. }
  1438. setW( w ) {
  1439. this.w = w;
  1440. return this;
  1441. }
  1442. setComponent( index, value ) {
  1443. switch ( index ) {
  1444. case 0: this.x = value; break;
  1445. case 1: this.y = value; break;
  1446. case 2: this.z = value; break;
  1447. case 3: this.w = value; break;
  1448. default: throw new Error( 'index is out of range: ' + index );
  1449. }
  1450. return this;
  1451. }
  1452. getComponent( index ) {
  1453. switch ( index ) {
  1454. case 0: return this.x;
  1455. case 1: return this.y;
  1456. case 2: return this.z;
  1457. case 3: return this.w;
  1458. default: throw new Error( 'index is out of range: ' + index );
  1459. }
  1460. }
  1461. clone() {
  1462. return new this.constructor( this.x, this.y, this.z, this.w );
  1463. }
  1464. copy( v ) {
  1465. this.x = v.x;
  1466. this.y = v.y;
  1467. this.z = v.z;
  1468. this.w = ( v.w !== undefined ) ? v.w : 1;
  1469. return this;
  1470. }
  1471. add( v ) {
  1472. this.x += v.x;
  1473. this.y += v.y;
  1474. this.z += v.z;
  1475. this.w += v.w;
  1476. return this;
  1477. }
  1478. addScalar( s ) {
  1479. this.x += s;
  1480. this.y += s;
  1481. this.z += s;
  1482. this.w += s;
  1483. return this;
  1484. }
  1485. addVectors( a, b ) {
  1486. this.x = a.x + b.x;
  1487. this.y = a.y + b.y;
  1488. this.z = a.z + b.z;
  1489. this.w = a.w + b.w;
  1490. return this;
  1491. }
  1492. addScaledVector( v, s ) {
  1493. this.x += v.x * s;
  1494. this.y += v.y * s;
  1495. this.z += v.z * s;
  1496. this.w += v.w * s;
  1497. return this;
  1498. }
  1499. sub( v ) {
  1500. this.x -= v.x;
  1501. this.y -= v.y;
  1502. this.z -= v.z;
  1503. this.w -= v.w;
  1504. return this;
  1505. }
  1506. subScalar( s ) {
  1507. this.x -= s;
  1508. this.y -= s;
  1509. this.z -= s;
  1510. this.w -= s;
  1511. return this;
  1512. }
  1513. subVectors( a, b ) {
  1514. this.x = a.x - b.x;
  1515. this.y = a.y - b.y;
  1516. this.z = a.z - b.z;
  1517. this.w = a.w - b.w;
  1518. return this;
  1519. }
  1520. multiply( v ) {
  1521. this.x *= v.x;
  1522. this.y *= v.y;
  1523. this.z *= v.z;
  1524. this.w *= v.w;
  1525. return this;
  1526. }
  1527. multiplyScalar( scalar ) {
  1528. this.x *= scalar;
  1529. this.y *= scalar;
  1530. this.z *= scalar;
  1531. this.w *= scalar;
  1532. return this;
  1533. }
  1534. applyMatrix4( m ) {
  1535. const x = this.x, y = this.y, z = this.z, w = this.w;
  1536. const e = m.elements;
  1537. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1538. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1539. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1540. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1541. return this;
  1542. }
  1543. divideScalar( scalar ) {
  1544. return this.multiplyScalar( 1 / scalar );
  1545. }
  1546. setAxisAngleFromQuaternion( q ) {
  1547. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1548. // q is assumed to be normalized
  1549. this.w = 2 * Math.acos( q.w );
  1550. const s = Math.sqrt( 1 - q.w * q.w );
  1551. if ( s < 0.0001 ) {
  1552. this.x = 1;
  1553. this.y = 0;
  1554. this.z = 0;
  1555. } else {
  1556. this.x = q.x / s;
  1557. this.y = q.y / s;
  1558. this.z = q.z / s;
  1559. }
  1560. return this;
  1561. }
  1562. setAxisAngleFromRotationMatrix( m ) {
  1563. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1564. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1565. let angle, x, y, z; // variables for result
  1566. const epsilon = 0.01, // margin to allow for rounding errors
  1567. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1568. te = m.elements,
  1569. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1570. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1571. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1572. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1573. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1574. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1575. // singularity found
  1576. // first check for identity matrix which must have +1 for all terms
  1577. // in leading diagonal and zero in other terms
  1578. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1579. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1580. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1581. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1582. // this singularity is identity matrix so angle = 0
  1583. this.set( 1, 0, 0, 0 );
  1584. return this; // zero angle, arbitrary axis
  1585. }
  1586. // otherwise this singularity is angle = 180
  1587. angle = Math.PI;
  1588. const xx = ( m11 + 1 ) / 2;
  1589. const yy = ( m22 + 1 ) / 2;
  1590. const zz = ( m33 + 1 ) / 2;
  1591. const xy = ( m12 + m21 ) / 4;
  1592. const xz = ( m13 + m31 ) / 4;
  1593. const yz = ( m23 + m32 ) / 4;
  1594. if ( ( xx > yy ) && ( xx > zz ) ) {
  1595. // m11 is the largest diagonal term
  1596. if ( xx < epsilon ) {
  1597. x = 0;
  1598. y = 0.707106781;
  1599. z = 0.707106781;
  1600. } else {
  1601. x = Math.sqrt( xx );
  1602. y = xy / x;
  1603. z = xz / x;
  1604. }
  1605. } else if ( yy > zz ) {
  1606. // m22 is the largest diagonal term
  1607. if ( yy < epsilon ) {
  1608. x = 0.707106781;
  1609. y = 0;
  1610. z = 0.707106781;
  1611. } else {
  1612. y = Math.sqrt( yy );
  1613. x = xy / y;
  1614. z = yz / y;
  1615. }
  1616. } else {
  1617. // m33 is the largest diagonal term so base result on this
  1618. if ( zz < epsilon ) {
  1619. x = 0.707106781;
  1620. y = 0.707106781;
  1621. z = 0;
  1622. } else {
  1623. z = Math.sqrt( zz );
  1624. x = xz / z;
  1625. y = yz / z;
  1626. }
  1627. }
  1628. this.set( x, y, z, angle );
  1629. return this; // return 180 deg rotation
  1630. }
  1631. // as we have reached here there are no singularities so we can handle normally
  1632. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1633. ( m13 - m31 ) * ( m13 - m31 ) +
  1634. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1635. if ( Math.abs( s ) < 0.001 ) s = 1;
  1636. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1637. // caught by singularity test above, but I've left it in just in case
  1638. this.x = ( m32 - m23 ) / s;
  1639. this.y = ( m13 - m31 ) / s;
  1640. this.z = ( m21 - m12 ) / s;
  1641. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1642. return this;
  1643. }
  1644. min( v ) {
  1645. this.x = Math.min( this.x, v.x );
  1646. this.y = Math.min( this.y, v.y );
  1647. this.z = Math.min( this.z, v.z );
  1648. this.w = Math.min( this.w, v.w );
  1649. return this;
  1650. }
  1651. max( v ) {
  1652. this.x = Math.max( this.x, v.x );
  1653. this.y = Math.max( this.y, v.y );
  1654. this.z = Math.max( this.z, v.z );
  1655. this.w = Math.max( this.w, v.w );
  1656. return this;
  1657. }
  1658. clamp( min, max ) {
  1659. // assumes min < max, componentwise
  1660. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1661. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1662. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1663. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1664. return this;
  1665. }
  1666. clampScalar( minVal, maxVal ) {
  1667. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1668. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1669. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1670. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1671. return this;
  1672. }
  1673. clampLength( min, max ) {
  1674. const length = this.length();
  1675. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1676. }
  1677. floor() {
  1678. this.x = Math.floor( this.x );
  1679. this.y = Math.floor( this.y );
  1680. this.z = Math.floor( this.z );
  1681. this.w = Math.floor( this.w );
  1682. return this;
  1683. }
  1684. ceil() {
  1685. this.x = Math.ceil( this.x );
  1686. this.y = Math.ceil( this.y );
  1687. this.z = Math.ceil( this.z );
  1688. this.w = Math.ceil( this.w );
  1689. return this;
  1690. }
  1691. round() {
  1692. this.x = Math.round( this.x );
  1693. this.y = Math.round( this.y );
  1694. this.z = Math.round( this.z );
  1695. this.w = Math.round( this.w );
  1696. return this;
  1697. }
  1698. roundToZero() {
  1699. this.x = Math.trunc( this.x );
  1700. this.y = Math.trunc( this.y );
  1701. this.z = Math.trunc( this.z );
  1702. this.w = Math.trunc( this.w );
  1703. return this;
  1704. }
  1705. negate() {
  1706. this.x = - this.x;
  1707. this.y = - this.y;
  1708. this.z = - this.z;
  1709. this.w = - this.w;
  1710. return this;
  1711. }
  1712. dot( v ) {
  1713. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1714. }
  1715. lengthSq() {
  1716. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1717. }
  1718. length() {
  1719. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1720. }
  1721. manhattanLength() {
  1722. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1723. }
  1724. normalize() {
  1725. return this.divideScalar( this.length() || 1 );
  1726. }
  1727. setLength( length ) {
  1728. return this.normalize().multiplyScalar( length );
  1729. }
  1730. lerp( v, alpha ) {
  1731. this.x += ( v.x - this.x ) * alpha;
  1732. this.y += ( v.y - this.y ) * alpha;
  1733. this.z += ( v.z - this.z ) * alpha;
  1734. this.w += ( v.w - this.w ) * alpha;
  1735. return this;
  1736. }
  1737. lerpVectors( v1, v2, alpha ) {
  1738. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1739. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1740. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1741. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1742. return this;
  1743. }
  1744. equals( v ) {
  1745. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1746. }
  1747. fromArray( array, offset = 0 ) {
  1748. this.x = array[ offset ];
  1749. this.y = array[ offset + 1 ];
  1750. this.z = array[ offset + 2 ];
  1751. this.w = array[ offset + 3 ];
  1752. return this;
  1753. }
  1754. toArray( array = [], offset = 0 ) {
  1755. array[ offset ] = this.x;
  1756. array[ offset + 1 ] = this.y;
  1757. array[ offset + 2 ] = this.z;
  1758. array[ offset + 3 ] = this.w;
  1759. return array;
  1760. }
  1761. fromBufferAttribute( attribute, index ) {
  1762. this.x = attribute.getX( index );
  1763. this.y = attribute.getY( index );
  1764. this.z = attribute.getZ( index );
  1765. this.w = attribute.getW( index );
  1766. return this;
  1767. }
  1768. random() {
  1769. this.x = Math.random();
  1770. this.y = Math.random();
  1771. this.z = Math.random();
  1772. this.w = Math.random();
  1773. return this;
  1774. }
  1775. *[ Symbol.iterator ]() {
  1776. yield this.x;
  1777. yield this.y;
  1778. yield this.z;
  1779. yield this.w;
  1780. }
  1781. }
  1782. /*
  1783. In options, we can specify:
  1784. * Texture parameters for an auto-generated target texture
  1785. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1786. */
  1787. class RenderTarget extends EventDispatcher {
  1788. constructor( width = 1, height = 1, options = {} ) {
  1789. super();
  1790. this.isRenderTarget = true;
  1791. this.width = width;
  1792. this.height = height;
  1793. this.depth = 1;
  1794. this.scissor = new Vector4( 0, 0, width, height );
  1795. this.scissorTest = false;
  1796. this.viewport = new Vector4( 0, 0, width, height );
  1797. const image = { width: width, height: height, depth: 1 };
  1798. if ( options.encoding !== undefined ) {
  1799. // @deprecated, r152
  1800. warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  1801. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1802. }
  1803. options = Object.assign( {
  1804. generateMipmaps: false,
  1805. internalFormat: null,
  1806. minFilter: LinearFilter,
  1807. depthBuffer: true,
  1808. stencilBuffer: false,
  1809. depthTexture: null,
  1810. samples: 0
  1811. }, options );
  1812. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1813. this.texture.isRenderTargetTexture = true;
  1814. this.texture.flipY = false;
  1815. this.texture.generateMipmaps = options.generateMipmaps;
  1816. this.texture.internalFormat = options.internalFormat;
  1817. this.depthBuffer = options.depthBuffer;
  1818. this.stencilBuffer = options.stencilBuffer;
  1819. this.depthTexture = options.depthTexture;
  1820. this.samples = options.samples;
  1821. }
  1822. setSize( width, height, depth = 1 ) {
  1823. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1824. this.width = width;
  1825. this.height = height;
  1826. this.depth = depth;
  1827. this.texture.image.width = width;
  1828. this.texture.image.height = height;
  1829. this.texture.image.depth = depth;
  1830. this.dispose();
  1831. }
  1832. this.viewport.set( 0, 0, width, height );
  1833. this.scissor.set( 0, 0, width, height );
  1834. }
  1835. clone() {
  1836. return new this.constructor().copy( this );
  1837. }
  1838. copy( source ) {
  1839. this.width = source.width;
  1840. this.height = source.height;
  1841. this.depth = source.depth;
  1842. this.scissor.copy( source.scissor );
  1843. this.scissorTest = source.scissorTest;
  1844. this.viewport.copy( source.viewport );
  1845. this.texture = source.texture.clone();
  1846. this.texture.isRenderTargetTexture = true;
  1847. // ensure image object is not shared, see #20328
  1848. const image = Object.assign( {}, source.texture.image );
  1849. this.texture.source = new Source( image );
  1850. this.depthBuffer = source.depthBuffer;
  1851. this.stencilBuffer = source.stencilBuffer;
  1852. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1853. this.samples = source.samples;
  1854. return this;
  1855. }
  1856. dispose() {
  1857. this.dispatchEvent( { type: 'dispose' } );
  1858. }
  1859. }
  1860. class WebGLRenderTarget extends RenderTarget {
  1861. constructor( width = 1, height = 1, options = {} ) {
  1862. super( width, height, options );
  1863. this.isWebGLRenderTarget = true;
  1864. }
  1865. }
  1866. class DataArrayTexture extends Texture {
  1867. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1868. super( null );
  1869. this.isDataArrayTexture = true;
  1870. this.image = { data, width, height, depth };
  1871. this.magFilter = NearestFilter;
  1872. this.minFilter = NearestFilter;
  1873. this.wrapR = ClampToEdgeWrapping;
  1874. this.generateMipmaps = false;
  1875. this.flipY = false;
  1876. this.unpackAlignment = 1;
  1877. }
  1878. }
  1879. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1880. constructor( width = 1, height = 1, depth = 1 ) {
  1881. super( width, height );
  1882. this.isWebGLArrayRenderTarget = true;
  1883. this.depth = depth;
  1884. this.texture = new DataArrayTexture( null, width, height, depth );
  1885. this.texture.isRenderTargetTexture = true;
  1886. }
  1887. }
  1888. class Data3DTexture extends Texture {
  1889. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1890. // We're going to add .setXXX() methods for setting properties later.
  1891. // Users can still set in DataTexture3D directly.
  1892. //
  1893. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1894. // texture.anisotropy = 16;
  1895. //
  1896. // See #14839
  1897. super( null );
  1898. this.isData3DTexture = true;
  1899. this.image = { data, width, height, depth };
  1900. this.magFilter = NearestFilter;
  1901. this.minFilter = NearestFilter;
  1902. this.wrapR = ClampToEdgeWrapping;
  1903. this.generateMipmaps = false;
  1904. this.flipY = false;
  1905. this.unpackAlignment = 1;
  1906. }
  1907. }
  1908. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1909. constructor( width = 1, height = 1, depth = 1 ) {
  1910. super( width, height );
  1911. this.isWebGL3DRenderTarget = true;
  1912. this.depth = depth;
  1913. this.texture = new Data3DTexture( null, width, height, depth );
  1914. this.texture.isRenderTargetTexture = true;
  1915. }
  1916. }
  1917. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1918. constructor( width = 1, height = 1, count = 1, options = {} ) {
  1919. super( width, height, options );
  1920. this.isWebGLMultipleRenderTargets = true;
  1921. const texture = this.texture;
  1922. this.texture = [];
  1923. for ( let i = 0; i < count; i ++ ) {
  1924. this.texture[ i ] = texture.clone();
  1925. this.texture[ i ].isRenderTargetTexture = true;
  1926. }
  1927. }
  1928. setSize( width, height, depth = 1 ) {
  1929. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1930. this.width = width;
  1931. this.height = height;
  1932. this.depth = depth;
  1933. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1934. this.texture[ i ].image.width = width;
  1935. this.texture[ i ].image.height = height;
  1936. this.texture[ i ].image.depth = depth;
  1937. }
  1938. this.dispose();
  1939. }
  1940. this.viewport.set( 0, 0, width, height );
  1941. this.scissor.set( 0, 0, width, height );
  1942. }
  1943. copy( source ) {
  1944. this.dispose();
  1945. this.width = source.width;
  1946. this.height = source.height;
  1947. this.depth = source.depth;
  1948. this.scissor.copy( source.scissor );
  1949. this.scissorTest = source.scissorTest;
  1950. this.viewport.copy( source.viewport );
  1951. this.depthBuffer = source.depthBuffer;
  1952. this.stencilBuffer = source.stencilBuffer;
  1953. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1954. this.texture.length = 0;
  1955. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1956. this.texture[ i ] = source.texture[ i ].clone();
  1957. this.texture[ i ].isRenderTargetTexture = true;
  1958. }
  1959. return this;
  1960. }
  1961. }
  1962. class Quaternion {
  1963. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1964. this.isQuaternion = true;
  1965. this._x = x;
  1966. this._y = y;
  1967. this._z = z;
  1968. this._w = w;
  1969. }
  1970. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1971. // fuzz-free, array-based Quaternion SLERP operation
  1972. let x0 = src0[ srcOffset0 + 0 ],
  1973. y0 = src0[ srcOffset0 + 1 ],
  1974. z0 = src0[ srcOffset0 + 2 ],
  1975. w0 = src0[ srcOffset0 + 3 ];
  1976. const x1 = src1[ srcOffset1 + 0 ],
  1977. y1 = src1[ srcOffset1 + 1 ],
  1978. z1 = src1[ srcOffset1 + 2 ],
  1979. w1 = src1[ srcOffset1 + 3 ];
  1980. if ( t === 0 ) {
  1981. dst[ dstOffset + 0 ] = x0;
  1982. dst[ dstOffset + 1 ] = y0;
  1983. dst[ dstOffset + 2 ] = z0;
  1984. dst[ dstOffset + 3 ] = w0;
  1985. return;
  1986. }
  1987. if ( t === 1 ) {
  1988. dst[ dstOffset + 0 ] = x1;
  1989. dst[ dstOffset + 1 ] = y1;
  1990. dst[ dstOffset + 2 ] = z1;
  1991. dst[ dstOffset + 3 ] = w1;
  1992. return;
  1993. }
  1994. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1995. let s = 1 - t;
  1996. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1997. dir = ( cos >= 0 ? 1 : - 1 ),
  1998. sqrSin = 1 - cos * cos;
  1999. // Skip the Slerp for tiny steps to avoid numeric problems:
  2000. if ( sqrSin > Number.EPSILON ) {
  2001. const sin = Math.sqrt( sqrSin ),
  2002. len = Math.atan2( sin, cos * dir );
  2003. s = Math.sin( s * len ) / sin;
  2004. t = Math.sin( t * len ) / sin;
  2005. }
  2006. const tDir = t * dir;
  2007. x0 = x0 * s + x1 * tDir;
  2008. y0 = y0 * s + y1 * tDir;
  2009. z0 = z0 * s + z1 * tDir;
  2010. w0 = w0 * s + w1 * tDir;
  2011. // Normalize in case we just did a lerp:
  2012. if ( s === 1 - t ) {
  2013. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2014. x0 *= f;
  2015. y0 *= f;
  2016. z0 *= f;
  2017. w0 *= f;
  2018. }
  2019. }
  2020. dst[ dstOffset ] = x0;
  2021. dst[ dstOffset + 1 ] = y0;
  2022. dst[ dstOffset + 2 ] = z0;
  2023. dst[ dstOffset + 3 ] = w0;
  2024. }
  2025. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2026. const x0 = src0[ srcOffset0 ];
  2027. const y0 = src0[ srcOffset0 + 1 ];
  2028. const z0 = src0[ srcOffset0 + 2 ];
  2029. const w0 = src0[ srcOffset0 + 3 ];
  2030. const x1 = src1[ srcOffset1 ];
  2031. const y1 = src1[ srcOffset1 + 1 ];
  2032. const z1 = src1[ srcOffset1 + 2 ];
  2033. const w1 = src1[ srcOffset1 + 3 ];
  2034. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2035. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2036. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2037. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2038. return dst;
  2039. }
  2040. get x() {
  2041. return this._x;
  2042. }
  2043. set x( value ) {
  2044. this._x = value;
  2045. this._onChangeCallback();
  2046. }
  2047. get y() {
  2048. return this._y;
  2049. }
  2050. set y( value ) {
  2051. this._y = value;
  2052. this._onChangeCallback();
  2053. }
  2054. get z() {
  2055. return this._z;
  2056. }
  2057. set z( value ) {
  2058. this._z = value;
  2059. this._onChangeCallback();
  2060. }
  2061. get w() {
  2062. return this._w;
  2063. }
  2064. set w( value ) {
  2065. this._w = value;
  2066. this._onChangeCallback();
  2067. }
  2068. set( x, y, z, w ) {
  2069. this._x = x;
  2070. this._y = y;
  2071. this._z = z;
  2072. this._w = w;
  2073. this._onChangeCallback();
  2074. return this;
  2075. }
  2076. clone() {
  2077. return new this.constructor( this._x, this._y, this._z, this._w );
  2078. }
  2079. copy( quaternion ) {
  2080. this._x = quaternion.x;
  2081. this._y = quaternion.y;
  2082. this._z = quaternion.z;
  2083. this._w = quaternion.w;
  2084. this._onChangeCallback();
  2085. return this;
  2086. }
  2087. setFromEuler( euler, update ) {
  2088. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2089. // http://www.mathworks.com/matlabcentral/fileexchange/
  2090. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2091. // content/SpinCalc.m
  2092. const cos = Math.cos;
  2093. const sin = Math.sin;
  2094. const c1 = cos( x / 2 );
  2095. const c2 = cos( y / 2 );
  2096. const c3 = cos( z / 2 );
  2097. const s1 = sin( x / 2 );
  2098. const s2 = sin( y / 2 );
  2099. const s3 = sin( z / 2 );
  2100. switch ( order ) {
  2101. case 'XYZ':
  2102. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2103. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2104. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2105. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2106. break;
  2107. case 'YXZ':
  2108. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2109. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2110. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2111. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2112. break;
  2113. case 'ZXY':
  2114. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2115. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2116. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2117. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2118. break;
  2119. case 'ZYX':
  2120. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2121. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2122. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2123. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2124. break;
  2125. case 'YZX':
  2126. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2127. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2128. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2129. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2130. break;
  2131. case 'XZY':
  2132. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2133. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2134. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2135. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2136. break;
  2137. default:
  2138. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2139. }
  2140. if ( update !== false ) this._onChangeCallback();
  2141. return this;
  2142. }
  2143. setFromAxisAngle( axis, angle ) {
  2144. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2145. // assumes axis is normalized
  2146. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2147. this._x = axis.x * s;
  2148. this._y = axis.y * s;
  2149. this._z = axis.z * s;
  2150. this._w = Math.cos( halfAngle );
  2151. this._onChangeCallback();
  2152. return this;
  2153. }
  2154. setFromRotationMatrix( m ) {
  2155. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2156. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2157. const te = m.elements,
  2158. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2159. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2160. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2161. trace = m11 + m22 + m33;
  2162. if ( trace > 0 ) {
  2163. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2164. this._w = 0.25 / s;
  2165. this._x = ( m32 - m23 ) * s;
  2166. this._y = ( m13 - m31 ) * s;
  2167. this._z = ( m21 - m12 ) * s;
  2168. } else if ( m11 > m22 && m11 > m33 ) {
  2169. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2170. this._w = ( m32 - m23 ) / s;
  2171. this._x = 0.25 * s;
  2172. this._y = ( m12 + m21 ) / s;
  2173. this._z = ( m13 + m31 ) / s;
  2174. } else if ( m22 > m33 ) {
  2175. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2176. this._w = ( m13 - m31 ) / s;
  2177. this._x = ( m12 + m21 ) / s;
  2178. this._y = 0.25 * s;
  2179. this._z = ( m23 + m32 ) / s;
  2180. } else {
  2181. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2182. this._w = ( m21 - m12 ) / s;
  2183. this._x = ( m13 + m31 ) / s;
  2184. this._y = ( m23 + m32 ) / s;
  2185. this._z = 0.25 * s;
  2186. }
  2187. this._onChangeCallback();
  2188. return this;
  2189. }
  2190. setFromUnitVectors( vFrom, vTo ) {
  2191. // assumes direction vectors vFrom and vTo are normalized
  2192. let r = vFrom.dot( vTo ) + 1;
  2193. if ( r < Number.EPSILON ) {
  2194. // vFrom and vTo point in opposite directions
  2195. r = 0;
  2196. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2197. this._x = - vFrom.y;
  2198. this._y = vFrom.x;
  2199. this._z = 0;
  2200. this._w = r;
  2201. } else {
  2202. this._x = 0;
  2203. this._y = - vFrom.z;
  2204. this._z = vFrom.y;
  2205. this._w = r;
  2206. }
  2207. } else {
  2208. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2209. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2210. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2211. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2212. this._w = r;
  2213. }
  2214. return this.normalize();
  2215. }
  2216. angleTo( q ) {
  2217. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2218. }
  2219. rotateTowards( q, step ) {
  2220. const angle = this.angleTo( q );
  2221. if ( angle === 0 ) return this;
  2222. const t = Math.min( 1, step / angle );
  2223. this.slerp( q, t );
  2224. return this;
  2225. }
  2226. identity() {
  2227. return this.set( 0, 0, 0, 1 );
  2228. }
  2229. invert() {
  2230. // quaternion is assumed to have unit length
  2231. return this.conjugate();
  2232. }
  2233. conjugate() {
  2234. this._x *= - 1;
  2235. this._y *= - 1;
  2236. this._z *= - 1;
  2237. this._onChangeCallback();
  2238. return this;
  2239. }
  2240. dot( v ) {
  2241. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2242. }
  2243. lengthSq() {
  2244. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2245. }
  2246. length() {
  2247. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2248. }
  2249. normalize() {
  2250. let l = this.length();
  2251. if ( l === 0 ) {
  2252. this._x = 0;
  2253. this._y = 0;
  2254. this._z = 0;
  2255. this._w = 1;
  2256. } else {
  2257. l = 1 / l;
  2258. this._x = this._x * l;
  2259. this._y = this._y * l;
  2260. this._z = this._z * l;
  2261. this._w = this._w * l;
  2262. }
  2263. this._onChangeCallback();
  2264. return this;
  2265. }
  2266. multiply( q ) {
  2267. return this.multiplyQuaternions( this, q );
  2268. }
  2269. premultiply( q ) {
  2270. return this.multiplyQuaternions( q, this );
  2271. }
  2272. multiplyQuaternions( a, b ) {
  2273. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2274. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2275. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2276. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2277. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2278. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2279. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2280. this._onChangeCallback();
  2281. return this;
  2282. }
  2283. slerp( qb, t ) {
  2284. if ( t === 0 ) return this;
  2285. if ( t === 1 ) return this.copy( qb );
  2286. const x = this._x, y = this._y, z = this._z, w = this._w;
  2287. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2288. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2289. if ( cosHalfTheta < 0 ) {
  2290. this._w = - qb._w;
  2291. this._x = - qb._x;
  2292. this._y = - qb._y;
  2293. this._z = - qb._z;
  2294. cosHalfTheta = - cosHalfTheta;
  2295. } else {
  2296. this.copy( qb );
  2297. }
  2298. if ( cosHalfTheta >= 1.0 ) {
  2299. this._w = w;
  2300. this._x = x;
  2301. this._y = y;
  2302. this._z = z;
  2303. return this;
  2304. }
  2305. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2306. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2307. const s = 1 - t;
  2308. this._w = s * w + t * this._w;
  2309. this._x = s * x + t * this._x;
  2310. this._y = s * y + t * this._y;
  2311. this._z = s * z + t * this._z;
  2312. this.normalize();
  2313. this._onChangeCallback();
  2314. return this;
  2315. }
  2316. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2317. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2318. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2319. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2320. this._w = ( w * ratioA + this._w * ratioB );
  2321. this._x = ( x * ratioA + this._x * ratioB );
  2322. this._y = ( y * ratioA + this._y * ratioB );
  2323. this._z = ( z * ratioA + this._z * ratioB );
  2324. this._onChangeCallback();
  2325. return this;
  2326. }
  2327. slerpQuaternions( qa, qb, t ) {
  2328. return this.copy( qa ).slerp( qb, t );
  2329. }
  2330. random() {
  2331. // Derived from http://planning.cs.uiuc.edu/node198.html
  2332. // Note, this source uses w, x, y, z ordering,
  2333. // so we swap the order below.
  2334. const u1 = Math.random();
  2335. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2336. const sqrtu1 = Math.sqrt( u1 );
  2337. const u2 = 2 * Math.PI * Math.random();
  2338. const u3 = 2 * Math.PI * Math.random();
  2339. return this.set(
  2340. sqrt1u1 * Math.cos( u2 ),
  2341. sqrtu1 * Math.sin( u3 ),
  2342. sqrtu1 * Math.cos( u3 ),
  2343. sqrt1u1 * Math.sin( u2 ),
  2344. );
  2345. }
  2346. equals( quaternion ) {
  2347. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2348. }
  2349. fromArray( array, offset = 0 ) {
  2350. this._x = array[ offset ];
  2351. this._y = array[ offset + 1 ];
  2352. this._z = array[ offset + 2 ];
  2353. this._w = array[ offset + 3 ];
  2354. this._onChangeCallback();
  2355. return this;
  2356. }
  2357. toArray( array = [], offset = 0 ) {
  2358. array[ offset ] = this._x;
  2359. array[ offset + 1 ] = this._y;
  2360. array[ offset + 2 ] = this._z;
  2361. array[ offset + 3 ] = this._w;
  2362. return array;
  2363. }
  2364. fromBufferAttribute( attribute, index ) {
  2365. this._x = attribute.getX( index );
  2366. this._y = attribute.getY( index );
  2367. this._z = attribute.getZ( index );
  2368. this._w = attribute.getW( index );
  2369. return this;
  2370. }
  2371. toJSON() {
  2372. return this.toArray();
  2373. }
  2374. _onChange( callback ) {
  2375. this._onChangeCallback = callback;
  2376. return this;
  2377. }
  2378. _onChangeCallback() {}
  2379. *[ Symbol.iterator ]() {
  2380. yield this._x;
  2381. yield this._y;
  2382. yield this._z;
  2383. yield this._w;
  2384. }
  2385. }
  2386. class Vector3 {
  2387. constructor( x = 0, y = 0, z = 0 ) {
  2388. Vector3.prototype.isVector3 = true;
  2389. this.x = x;
  2390. this.y = y;
  2391. this.z = z;
  2392. }
  2393. set( x, y, z ) {
  2394. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2395. this.x = x;
  2396. this.y = y;
  2397. this.z = z;
  2398. return this;
  2399. }
  2400. setScalar( scalar ) {
  2401. this.x = scalar;
  2402. this.y = scalar;
  2403. this.z = scalar;
  2404. return this;
  2405. }
  2406. setX( x ) {
  2407. this.x = x;
  2408. return this;
  2409. }
  2410. setY( y ) {
  2411. this.y = y;
  2412. return this;
  2413. }
  2414. setZ( z ) {
  2415. this.z = z;
  2416. return this;
  2417. }
  2418. setComponent( index, value ) {
  2419. switch ( index ) {
  2420. case 0: this.x = value; break;
  2421. case 1: this.y = value; break;
  2422. case 2: this.z = value; break;
  2423. default: throw new Error( 'index is out of range: ' + index );
  2424. }
  2425. return this;
  2426. }
  2427. getComponent( index ) {
  2428. switch ( index ) {
  2429. case 0: return this.x;
  2430. case 1: return this.y;
  2431. case 2: return this.z;
  2432. default: throw new Error( 'index is out of range: ' + index );
  2433. }
  2434. }
  2435. clone() {
  2436. return new this.constructor( this.x, this.y, this.z );
  2437. }
  2438. copy( v ) {
  2439. this.x = v.x;
  2440. this.y = v.y;
  2441. this.z = v.z;
  2442. return this;
  2443. }
  2444. add( v ) {
  2445. this.x += v.x;
  2446. this.y += v.y;
  2447. this.z += v.z;
  2448. return this;
  2449. }
  2450. addScalar( s ) {
  2451. this.x += s;
  2452. this.y += s;
  2453. this.z += s;
  2454. return this;
  2455. }
  2456. addVectors( a, b ) {
  2457. this.x = a.x + b.x;
  2458. this.y = a.y + b.y;
  2459. this.z = a.z + b.z;
  2460. return this;
  2461. }
  2462. addScaledVector( v, s ) {
  2463. this.x += v.x * s;
  2464. this.y += v.y * s;
  2465. this.z += v.z * s;
  2466. return this;
  2467. }
  2468. sub( v ) {
  2469. this.x -= v.x;
  2470. this.y -= v.y;
  2471. this.z -= v.z;
  2472. return this;
  2473. }
  2474. subScalar( s ) {
  2475. this.x -= s;
  2476. this.y -= s;
  2477. this.z -= s;
  2478. return this;
  2479. }
  2480. subVectors( a, b ) {
  2481. this.x = a.x - b.x;
  2482. this.y = a.y - b.y;
  2483. this.z = a.z - b.z;
  2484. return this;
  2485. }
  2486. multiply( v ) {
  2487. this.x *= v.x;
  2488. this.y *= v.y;
  2489. this.z *= v.z;
  2490. return this;
  2491. }
  2492. multiplyScalar( scalar ) {
  2493. this.x *= scalar;
  2494. this.y *= scalar;
  2495. this.z *= scalar;
  2496. return this;
  2497. }
  2498. multiplyVectors( a, b ) {
  2499. this.x = a.x * b.x;
  2500. this.y = a.y * b.y;
  2501. this.z = a.z * b.z;
  2502. return this;
  2503. }
  2504. applyEuler( euler ) {
  2505. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2506. }
  2507. applyAxisAngle( axis, angle ) {
  2508. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2509. }
  2510. applyMatrix3( m ) {
  2511. const x = this.x, y = this.y, z = this.z;
  2512. const e = m.elements;
  2513. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2514. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2515. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2516. return this;
  2517. }
  2518. applyNormalMatrix( m ) {
  2519. return this.applyMatrix3( m ).normalize();
  2520. }
  2521. applyMatrix4( m ) {
  2522. const x = this.x, y = this.y, z = this.z;
  2523. const e = m.elements;
  2524. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2525. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2526. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2527. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2528. return this;
  2529. }
  2530. applyQuaternion( q ) {
  2531. const x = this.x, y = this.y, z = this.z;
  2532. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2533. // calculate quat * vector
  2534. const ix = qw * x + qy * z - qz * y;
  2535. const iy = qw * y + qz * x - qx * z;
  2536. const iz = qw * z + qx * y - qy * x;
  2537. const iw = - qx * x - qy * y - qz * z;
  2538. // calculate result * inverse quat
  2539. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2540. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2541. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2542. return this;
  2543. }
  2544. project( camera ) {
  2545. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2546. }
  2547. unproject( camera ) {
  2548. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2549. }
  2550. transformDirection( m ) {
  2551. // input: THREE.Matrix4 affine matrix
  2552. // vector interpreted as a direction
  2553. const x = this.x, y = this.y, z = this.z;
  2554. const e = m.elements;
  2555. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2556. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2557. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2558. return this.normalize();
  2559. }
  2560. divide( v ) {
  2561. this.x /= v.x;
  2562. this.y /= v.y;
  2563. this.z /= v.z;
  2564. return this;
  2565. }
  2566. divideScalar( scalar ) {
  2567. return this.multiplyScalar( 1 / scalar );
  2568. }
  2569. min( v ) {
  2570. this.x = Math.min( this.x, v.x );
  2571. this.y = Math.min( this.y, v.y );
  2572. this.z = Math.min( this.z, v.z );
  2573. return this;
  2574. }
  2575. max( v ) {
  2576. this.x = Math.max( this.x, v.x );
  2577. this.y = Math.max( this.y, v.y );
  2578. this.z = Math.max( this.z, v.z );
  2579. return this;
  2580. }
  2581. clamp( min, max ) {
  2582. // assumes min < max, componentwise
  2583. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2584. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2585. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2586. return this;
  2587. }
  2588. clampScalar( minVal, maxVal ) {
  2589. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2590. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2591. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2592. return this;
  2593. }
  2594. clampLength( min, max ) {
  2595. const length = this.length();
  2596. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2597. }
  2598. floor() {
  2599. this.x = Math.floor( this.x );
  2600. this.y = Math.floor( this.y );
  2601. this.z = Math.floor( this.z );
  2602. return this;
  2603. }
  2604. ceil() {
  2605. this.x = Math.ceil( this.x );
  2606. this.y = Math.ceil( this.y );
  2607. this.z = Math.ceil( this.z );
  2608. return this;
  2609. }
  2610. round() {
  2611. this.x = Math.round( this.x );
  2612. this.y = Math.round( this.y );
  2613. this.z = Math.round( this.z );
  2614. return this;
  2615. }
  2616. roundToZero() {
  2617. this.x = Math.trunc( this.x );
  2618. this.y = Math.trunc( this.y );
  2619. this.z = Math.trunc( this.z );
  2620. return this;
  2621. }
  2622. negate() {
  2623. this.x = - this.x;
  2624. this.y = - this.y;
  2625. this.z = - this.z;
  2626. return this;
  2627. }
  2628. dot( v ) {
  2629. return this.x * v.x + this.y * v.y + this.z * v.z;
  2630. }
  2631. // TODO lengthSquared?
  2632. lengthSq() {
  2633. return this.x * this.x + this.y * this.y + this.z * this.z;
  2634. }
  2635. length() {
  2636. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2637. }
  2638. manhattanLength() {
  2639. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2640. }
  2641. normalize() {
  2642. return this.divideScalar( this.length() || 1 );
  2643. }
  2644. setLength( length ) {
  2645. return this.normalize().multiplyScalar( length );
  2646. }
  2647. lerp( v, alpha ) {
  2648. this.x += ( v.x - this.x ) * alpha;
  2649. this.y += ( v.y - this.y ) * alpha;
  2650. this.z += ( v.z - this.z ) * alpha;
  2651. return this;
  2652. }
  2653. lerpVectors( v1, v2, alpha ) {
  2654. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2655. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2656. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2657. return this;
  2658. }
  2659. cross( v ) {
  2660. return this.crossVectors( this, v );
  2661. }
  2662. crossVectors( a, b ) {
  2663. const ax = a.x, ay = a.y, az = a.z;
  2664. const bx = b.x, by = b.y, bz = b.z;
  2665. this.x = ay * bz - az * by;
  2666. this.y = az * bx - ax * bz;
  2667. this.z = ax * by - ay * bx;
  2668. return this;
  2669. }
  2670. projectOnVector( v ) {
  2671. const denominator = v.lengthSq();
  2672. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2673. const scalar = v.dot( this ) / denominator;
  2674. return this.copy( v ).multiplyScalar( scalar );
  2675. }
  2676. projectOnPlane( planeNormal ) {
  2677. _vector$b.copy( this ).projectOnVector( planeNormal );
  2678. return this.sub( _vector$b );
  2679. }
  2680. reflect( normal ) {
  2681. // reflect incident vector off plane orthogonal to normal
  2682. // normal is assumed to have unit length
  2683. return this.sub( _vector$b.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2684. }
  2685. angleTo( v ) {
  2686. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2687. if ( denominator === 0 ) return Math.PI / 2;
  2688. const theta = this.dot( v ) / denominator;
  2689. // clamp, to handle numerical problems
  2690. return Math.acos( clamp( theta, - 1, 1 ) );
  2691. }
  2692. distanceTo( v ) {
  2693. return Math.sqrt( this.distanceToSquared( v ) );
  2694. }
  2695. distanceToSquared( v ) {
  2696. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2697. return dx * dx + dy * dy + dz * dz;
  2698. }
  2699. manhattanDistanceTo( v ) {
  2700. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2701. }
  2702. setFromSpherical( s ) {
  2703. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2704. }
  2705. setFromSphericalCoords( radius, phi, theta ) {
  2706. const sinPhiRadius = Math.sin( phi ) * radius;
  2707. this.x = sinPhiRadius * Math.sin( theta );
  2708. this.y = Math.cos( phi ) * radius;
  2709. this.z = sinPhiRadius * Math.cos( theta );
  2710. return this;
  2711. }
  2712. setFromCylindrical( c ) {
  2713. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2714. }
  2715. setFromCylindricalCoords( radius, theta, y ) {
  2716. this.x = radius * Math.sin( theta );
  2717. this.y = y;
  2718. this.z = radius * Math.cos( theta );
  2719. return this;
  2720. }
  2721. setFromMatrixPosition( m ) {
  2722. const e = m.elements;
  2723. this.x = e[ 12 ];
  2724. this.y = e[ 13 ];
  2725. this.z = e[ 14 ];
  2726. return this;
  2727. }
  2728. setFromMatrixScale( m ) {
  2729. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2730. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2731. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2732. this.x = sx;
  2733. this.y = sy;
  2734. this.z = sz;
  2735. return this;
  2736. }
  2737. setFromMatrixColumn( m, index ) {
  2738. return this.fromArray( m.elements, index * 4 );
  2739. }
  2740. setFromMatrix3Column( m, index ) {
  2741. return this.fromArray( m.elements, index * 3 );
  2742. }
  2743. setFromEuler( e ) {
  2744. this.x = e._x;
  2745. this.y = e._y;
  2746. this.z = e._z;
  2747. return this;
  2748. }
  2749. setFromColor( c ) {
  2750. this.x = c.r;
  2751. this.y = c.g;
  2752. this.z = c.b;
  2753. return this;
  2754. }
  2755. equals( v ) {
  2756. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2757. }
  2758. fromArray( array, offset = 0 ) {
  2759. this.x = array[ offset ];
  2760. this.y = array[ offset + 1 ];
  2761. this.z = array[ offset + 2 ];
  2762. return this;
  2763. }
  2764. toArray( array = [], offset = 0 ) {
  2765. array[ offset ] = this.x;
  2766. array[ offset + 1 ] = this.y;
  2767. array[ offset + 2 ] = this.z;
  2768. return array;
  2769. }
  2770. fromBufferAttribute( attribute, index ) {
  2771. this.x = attribute.getX( index );
  2772. this.y = attribute.getY( index );
  2773. this.z = attribute.getZ( index );
  2774. return this;
  2775. }
  2776. random() {
  2777. this.x = Math.random();
  2778. this.y = Math.random();
  2779. this.z = Math.random();
  2780. return this;
  2781. }
  2782. randomDirection() {
  2783. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2784. const u = ( Math.random() - 0.5 ) * 2;
  2785. const t = Math.random() * Math.PI * 2;
  2786. const f = Math.sqrt( 1 - u ** 2 );
  2787. this.x = f * Math.cos( t );
  2788. this.y = f * Math.sin( t );
  2789. this.z = u;
  2790. return this;
  2791. }
  2792. *[ Symbol.iterator ]() {
  2793. yield this.x;
  2794. yield this.y;
  2795. yield this.z;
  2796. }
  2797. }
  2798. const _vector$b = /*@__PURE__*/ new Vector3();
  2799. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2800. class Box3 {
  2801. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2802. this.isBox3 = true;
  2803. this.min = min;
  2804. this.max = max;
  2805. }
  2806. set( min, max ) {
  2807. this.min.copy( min );
  2808. this.max.copy( max );
  2809. return this;
  2810. }
  2811. setFromArray( array ) {
  2812. this.makeEmpty();
  2813. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2814. this.expandByPoint( _vector$a.fromArray( array, i ) );
  2815. }
  2816. return this;
  2817. }
  2818. setFromBufferAttribute( attribute ) {
  2819. this.makeEmpty();
  2820. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2821. this.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );
  2822. }
  2823. return this;
  2824. }
  2825. setFromPoints( points ) {
  2826. this.makeEmpty();
  2827. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2828. this.expandByPoint( points[ i ] );
  2829. }
  2830. return this;
  2831. }
  2832. setFromCenterAndSize( center, size ) {
  2833. const halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );
  2834. this.min.copy( center ).sub( halfSize );
  2835. this.max.copy( center ).add( halfSize );
  2836. return this;
  2837. }
  2838. setFromObject( object, precise = false ) {
  2839. this.makeEmpty();
  2840. return this.expandByObject( object, precise );
  2841. }
  2842. clone() {
  2843. return new this.constructor().copy( this );
  2844. }
  2845. copy( box ) {
  2846. this.min.copy( box.min );
  2847. this.max.copy( box.max );
  2848. return this;
  2849. }
  2850. makeEmpty() {
  2851. this.min.x = this.min.y = this.min.z = + Infinity;
  2852. this.max.x = this.max.y = this.max.z = - Infinity;
  2853. return this;
  2854. }
  2855. isEmpty() {
  2856. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2857. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2858. }
  2859. getCenter( target ) {
  2860. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2861. }
  2862. getSize( target ) {
  2863. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2864. }
  2865. expandByPoint( point ) {
  2866. this.min.min( point );
  2867. this.max.max( point );
  2868. return this;
  2869. }
  2870. expandByVector( vector ) {
  2871. this.min.sub( vector );
  2872. this.max.add( vector );
  2873. return this;
  2874. }
  2875. expandByScalar( scalar ) {
  2876. this.min.addScalar( - scalar );
  2877. this.max.addScalar( scalar );
  2878. return this;
  2879. }
  2880. expandByObject( object, precise = false ) {
  2881. // Computes the world-axis-aligned bounding box of an object (including its children),
  2882. // accounting for both the object's, and children's, world transforms
  2883. object.updateWorldMatrix( false, false );
  2884. if ( object.boundingBox !== undefined ) {
  2885. if ( object.boundingBox === null ) {
  2886. object.computeBoundingBox();
  2887. }
  2888. _box$3.copy( object.boundingBox );
  2889. _box$3.applyMatrix4( object.matrixWorld );
  2890. this.union( _box$3 );
  2891. } else {
  2892. const geometry = object.geometry;
  2893. if ( geometry !== undefined ) {
  2894. if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {
  2895. const position = geometry.attributes.position;
  2896. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2897. _vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2898. this.expandByPoint( _vector$a );
  2899. }
  2900. } else {
  2901. if ( geometry.boundingBox === null ) {
  2902. geometry.computeBoundingBox();
  2903. }
  2904. _box$3.copy( geometry.boundingBox );
  2905. _box$3.applyMatrix4( object.matrixWorld );
  2906. this.union( _box$3 );
  2907. }
  2908. }
  2909. }
  2910. const children = object.children;
  2911. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2912. this.expandByObject( children[ i ], precise );
  2913. }
  2914. return this;
  2915. }
  2916. containsPoint( point ) {
  2917. return point.x < this.min.x || point.x > this.max.x ||
  2918. point.y < this.min.y || point.y > this.max.y ||
  2919. point.z < this.min.z || point.z > this.max.z ? false : true;
  2920. }
  2921. containsBox( box ) {
  2922. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2923. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2924. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2925. }
  2926. getParameter( point, target ) {
  2927. // This can potentially have a divide by zero if the box
  2928. // has a size dimension of 0.
  2929. return target.set(
  2930. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2931. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2932. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2933. );
  2934. }
  2935. intersectsBox( box ) {
  2936. // using 6 splitting planes to rule out intersections.
  2937. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2938. box.max.y < this.min.y || box.min.y > this.max.y ||
  2939. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2940. }
  2941. intersectsSphere( sphere ) {
  2942. // Find the point on the AABB closest to the sphere center.
  2943. this.clampPoint( sphere.center, _vector$a );
  2944. // If that point is inside the sphere, the AABB and sphere intersect.
  2945. return _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2946. }
  2947. intersectsPlane( plane ) {
  2948. // We compute the minimum and maximum dot product values. If those values
  2949. // are on the same side (back or front) of the plane, then there is no intersection.
  2950. let min, max;
  2951. if ( plane.normal.x > 0 ) {
  2952. min = plane.normal.x * this.min.x;
  2953. max = plane.normal.x * this.max.x;
  2954. } else {
  2955. min = plane.normal.x * this.max.x;
  2956. max = plane.normal.x * this.min.x;
  2957. }
  2958. if ( plane.normal.y > 0 ) {
  2959. min += plane.normal.y * this.min.y;
  2960. max += plane.normal.y * this.max.y;
  2961. } else {
  2962. min += plane.normal.y * this.max.y;
  2963. max += plane.normal.y * this.min.y;
  2964. }
  2965. if ( plane.normal.z > 0 ) {
  2966. min += plane.normal.z * this.min.z;
  2967. max += plane.normal.z * this.max.z;
  2968. } else {
  2969. min += plane.normal.z * this.max.z;
  2970. max += plane.normal.z * this.min.z;
  2971. }
  2972. return ( min <= - plane.constant && max >= - plane.constant );
  2973. }
  2974. intersectsTriangle( triangle ) {
  2975. if ( this.isEmpty() ) {
  2976. return false;
  2977. }
  2978. // compute box center and extents
  2979. this.getCenter( _center );
  2980. _extents.subVectors( this.max, _center );
  2981. // translate triangle to aabb origin
  2982. _v0$2.subVectors( triangle.a, _center );
  2983. _v1$7.subVectors( triangle.b, _center );
  2984. _v2$4.subVectors( triangle.c, _center );
  2985. // compute edge vectors for triangle
  2986. _f0.subVectors( _v1$7, _v0$2 );
  2987. _f1.subVectors( _v2$4, _v1$7 );
  2988. _f2.subVectors( _v0$2, _v2$4 );
  2989. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2990. // 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
  2991. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2992. let axes = [
  2993. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2994. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2995. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2996. ];
  2997. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2998. return false;
  2999. }
  3000. // test 3 face normals from the aabb
  3001. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3002. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3003. return false;
  3004. }
  3005. // finally testing the face normal of the triangle
  3006. // use already existing triangle edge vectors here
  3007. _triangleNormal.crossVectors( _f0, _f1 );
  3008. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3009. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3010. }
  3011. clampPoint( point, target ) {
  3012. return target.copy( point ).clamp( this.min, this.max );
  3013. }
  3014. distanceToPoint( point ) {
  3015. return this.clampPoint( point, _vector$a ).distanceTo( point );
  3016. }
  3017. getBoundingSphere( target ) {
  3018. if ( this.isEmpty() ) {
  3019. target.makeEmpty();
  3020. } else {
  3021. this.getCenter( target.center );
  3022. target.radius = this.getSize( _vector$a ).length() * 0.5;
  3023. }
  3024. return target;
  3025. }
  3026. intersect( box ) {
  3027. this.min.max( box.min );
  3028. this.max.min( box.max );
  3029. // 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.
  3030. if ( this.isEmpty() ) this.makeEmpty();
  3031. return this;
  3032. }
  3033. union( box ) {
  3034. this.min.min( box.min );
  3035. this.max.max( box.max );
  3036. return this;
  3037. }
  3038. applyMatrix4( matrix ) {
  3039. // transform of empty box is an empty box.
  3040. if ( this.isEmpty() ) return this;
  3041. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3042. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3043. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3044. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3045. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3046. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3047. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3048. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3049. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3050. this.setFromPoints( _points );
  3051. return this;
  3052. }
  3053. translate( offset ) {
  3054. this.min.add( offset );
  3055. this.max.add( offset );
  3056. return this;
  3057. }
  3058. equals( box ) {
  3059. return box.min.equals( this.min ) && box.max.equals( this.max );
  3060. }
  3061. }
  3062. const _points = [
  3063. /*@__PURE__*/ new Vector3(),
  3064. /*@__PURE__*/ new Vector3(),
  3065. /*@__PURE__*/ new Vector3(),
  3066. /*@__PURE__*/ new Vector3(),
  3067. /*@__PURE__*/ new Vector3(),
  3068. /*@__PURE__*/ new Vector3(),
  3069. /*@__PURE__*/ new Vector3(),
  3070. /*@__PURE__*/ new Vector3()
  3071. ];
  3072. const _vector$a = /*@__PURE__*/ new Vector3();
  3073. const _box$3 = /*@__PURE__*/ new Box3();
  3074. // triangle centered vertices
  3075. const _v0$2 = /*@__PURE__*/ new Vector3();
  3076. const _v1$7 = /*@__PURE__*/ new Vector3();
  3077. const _v2$4 = /*@__PURE__*/ new Vector3();
  3078. // triangle edge vectors
  3079. const _f0 = /*@__PURE__*/ new Vector3();
  3080. const _f1 = /*@__PURE__*/ new Vector3();
  3081. const _f2 = /*@__PURE__*/ new Vector3();
  3082. const _center = /*@__PURE__*/ new Vector3();
  3083. const _extents = /*@__PURE__*/ new Vector3();
  3084. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3085. const _testAxis = /*@__PURE__*/ new Vector3();
  3086. function satForAxes( axes, v0, v1, v2, extents ) {
  3087. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3088. _testAxis.fromArray( axes, i );
  3089. // project the aabb onto the separating axis
  3090. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3091. // project all 3 vertices of the triangle onto the separating axis
  3092. const p0 = v0.dot( _testAxis );
  3093. const p1 = v1.dot( _testAxis );
  3094. const p2 = v2.dot( _testAxis );
  3095. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3096. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3097. // points of the projected triangle are outside the projected half-length of the aabb
  3098. // the axis is separating and we can exit
  3099. return false;
  3100. }
  3101. }
  3102. return true;
  3103. }
  3104. const _box$2 = /*@__PURE__*/ new Box3();
  3105. const _v1$6 = /*@__PURE__*/ new Vector3();
  3106. const _v2$3 = /*@__PURE__*/ new Vector3();
  3107. class Sphere {
  3108. constructor( center = new Vector3(), radius = - 1 ) {
  3109. this.center = center;
  3110. this.radius = radius;
  3111. }
  3112. set( center, radius ) {
  3113. this.center.copy( center );
  3114. this.radius = radius;
  3115. return this;
  3116. }
  3117. setFromPoints( points, optionalCenter ) {
  3118. const center = this.center;
  3119. if ( optionalCenter !== undefined ) {
  3120. center.copy( optionalCenter );
  3121. } else {
  3122. _box$2.setFromPoints( points ).getCenter( center );
  3123. }
  3124. let maxRadiusSq = 0;
  3125. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3126. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3127. }
  3128. this.radius = Math.sqrt( maxRadiusSq );
  3129. return this;
  3130. }
  3131. copy( sphere ) {
  3132. this.center.copy( sphere.center );
  3133. this.radius = sphere.radius;
  3134. return this;
  3135. }
  3136. isEmpty() {
  3137. return ( this.radius < 0 );
  3138. }
  3139. makeEmpty() {
  3140. this.center.set( 0, 0, 0 );
  3141. this.radius = - 1;
  3142. return this;
  3143. }
  3144. containsPoint( point ) {
  3145. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3146. }
  3147. distanceToPoint( point ) {
  3148. return ( point.distanceTo( this.center ) - this.radius );
  3149. }
  3150. intersectsSphere( sphere ) {
  3151. const radiusSum = this.radius + sphere.radius;
  3152. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3153. }
  3154. intersectsBox( box ) {
  3155. return box.intersectsSphere( this );
  3156. }
  3157. intersectsPlane( plane ) {
  3158. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3159. }
  3160. clampPoint( point, target ) {
  3161. const deltaLengthSq = this.center.distanceToSquared( point );
  3162. target.copy( point );
  3163. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3164. target.sub( this.center ).normalize();
  3165. target.multiplyScalar( this.radius ).add( this.center );
  3166. }
  3167. return target;
  3168. }
  3169. getBoundingBox( target ) {
  3170. if ( this.isEmpty() ) {
  3171. // Empty sphere produces empty bounding box
  3172. target.makeEmpty();
  3173. return target;
  3174. }
  3175. target.set( this.center, this.center );
  3176. target.expandByScalar( this.radius );
  3177. return target;
  3178. }
  3179. applyMatrix4( matrix ) {
  3180. this.center.applyMatrix4( matrix );
  3181. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3182. return this;
  3183. }
  3184. translate( offset ) {
  3185. this.center.add( offset );
  3186. return this;
  3187. }
  3188. expandByPoint( point ) {
  3189. if ( this.isEmpty() ) {
  3190. this.center.copy( point );
  3191. this.radius = 0;
  3192. return this;
  3193. }
  3194. _v1$6.subVectors( point, this.center );
  3195. const lengthSq = _v1$6.lengthSq();
  3196. if ( lengthSq > ( this.radius * this.radius ) ) {
  3197. // calculate the minimal sphere
  3198. const length = Math.sqrt( lengthSq );
  3199. const delta = ( length - this.radius ) * 0.5;
  3200. this.center.addScaledVector( _v1$6, delta / length );
  3201. this.radius += delta;
  3202. }
  3203. return this;
  3204. }
  3205. union( sphere ) {
  3206. if ( sphere.isEmpty() ) {
  3207. return this;
  3208. }
  3209. if ( this.isEmpty() ) {
  3210. this.copy( sphere );
  3211. return this;
  3212. }
  3213. if ( this.center.equals( sphere.center ) === true ) {
  3214. this.radius = Math.max( this.radius, sphere.radius );
  3215. } else {
  3216. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3217. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3218. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3219. }
  3220. return this;
  3221. }
  3222. equals( sphere ) {
  3223. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3224. }
  3225. clone() {
  3226. return new this.constructor().copy( this );
  3227. }
  3228. }
  3229. const _vector$9 = /*@__PURE__*/ new Vector3();
  3230. const _segCenter = /*@__PURE__*/ new Vector3();
  3231. const _segDir = /*@__PURE__*/ new Vector3();
  3232. const _diff = /*@__PURE__*/ new Vector3();
  3233. const _edge1 = /*@__PURE__*/ new Vector3();
  3234. const _edge2 = /*@__PURE__*/ new Vector3();
  3235. const _normal$1 = /*@__PURE__*/ new Vector3();
  3236. class Ray {
  3237. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3238. this.origin = origin;
  3239. this.direction = direction;
  3240. }
  3241. set( origin, direction ) {
  3242. this.origin.copy( origin );
  3243. this.direction.copy( direction );
  3244. return this;
  3245. }
  3246. copy( ray ) {
  3247. this.origin.copy( ray.origin );
  3248. this.direction.copy( ray.direction );
  3249. return this;
  3250. }
  3251. at( t, target ) {
  3252. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3253. }
  3254. lookAt( v ) {
  3255. this.direction.copy( v ).sub( this.origin ).normalize();
  3256. return this;
  3257. }
  3258. recast( t ) {
  3259. this.origin.copy( this.at( t, _vector$9 ) );
  3260. return this;
  3261. }
  3262. closestPointToPoint( point, target ) {
  3263. target.subVectors( point, this.origin );
  3264. const directionDistance = target.dot( this.direction );
  3265. if ( directionDistance < 0 ) {
  3266. return target.copy( this.origin );
  3267. }
  3268. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3269. }
  3270. distanceToPoint( point ) {
  3271. return Math.sqrt( this.distanceSqToPoint( point ) );
  3272. }
  3273. distanceSqToPoint( point ) {
  3274. const directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );
  3275. // point behind the ray
  3276. if ( directionDistance < 0 ) {
  3277. return this.origin.distanceToSquared( point );
  3278. }
  3279. _vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3280. return _vector$9.distanceToSquared( point );
  3281. }
  3282. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3283. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3284. // It returns the min distance between the ray and the segment
  3285. // defined by v0 and v1
  3286. // It can also set two optional targets :
  3287. // - The closest point on the ray
  3288. // - The closest point on the segment
  3289. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3290. _segDir.copy( v1 ).sub( v0 ).normalize();
  3291. _diff.copy( this.origin ).sub( _segCenter );
  3292. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3293. const a01 = - this.direction.dot( _segDir );
  3294. const b0 = _diff.dot( this.direction );
  3295. const b1 = - _diff.dot( _segDir );
  3296. const c = _diff.lengthSq();
  3297. const det = Math.abs( 1 - a01 * a01 );
  3298. let s0, s1, sqrDist, extDet;
  3299. if ( det > 0 ) {
  3300. // The ray and segment are not parallel.
  3301. s0 = a01 * b1 - b0;
  3302. s1 = a01 * b0 - b1;
  3303. extDet = segExtent * det;
  3304. if ( s0 >= 0 ) {
  3305. if ( s1 >= - extDet ) {
  3306. if ( s1 <= extDet ) {
  3307. // region 0
  3308. // Minimum at interior points of ray and segment.
  3309. const invDet = 1 / det;
  3310. s0 *= invDet;
  3311. s1 *= invDet;
  3312. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3313. } else {
  3314. // region 1
  3315. s1 = segExtent;
  3316. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3317. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3318. }
  3319. } else {
  3320. // region 5
  3321. s1 = - segExtent;
  3322. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3323. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3324. }
  3325. } else {
  3326. if ( s1 <= - extDet ) {
  3327. // region 4
  3328. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3329. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3330. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3331. } else if ( s1 <= extDet ) {
  3332. // region 3
  3333. s0 = 0;
  3334. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3335. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3336. } else {
  3337. // region 2
  3338. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3339. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3340. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3341. }
  3342. }
  3343. } else {
  3344. // Ray and segment are parallel.
  3345. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3346. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3347. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3348. }
  3349. if ( optionalPointOnRay ) {
  3350. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3351. }
  3352. if ( optionalPointOnSegment ) {
  3353. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3354. }
  3355. return sqrDist;
  3356. }
  3357. intersectSphere( sphere, target ) {
  3358. _vector$9.subVectors( sphere.center, this.origin );
  3359. const tca = _vector$9.dot( this.direction );
  3360. const d2 = _vector$9.dot( _vector$9 ) - tca * tca;
  3361. const radius2 = sphere.radius * sphere.radius;
  3362. if ( d2 > radius2 ) return null;
  3363. const thc = Math.sqrt( radius2 - d2 );
  3364. // t0 = first intersect point - entrance on front of sphere
  3365. const t0 = tca - thc;
  3366. // t1 = second intersect point - exit point on back of sphere
  3367. const t1 = tca + thc;
  3368. // test to see if t1 is behind the ray - if so, return null
  3369. if ( t1 < 0 ) return null;
  3370. // test to see if t0 is behind the ray:
  3371. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3372. // in order to always return an intersect point that is in front of the ray.
  3373. if ( t0 < 0 ) return this.at( t1, target );
  3374. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3375. return this.at( t0, target );
  3376. }
  3377. intersectsSphere( sphere ) {
  3378. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3379. }
  3380. distanceToPlane( plane ) {
  3381. const denominator = plane.normal.dot( this.direction );
  3382. if ( denominator === 0 ) {
  3383. // line is coplanar, return origin
  3384. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3385. return 0;
  3386. }
  3387. // Null is preferable to undefined since undefined means.... it is undefined
  3388. return null;
  3389. }
  3390. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3391. // Return if the ray never intersects the plane
  3392. return t >= 0 ? t : null;
  3393. }
  3394. intersectPlane( plane, target ) {
  3395. const t = this.distanceToPlane( plane );
  3396. if ( t === null ) {
  3397. return null;
  3398. }
  3399. return this.at( t, target );
  3400. }
  3401. intersectsPlane( plane ) {
  3402. // check if the ray lies on the plane first
  3403. const distToPoint = plane.distanceToPoint( this.origin );
  3404. if ( distToPoint === 0 ) {
  3405. return true;
  3406. }
  3407. const denominator = plane.normal.dot( this.direction );
  3408. if ( denominator * distToPoint < 0 ) {
  3409. return true;
  3410. }
  3411. // ray origin is behind the plane (and is pointing behind it)
  3412. return false;
  3413. }
  3414. intersectBox( box, target ) {
  3415. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3416. const invdirx = 1 / this.direction.x,
  3417. invdiry = 1 / this.direction.y,
  3418. invdirz = 1 / this.direction.z;
  3419. const origin = this.origin;
  3420. if ( invdirx >= 0 ) {
  3421. tmin = ( box.min.x - origin.x ) * invdirx;
  3422. tmax = ( box.max.x - origin.x ) * invdirx;
  3423. } else {
  3424. tmin = ( box.max.x - origin.x ) * invdirx;
  3425. tmax = ( box.min.x - origin.x ) * invdirx;
  3426. }
  3427. if ( invdiry >= 0 ) {
  3428. tymin = ( box.min.y - origin.y ) * invdiry;
  3429. tymax = ( box.max.y - origin.y ) * invdiry;
  3430. } else {
  3431. tymin = ( box.max.y - origin.y ) * invdiry;
  3432. tymax = ( box.min.y - origin.y ) * invdiry;
  3433. }
  3434. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3435. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3436. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3437. if ( invdirz >= 0 ) {
  3438. tzmin = ( box.min.z - origin.z ) * invdirz;
  3439. tzmax = ( box.max.z - origin.z ) * invdirz;
  3440. } else {
  3441. tzmin = ( box.max.z - origin.z ) * invdirz;
  3442. tzmax = ( box.min.z - origin.z ) * invdirz;
  3443. }
  3444. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3445. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3446. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3447. //return point closest to the ray (positive side)
  3448. if ( tmax < 0 ) return null;
  3449. return this.at( tmin >= 0 ? tmin : tmax, target );
  3450. }
  3451. intersectsBox( box ) {
  3452. return this.intersectBox( box, _vector$9 ) !== null;
  3453. }
  3454. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3455. // Compute the offset origin, edges, and normal.
  3456. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3457. _edge1.subVectors( b, a );
  3458. _edge2.subVectors( c, a );
  3459. _normal$1.crossVectors( _edge1, _edge2 );
  3460. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3461. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3462. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3463. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3464. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3465. let DdN = this.direction.dot( _normal$1 );
  3466. let sign;
  3467. if ( DdN > 0 ) {
  3468. if ( backfaceCulling ) return null;
  3469. sign = 1;
  3470. } else if ( DdN < 0 ) {
  3471. sign = - 1;
  3472. DdN = - DdN;
  3473. } else {
  3474. return null;
  3475. }
  3476. _diff.subVectors( this.origin, a );
  3477. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3478. // b1 < 0, no intersection
  3479. if ( DdQxE2 < 0 ) {
  3480. return null;
  3481. }
  3482. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3483. // b2 < 0, no intersection
  3484. if ( DdE1xQ < 0 ) {
  3485. return null;
  3486. }
  3487. // b1+b2 > 1, no intersection
  3488. if ( DdQxE2 + DdE1xQ > DdN ) {
  3489. return null;
  3490. }
  3491. // Line intersects triangle, check if ray does.
  3492. const QdN = - sign * _diff.dot( _normal$1 );
  3493. // t < 0, no intersection
  3494. if ( QdN < 0 ) {
  3495. return null;
  3496. }
  3497. // Ray intersects triangle.
  3498. return this.at( QdN / DdN, target );
  3499. }
  3500. applyMatrix4( matrix4 ) {
  3501. this.origin.applyMatrix4( matrix4 );
  3502. this.direction.transformDirection( matrix4 );
  3503. return this;
  3504. }
  3505. equals( ray ) {
  3506. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3507. }
  3508. clone() {
  3509. return new this.constructor().copy( this );
  3510. }
  3511. }
  3512. class Matrix4 {
  3513. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3514. Matrix4.prototype.isMatrix4 = true;
  3515. this.elements = [
  3516. 1, 0, 0, 0,
  3517. 0, 1, 0, 0,
  3518. 0, 0, 1, 0,
  3519. 0, 0, 0, 1
  3520. ];
  3521. if ( n11 !== undefined ) {
  3522. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3523. }
  3524. }
  3525. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3526. const te = this.elements;
  3527. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3528. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3529. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3530. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3531. return this;
  3532. }
  3533. identity() {
  3534. this.set(
  3535. 1, 0, 0, 0,
  3536. 0, 1, 0, 0,
  3537. 0, 0, 1, 0,
  3538. 0, 0, 0, 1
  3539. );
  3540. return this;
  3541. }
  3542. clone() {
  3543. return new Matrix4().fromArray( this.elements );
  3544. }
  3545. copy( m ) {
  3546. const te = this.elements;
  3547. const me = m.elements;
  3548. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3549. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3550. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3551. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3552. return this;
  3553. }
  3554. copyPosition( m ) {
  3555. const te = this.elements, me = m.elements;
  3556. te[ 12 ] = me[ 12 ];
  3557. te[ 13 ] = me[ 13 ];
  3558. te[ 14 ] = me[ 14 ];
  3559. return this;
  3560. }
  3561. setFromMatrix3( m ) {
  3562. const me = m.elements;
  3563. this.set(
  3564. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3565. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3566. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3567. 0, 0, 0, 1
  3568. );
  3569. return this;
  3570. }
  3571. extractBasis( xAxis, yAxis, zAxis ) {
  3572. xAxis.setFromMatrixColumn( this, 0 );
  3573. yAxis.setFromMatrixColumn( this, 1 );
  3574. zAxis.setFromMatrixColumn( this, 2 );
  3575. return this;
  3576. }
  3577. makeBasis( xAxis, yAxis, zAxis ) {
  3578. this.set(
  3579. xAxis.x, yAxis.x, zAxis.x, 0,
  3580. xAxis.y, yAxis.y, zAxis.y, 0,
  3581. xAxis.z, yAxis.z, zAxis.z, 0,
  3582. 0, 0, 0, 1
  3583. );
  3584. return this;
  3585. }
  3586. extractRotation( m ) {
  3587. // this method does not support reflection matrices
  3588. const te = this.elements;
  3589. const me = m.elements;
  3590. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3591. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3592. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3593. te[ 0 ] = me[ 0 ] * scaleX;
  3594. te[ 1 ] = me[ 1 ] * scaleX;
  3595. te[ 2 ] = me[ 2 ] * scaleX;
  3596. te[ 3 ] = 0;
  3597. te[ 4 ] = me[ 4 ] * scaleY;
  3598. te[ 5 ] = me[ 5 ] * scaleY;
  3599. te[ 6 ] = me[ 6 ] * scaleY;
  3600. te[ 7 ] = 0;
  3601. te[ 8 ] = me[ 8 ] * scaleZ;
  3602. te[ 9 ] = me[ 9 ] * scaleZ;
  3603. te[ 10 ] = me[ 10 ] * scaleZ;
  3604. te[ 11 ] = 0;
  3605. te[ 12 ] = 0;
  3606. te[ 13 ] = 0;
  3607. te[ 14 ] = 0;
  3608. te[ 15 ] = 1;
  3609. return this;
  3610. }
  3611. makeRotationFromEuler( euler ) {
  3612. const te = this.elements;
  3613. const x = euler.x, y = euler.y, z = euler.z;
  3614. const a = Math.cos( x ), b = Math.sin( x );
  3615. const c = Math.cos( y ), d = Math.sin( y );
  3616. const e = Math.cos( z ), f = Math.sin( z );
  3617. if ( euler.order === 'XYZ' ) {
  3618. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3619. te[ 0 ] = c * e;
  3620. te[ 4 ] = - c * f;
  3621. te[ 8 ] = d;
  3622. te[ 1 ] = af + be * d;
  3623. te[ 5 ] = ae - bf * d;
  3624. te[ 9 ] = - b * c;
  3625. te[ 2 ] = bf - ae * d;
  3626. te[ 6 ] = be + af * d;
  3627. te[ 10 ] = a * c;
  3628. } else if ( euler.order === 'YXZ' ) {
  3629. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3630. te[ 0 ] = ce + df * b;
  3631. te[ 4 ] = de * b - cf;
  3632. te[ 8 ] = a * d;
  3633. te[ 1 ] = a * f;
  3634. te[ 5 ] = a * e;
  3635. te[ 9 ] = - b;
  3636. te[ 2 ] = cf * b - de;
  3637. te[ 6 ] = df + ce * b;
  3638. te[ 10 ] = a * c;
  3639. } else if ( euler.order === 'ZXY' ) {
  3640. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3641. te[ 0 ] = ce - df * b;
  3642. te[ 4 ] = - a * f;
  3643. te[ 8 ] = de + cf * b;
  3644. te[ 1 ] = cf + de * b;
  3645. te[ 5 ] = a * e;
  3646. te[ 9 ] = df - ce * b;
  3647. te[ 2 ] = - a * d;
  3648. te[ 6 ] = b;
  3649. te[ 10 ] = a * c;
  3650. } else if ( euler.order === 'ZYX' ) {
  3651. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3652. te[ 0 ] = c * e;
  3653. te[ 4 ] = be * d - af;
  3654. te[ 8 ] = ae * d + bf;
  3655. te[ 1 ] = c * f;
  3656. te[ 5 ] = bf * d + ae;
  3657. te[ 9 ] = af * d - be;
  3658. te[ 2 ] = - d;
  3659. te[ 6 ] = b * c;
  3660. te[ 10 ] = a * c;
  3661. } else if ( euler.order === 'YZX' ) {
  3662. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3663. te[ 0 ] = c * e;
  3664. te[ 4 ] = bd - ac * f;
  3665. te[ 8 ] = bc * f + ad;
  3666. te[ 1 ] = f;
  3667. te[ 5 ] = a * e;
  3668. te[ 9 ] = - b * e;
  3669. te[ 2 ] = - d * e;
  3670. te[ 6 ] = ad * f + bc;
  3671. te[ 10 ] = ac - bd * f;
  3672. } else if ( euler.order === 'XZY' ) {
  3673. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3674. te[ 0 ] = c * e;
  3675. te[ 4 ] = - f;
  3676. te[ 8 ] = d * e;
  3677. te[ 1 ] = ac * f + bd;
  3678. te[ 5 ] = a * e;
  3679. te[ 9 ] = ad * f - bc;
  3680. te[ 2 ] = bc * f - ad;
  3681. te[ 6 ] = b * e;
  3682. te[ 10 ] = bd * f + ac;
  3683. }
  3684. // bottom row
  3685. te[ 3 ] = 0;
  3686. te[ 7 ] = 0;
  3687. te[ 11 ] = 0;
  3688. // last column
  3689. te[ 12 ] = 0;
  3690. te[ 13 ] = 0;
  3691. te[ 14 ] = 0;
  3692. te[ 15 ] = 1;
  3693. return this;
  3694. }
  3695. makeRotationFromQuaternion( q ) {
  3696. return this.compose( _zero, q, _one );
  3697. }
  3698. lookAt( eye, target, up ) {
  3699. const te = this.elements;
  3700. _z.subVectors( eye, target );
  3701. if ( _z.lengthSq() === 0 ) {
  3702. // eye and target are in the same position
  3703. _z.z = 1;
  3704. }
  3705. _z.normalize();
  3706. _x.crossVectors( up, _z );
  3707. if ( _x.lengthSq() === 0 ) {
  3708. // up and z are parallel
  3709. if ( Math.abs( up.z ) === 1 ) {
  3710. _z.x += 0.0001;
  3711. } else {
  3712. _z.z += 0.0001;
  3713. }
  3714. _z.normalize();
  3715. _x.crossVectors( up, _z );
  3716. }
  3717. _x.normalize();
  3718. _y.crossVectors( _z, _x );
  3719. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3720. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3721. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3722. return this;
  3723. }
  3724. multiply( m ) {
  3725. return this.multiplyMatrices( this, m );
  3726. }
  3727. premultiply( m ) {
  3728. return this.multiplyMatrices( m, this );
  3729. }
  3730. multiplyMatrices( a, b ) {
  3731. const ae = a.elements;
  3732. const be = b.elements;
  3733. const te = this.elements;
  3734. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3735. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3736. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3737. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3738. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3739. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3740. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3741. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3742. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3743. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3744. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3745. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3746. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3747. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3748. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3749. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3750. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3751. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3752. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3753. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3754. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3755. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3756. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3757. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3758. return this;
  3759. }
  3760. multiplyScalar( s ) {
  3761. const te = this.elements;
  3762. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3763. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3764. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3765. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3766. return this;
  3767. }
  3768. determinant() {
  3769. const te = this.elements;
  3770. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3771. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3772. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3773. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3774. //TODO: make this more efficient
  3775. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3776. return (
  3777. n41 * (
  3778. + n14 * n23 * n32
  3779. - n13 * n24 * n32
  3780. - n14 * n22 * n33
  3781. + n12 * n24 * n33
  3782. + n13 * n22 * n34
  3783. - n12 * n23 * n34
  3784. ) +
  3785. n42 * (
  3786. + n11 * n23 * n34
  3787. - n11 * n24 * n33
  3788. + n14 * n21 * n33
  3789. - n13 * n21 * n34
  3790. + n13 * n24 * n31
  3791. - n14 * n23 * n31
  3792. ) +
  3793. n43 * (
  3794. + n11 * n24 * n32
  3795. - n11 * n22 * n34
  3796. - n14 * n21 * n32
  3797. + n12 * n21 * n34
  3798. + n14 * n22 * n31
  3799. - n12 * n24 * n31
  3800. ) +
  3801. n44 * (
  3802. - n13 * n22 * n31
  3803. - n11 * n23 * n32
  3804. + n11 * n22 * n33
  3805. + n13 * n21 * n32
  3806. - n12 * n21 * n33
  3807. + n12 * n23 * n31
  3808. )
  3809. );
  3810. }
  3811. transpose() {
  3812. const te = this.elements;
  3813. let tmp;
  3814. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3815. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3816. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3817. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3818. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3819. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3820. return this;
  3821. }
  3822. setPosition( x, y, z ) {
  3823. const te = this.elements;
  3824. if ( x.isVector3 ) {
  3825. te[ 12 ] = x.x;
  3826. te[ 13 ] = x.y;
  3827. te[ 14 ] = x.z;
  3828. } else {
  3829. te[ 12 ] = x;
  3830. te[ 13 ] = y;
  3831. te[ 14 ] = z;
  3832. }
  3833. return this;
  3834. }
  3835. invert() {
  3836. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3837. const te = this.elements,
  3838. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3839. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3840. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3841. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3842. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3843. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3844. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3845. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3846. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3847. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3848. const detInv = 1 / det;
  3849. te[ 0 ] = t11 * detInv;
  3850. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3851. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3852. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3853. te[ 4 ] = t12 * detInv;
  3854. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3855. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3856. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3857. te[ 8 ] = t13 * detInv;
  3858. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3859. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3860. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3861. te[ 12 ] = t14 * detInv;
  3862. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3863. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3864. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3865. return this;
  3866. }
  3867. scale( v ) {
  3868. const te = this.elements;
  3869. const x = v.x, y = v.y, z = v.z;
  3870. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3871. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3872. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3873. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3874. return this;
  3875. }
  3876. getMaxScaleOnAxis() {
  3877. const te = this.elements;
  3878. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3879. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3880. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3881. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3882. }
  3883. makeTranslation( x, y, z ) {
  3884. if ( x.isVector3 ) {
  3885. this.set(
  3886. 1, 0, 0, x.x,
  3887. 0, 1, 0, x.y,
  3888. 0, 0, 1, x.z,
  3889. 0, 0, 0, 1
  3890. );
  3891. } else {
  3892. this.set(
  3893. 1, 0, 0, x,
  3894. 0, 1, 0, y,
  3895. 0, 0, 1, z,
  3896. 0, 0, 0, 1
  3897. );
  3898. }
  3899. return this;
  3900. }
  3901. makeRotationX( theta ) {
  3902. const c = Math.cos( theta ), s = Math.sin( theta );
  3903. this.set(
  3904. 1, 0, 0, 0,
  3905. 0, c, - s, 0,
  3906. 0, s, c, 0,
  3907. 0, 0, 0, 1
  3908. );
  3909. return this;
  3910. }
  3911. makeRotationY( theta ) {
  3912. const c = Math.cos( theta ), s = Math.sin( theta );
  3913. this.set(
  3914. c, 0, s, 0,
  3915. 0, 1, 0, 0,
  3916. - s, 0, c, 0,
  3917. 0, 0, 0, 1
  3918. );
  3919. return this;
  3920. }
  3921. makeRotationZ( theta ) {
  3922. const c = Math.cos( theta ), s = Math.sin( theta );
  3923. this.set(
  3924. c, - s, 0, 0,
  3925. s, c, 0, 0,
  3926. 0, 0, 1, 0,
  3927. 0, 0, 0, 1
  3928. );
  3929. return this;
  3930. }
  3931. makeRotationAxis( axis, angle ) {
  3932. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3933. const c = Math.cos( angle );
  3934. const s = Math.sin( angle );
  3935. const t = 1 - c;
  3936. const x = axis.x, y = axis.y, z = axis.z;
  3937. const tx = t * x, ty = t * y;
  3938. this.set(
  3939. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3940. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3941. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3942. 0, 0, 0, 1
  3943. );
  3944. return this;
  3945. }
  3946. makeScale( x, y, z ) {
  3947. this.set(
  3948. x, 0, 0, 0,
  3949. 0, y, 0, 0,
  3950. 0, 0, z, 0,
  3951. 0, 0, 0, 1
  3952. );
  3953. return this;
  3954. }
  3955. makeShear( xy, xz, yx, yz, zx, zy ) {
  3956. this.set(
  3957. 1, yx, zx, 0,
  3958. xy, 1, zy, 0,
  3959. xz, yz, 1, 0,
  3960. 0, 0, 0, 1
  3961. );
  3962. return this;
  3963. }
  3964. compose( position, quaternion, scale ) {
  3965. const te = this.elements;
  3966. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3967. const x2 = x + x, y2 = y + y, z2 = z + z;
  3968. const xx = x * x2, xy = x * y2, xz = x * z2;
  3969. const yy = y * y2, yz = y * z2, zz = z * z2;
  3970. const wx = w * x2, wy = w * y2, wz = w * z2;
  3971. const sx = scale.x, sy = scale.y, sz = scale.z;
  3972. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3973. te[ 1 ] = ( xy + wz ) * sx;
  3974. te[ 2 ] = ( xz - wy ) * sx;
  3975. te[ 3 ] = 0;
  3976. te[ 4 ] = ( xy - wz ) * sy;
  3977. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3978. te[ 6 ] = ( yz + wx ) * sy;
  3979. te[ 7 ] = 0;
  3980. te[ 8 ] = ( xz + wy ) * sz;
  3981. te[ 9 ] = ( yz - wx ) * sz;
  3982. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3983. te[ 11 ] = 0;
  3984. te[ 12 ] = position.x;
  3985. te[ 13 ] = position.y;
  3986. te[ 14 ] = position.z;
  3987. te[ 15 ] = 1;
  3988. return this;
  3989. }
  3990. decompose( position, quaternion, scale ) {
  3991. const te = this.elements;
  3992. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3993. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3994. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3995. // if determine is negative, we need to invert one scale
  3996. const det = this.determinant();
  3997. if ( det < 0 ) sx = - sx;
  3998. position.x = te[ 12 ];
  3999. position.y = te[ 13 ];
  4000. position.z = te[ 14 ];
  4001. // scale the rotation part
  4002. _m1$2.copy( this );
  4003. const invSX = 1 / sx;
  4004. const invSY = 1 / sy;
  4005. const invSZ = 1 / sz;
  4006. _m1$2.elements[ 0 ] *= invSX;
  4007. _m1$2.elements[ 1 ] *= invSX;
  4008. _m1$2.elements[ 2 ] *= invSX;
  4009. _m1$2.elements[ 4 ] *= invSY;
  4010. _m1$2.elements[ 5 ] *= invSY;
  4011. _m1$2.elements[ 6 ] *= invSY;
  4012. _m1$2.elements[ 8 ] *= invSZ;
  4013. _m1$2.elements[ 9 ] *= invSZ;
  4014. _m1$2.elements[ 10 ] *= invSZ;
  4015. quaternion.setFromRotationMatrix( _m1$2 );
  4016. scale.x = sx;
  4017. scale.y = sy;
  4018. scale.z = sz;
  4019. return this;
  4020. }
  4021. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4022. const te = this.elements;
  4023. const x = 2 * near / ( right - left );
  4024. const y = 2 * near / ( top - bottom );
  4025. const a = ( right + left ) / ( right - left );
  4026. const b = ( top + bottom ) / ( top - bottom );
  4027. let c, d;
  4028. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4029. c = - ( far + near ) / ( far - near );
  4030. d = ( - 2 * far * near ) / ( far - near );
  4031. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4032. c = - far / ( far - near );
  4033. d = ( - far * near ) / ( far - near );
  4034. } else {
  4035. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4036. }
  4037. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4038. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4039. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4040. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4041. return this;
  4042. }
  4043. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4044. const te = this.elements;
  4045. const w = 1.0 / ( right - left );
  4046. const h = 1.0 / ( top - bottom );
  4047. const p = 1.0 / ( far - near );
  4048. const x = ( right + left ) * w;
  4049. const y = ( top + bottom ) * h;
  4050. let z, zInv;
  4051. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4052. z = ( far + near ) * p;
  4053. zInv = - 2 * p;
  4054. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4055. z = near * p;
  4056. zInv = - 1 * p;
  4057. } else {
  4058. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4059. }
  4060. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4061. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4062. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4063. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4064. return this;
  4065. }
  4066. equals( matrix ) {
  4067. const te = this.elements;
  4068. const me = matrix.elements;
  4069. for ( let i = 0; i < 16; i ++ ) {
  4070. if ( te[ i ] !== me[ i ] ) return false;
  4071. }
  4072. return true;
  4073. }
  4074. fromArray( array, offset = 0 ) {
  4075. for ( let i = 0; i < 16; i ++ ) {
  4076. this.elements[ i ] = array[ i + offset ];
  4077. }
  4078. return this;
  4079. }
  4080. toArray( array = [], offset = 0 ) {
  4081. const te = this.elements;
  4082. array[ offset ] = te[ 0 ];
  4083. array[ offset + 1 ] = te[ 1 ];
  4084. array[ offset + 2 ] = te[ 2 ];
  4085. array[ offset + 3 ] = te[ 3 ];
  4086. array[ offset + 4 ] = te[ 4 ];
  4087. array[ offset + 5 ] = te[ 5 ];
  4088. array[ offset + 6 ] = te[ 6 ];
  4089. array[ offset + 7 ] = te[ 7 ];
  4090. array[ offset + 8 ] = te[ 8 ];
  4091. array[ offset + 9 ] = te[ 9 ];
  4092. array[ offset + 10 ] = te[ 10 ];
  4093. array[ offset + 11 ] = te[ 11 ];
  4094. array[ offset + 12 ] = te[ 12 ];
  4095. array[ offset + 13 ] = te[ 13 ];
  4096. array[ offset + 14 ] = te[ 14 ];
  4097. array[ offset + 15 ] = te[ 15 ];
  4098. return array;
  4099. }
  4100. }
  4101. const _v1$5 = /*@__PURE__*/ new Vector3();
  4102. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4103. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4104. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4105. const _x = /*@__PURE__*/ new Vector3();
  4106. const _y = /*@__PURE__*/ new Vector3();
  4107. const _z = /*@__PURE__*/ new Vector3();
  4108. const _matrix = /*@__PURE__*/ new Matrix4();
  4109. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4110. class Euler {
  4111. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4112. this.isEuler = true;
  4113. this._x = x;
  4114. this._y = y;
  4115. this._z = z;
  4116. this._order = order;
  4117. }
  4118. get x() {
  4119. return this._x;
  4120. }
  4121. set x( value ) {
  4122. this._x = value;
  4123. this._onChangeCallback();
  4124. }
  4125. get y() {
  4126. return this._y;
  4127. }
  4128. set y( value ) {
  4129. this._y = value;
  4130. this._onChangeCallback();
  4131. }
  4132. get z() {
  4133. return this._z;
  4134. }
  4135. set z( value ) {
  4136. this._z = value;
  4137. this._onChangeCallback();
  4138. }
  4139. get order() {
  4140. return this._order;
  4141. }
  4142. set order( value ) {
  4143. this._order = value;
  4144. this._onChangeCallback();
  4145. }
  4146. set( x, y, z, order = this._order ) {
  4147. this._x = x;
  4148. this._y = y;
  4149. this._z = z;
  4150. this._order = order;
  4151. this._onChangeCallback();
  4152. return this;
  4153. }
  4154. clone() {
  4155. return new this.constructor( this._x, this._y, this._z, this._order );
  4156. }
  4157. copy( euler ) {
  4158. this._x = euler._x;
  4159. this._y = euler._y;
  4160. this._z = euler._z;
  4161. this._order = euler._order;
  4162. this._onChangeCallback();
  4163. return this;
  4164. }
  4165. setFromRotationMatrix( m, order = this._order, update = true ) {
  4166. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4167. const te = m.elements;
  4168. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4169. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4170. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4171. switch ( order ) {
  4172. case 'XYZ':
  4173. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4174. if ( Math.abs( m13 ) < 0.9999999 ) {
  4175. this._x = Math.atan2( - m23, m33 );
  4176. this._z = Math.atan2( - m12, m11 );
  4177. } else {
  4178. this._x = Math.atan2( m32, m22 );
  4179. this._z = 0;
  4180. }
  4181. break;
  4182. case 'YXZ':
  4183. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4184. if ( Math.abs( m23 ) < 0.9999999 ) {
  4185. this._y = Math.atan2( m13, m33 );
  4186. this._z = Math.atan2( m21, m22 );
  4187. } else {
  4188. this._y = Math.atan2( - m31, m11 );
  4189. this._z = 0;
  4190. }
  4191. break;
  4192. case 'ZXY':
  4193. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4194. if ( Math.abs( m32 ) < 0.9999999 ) {
  4195. this._y = Math.atan2( - m31, m33 );
  4196. this._z = Math.atan2( - m12, m22 );
  4197. } else {
  4198. this._y = 0;
  4199. this._z = Math.atan2( m21, m11 );
  4200. }
  4201. break;
  4202. case 'ZYX':
  4203. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4204. if ( Math.abs( m31 ) < 0.9999999 ) {
  4205. this._x = Math.atan2( m32, m33 );
  4206. this._z = Math.atan2( m21, m11 );
  4207. } else {
  4208. this._x = 0;
  4209. this._z = Math.atan2( - m12, m22 );
  4210. }
  4211. break;
  4212. case 'YZX':
  4213. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4214. if ( Math.abs( m21 ) < 0.9999999 ) {
  4215. this._x = Math.atan2( - m23, m22 );
  4216. this._y = Math.atan2( - m31, m11 );
  4217. } else {
  4218. this._x = 0;
  4219. this._y = Math.atan2( m13, m33 );
  4220. }
  4221. break;
  4222. case 'XZY':
  4223. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4224. if ( Math.abs( m12 ) < 0.9999999 ) {
  4225. this._x = Math.atan2( m32, m22 );
  4226. this._y = Math.atan2( m13, m11 );
  4227. } else {
  4228. this._x = Math.atan2( - m23, m33 );
  4229. this._y = 0;
  4230. }
  4231. break;
  4232. default:
  4233. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4234. }
  4235. this._order = order;
  4236. if ( update === true ) this._onChangeCallback();
  4237. return this;
  4238. }
  4239. setFromQuaternion( q, order, update ) {
  4240. _matrix.makeRotationFromQuaternion( q );
  4241. return this.setFromRotationMatrix( _matrix, order, update );
  4242. }
  4243. setFromVector3( v, order = this._order ) {
  4244. return this.set( v.x, v.y, v.z, order );
  4245. }
  4246. reorder( newOrder ) {
  4247. // WARNING: this discards revolution information -bhouston
  4248. _quaternion$3.setFromEuler( this );
  4249. return this.setFromQuaternion( _quaternion$3, newOrder );
  4250. }
  4251. equals( euler ) {
  4252. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4253. }
  4254. fromArray( array ) {
  4255. this._x = array[ 0 ];
  4256. this._y = array[ 1 ];
  4257. this._z = array[ 2 ];
  4258. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4259. this._onChangeCallback();
  4260. return this;
  4261. }
  4262. toArray( array = [], offset = 0 ) {
  4263. array[ offset ] = this._x;
  4264. array[ offset + 1 ] = this._y;
  4265. array[ offset + 2 ] = this._z;
  4266. array[ offset + 3 ] = this._order;
  4267. return array;
  4268. }
  4269. _onChange( callback ) {
  4270. this._onChangeCallback = callback;
  4271. return this;
  4272. }
  4273. _onChangeCallback() {}
  4274. *[ Symbol.iterator ]() {
  4275. yield this._x;
  4276. yield this._y;
  4277. yield this._z;
  4278. yield this._order;
  4279. }
  4280. }
  4281. Euler.DEFAULT_ORDER = 'XYZ';
  4282. class Layers {
  4283. constructor() {
  4284. this.mask = 1 | 0;
  4285. }
  4286. set( channel ) {
  4287. this.mask = ( 1 << channel | 0 ) >>> 0;
  4288. }
  4289. enable( channel ) {
  4290. this.mask |= 1 << channel | 0;
  4291. }
  4292. enableAll() {
  4293. this.mask = 0xffffffff | 0;
  4294. }
  4295. toggle( channel ) {
  4296. this.mask ^= 1 << channel | 0;
  4297. }
  4298. disable( channel ) {
  4299. this.mask &= ~ ( 1 << channel | 0 );
  4300. }
  4301. disableAll() {
  4302. this.mask = 0;
  4303. }
  4304. test( layers ) {
  4305. return ( this.mask & layers.mask ) !== 0;
  4306. }
  4307. isEnabled( channel ) {
  4308. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4309. }
  4310. }
  4311. let _object3DId = 0;
  4312. const _v1$4 = /*@__PURE__*/ new Vector3();
  4313. const _q1 = /*@__PURE__*/ new Quaternion();
  4314. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4315. const _target = /*@__PURE__*/ new Vector3();
  4316. const _position$3 = /*@__PURE__*/ new Vector3();
  4317. const _scale$2 = /*@__PURE__*/ new Vector3();
  4318. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4319. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4320. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4321. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4322. const _addedEvent = { type: 'added' };
  4323. const _removedEvent = { type: 'removed' };
  4324. class Object3D extends EventDispatcher {
  4325. constructor() {
  4326. super();
  4327. this.isObject3D = true;
  4328. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4329. this.uuid = generateUUID();
  4330. this.name = '';
  4331. this.type = 'Object3D';
  4332. this.parent = null;
  4333. this.children = [];
  4334. this.up = Object3D.DEFAULT_UP.clone();
  4335. const position = new Vector3();
  4336. const rotation = new Euler();
  4337. const quaternion = new Quaternion();
  4338. const scale = new Vector3( 1, 1, 1 );
  4339. function onRotationChange() {
  4340. quaternion.setFromEuler( rotation, false );
  4341. }
  4342. function onQuaternionChange() {
  4343. rotation.setFromQuaternion( quaternion, undefined, false );
  4344. }
  4345. rotation._onChange( onRotationChange );
  4346. quaternion._onChange( onQuaternionChange );
  4347. Object.defineProperties( this, {
  4348. position: {
  4349. configurable: true,
  4350. enumerable: true,
  4351. value: position
  4352. },
  4353. rotation: {
  4354. configurable: true,
  4355. enumerable: true,
  4356. value: rotation
  4357. },
  4358. quaternion: {
  4359. configurable: true,
  4360. enumerable: true,
  4361. value: quaternion
  4362. },
  4363. scale: {
  4364. configurable: true,
  4365. enumerable: true,
  4366. value: scale
  4367. },
  4368. modelViewMatrix: {
  4369. value: new Matrix4()
  4370. },
  4371. normalMatrix: {
  4372. value: new Matrix3()
  4373. }
  4374. } );
  4375. this.matrix = new Matrix4();
  4376. this.matrixWorld = new Matrix4();
  4377. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4378. this.matrixWorldNeedsUpdate = false;
  4379. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4380. this.layers = new Layers();
  4381. this.visible = true;
  4382. this.castShadow = false;
  4383. this.receiveShadow = false;
  4384. this.frustumCulled = true;
  4385. this.renderOrder = 0;
  4386. this.animations = [];
  4387. this.userData = {};
  4388. }
  4389. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4390. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4391. applyMatrix4( matrix ) {
  4392. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4393. this.matrix.premultiply( matrix );
  4394. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4395. }
  4396. applyQuaternion( q ) {
  4397. this.quaternion.premultiply( q );
  4398. return this;
  4399. }
  4400. setRotationFromAxisAngle( axis, angle ) {
  4401. // assumes axis is normalized
  4402. this.quaternion.setFromAxisAngle( axis, angle );
  4403. }
  4404. setRotationFromEuler( euler ) {
  4405. this.quaternion.setFromEuler( euler, true );
  4406. }
  4407. setRotationFromMatrix( m ) {
  4408. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4409. this.quaternion.setFromRotationMatrix( m );
  4410. }
  4411. setRotationFromQuaternion( q ) {
  4412. // assumes q is normalized
  4413. this.quaternion.copy( q );
  4414. }
  4415. rotateOnAxis( axis, angle ) {
  4416. // rotate object on axis in object space
  4417. // axis is assumed to be normalized
  4418. _q1.setFromAxisAngle( axis, angle );
  4419. this.quaternion.multiply( _q1 );
  4420. return this;
  4421. }
  4422. rotateOnWorldAxis( axis, angle ) {
  4423. // rotate object on axis in world space
  4424. // axis is assumed to be normalized
  4425. // method assumes no rotated parent
  4426. _q1.setFromAxisAngle( axis, angle );
  4427. this.quaternion.premultiply( _q1 );
  4428. return this;
  4429. }
  4430. rotateX( angle ) {
  4431. return this.rotateOnAxis( _xAxis, angle );
  4432. }
  4433. rotateY( angle ) {
  4434. return this.rotateOnAxis( _yAxis, angle );
  4435. }
  4436. rotateZ( angle ) {
  4437. return this.rotateOnAxis( _zAxis, angle );
  4438. }
  4439. translateOnAxis( axis, distance ) {
  4440. // translate object by distance along axis in object space
  4441. // axis is assumed to be normalized
  4442. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4443. this.position.add( _v1$4.multiplyScalar( distance ) );
  4444. return this;
  4445. }
  4446. translateX( distance ) {
  4447. return this.translateOnAxis( _xAxis, distance );
  4448. }
  4449. translateY( distance ) {
  4450. return this.translateOnAxis( _yAxis, distance );
  4451. }
  4452. translateZ( distance ) {
  4453. return this.translateOnAxis( _zAxis, distance );
  4454. }
  4455. localToWorld( vector ) {
  4456. this.updateWorldMatrix( true, false );
  4457. return vector.applyMatrix4( this.matrixWorld );
  4458. }
  4459. worldToLocal( vector ) {
  4460. this.updateWorldMatrix( true, false );
  4461. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4462. }
  4463. lookAt( x, y, z ) {
  4464. // This method does not support objects having non-uniformly-scaled parent(s)
  4465. if ( x.isVector3 ) {
  4466. _target.copy( x );
  4467. } else {
  4468. _target.set( x, y, z );
  4469. }
  4470. const parent = this.parent;
  4471. this.updateWorldMatrix( true, false );
  4472. _position$3.setFromMatrixPosition( this.matrixWorld );
  4473. if ( this.isCamera || this.isLight ) {
  4474. _m1$1.lookAt( _position$3, _target, this.up );
  4475. } else {
  4476. _m1$1.lookAt( _target, _position$3, this.up );
  4477. }
  4478. this.quaternion.setFromRotationMatrix( _m1$1 );
  4479. if ( parent ) {
  4480. _m1$1.extractRotation( parent.matrixWorld );
  4481. _q1.setFromRotationMatrix( _m1$1 );
  4482. this.quaternion.premultiply( _q1.invert() );
  4483. }
  4484. }
  4485. add( object ) {
  4486. if ( arguments.length > 1 ) {
  4487. for ( let i = 0; i < arguments.length; i ++ ) {
  4488. this.add( arguments[ i ] );
  4489. }
  4490. return this;
  4491. }
  4492. if ( object === this ) {
  4493. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4494. return this;
  4495. }
  4496. if ( object && object.isObject3D ) {
  4497. if ( object.parent !== null ) {
  4498. object.parent.remove( object );
  4499. }
  4500. object.parent = this;
  4501. this.children.push( object );
  4502. object.dispatchEvent( _addedEvent );
  4503. } else {
  4504. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4505. }
  4506. return this;
  4507. }
  4508. remove( object ) {
  4509. if ( arguments.length > 1 ) {
  4510. for ( let i = 0; i < arguments.length; i ++ ) {
  4511. this.remove( arguments[ i ] );
  4512. }
  4513. return this;
  4514. }
  4515. const index = this.children.indexOf( object );
  4516. if ( index !== - 1 ) {
  4517. object.parent = null;
  4518. this.children.splice( index, 1 );
  4519. object.dispatchEvent( _removedEvent );
  4520. }
  4521. return this;
  4522. }
  4523. removeFromParent() {
  4524. const parent = this.parent;
  4525. if ( parent !== null ) {
  4526. parent.remove( this );
  4527. }
  4528. return this;
  4529. }
  4530. clear() {
  4531. return this.remove( ... this.children );
  4532. }
  4533. attach( object ) {
  4534. // adds object as a child of this, while maintaining the object's world transform
  4535. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4536. this.updateWorldMatrix( true, false );
  4537. _m1$1.copy( this.matrixWorld ).invert();
  4538. if ( object.parent !== null ) {
  4539. object.parent.updateWorldMatrix( true, false );
  4540. _m1$1.multiply( object.parent.matrixWorld );
  4541. }
  4542. object.applyMatrix4( _m1$1 );
  4543. this.add( object );
  4544. object.updateWorldMatrix( false, true );
  4545. return this;
  4546. }
  4547. getObjectById( id ) {
  4548. return this.getObjectByProperty( 'id', id );
  4549. }
  4550. getObjectByName( name ) {
  4551. return this.getObjectByProperty( 'name', name );
  4552. }
  4553. getObjectByProperty( name, value ) {
  4554. if ( this[ name ] === value ) return this;
  4555. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4556. const child = this.children[ i ];
  4557. const object = child.getObjectByProperty( name, value );
  4558. if ( object !== undefined ) {
  4559. return object;
  4560. }
  4561. }
  4562. return undefined;
  4563. }
  4564. getObjectsByProperty( name, value ) {
  4565. let result = [];
  4566. if ( this[ name ] === value ) result.push( this );
  4567. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4568. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4569. if ( childResult.length > 0 ) {
  4570. result = result.concat( childResult );
  4571. }
  4572. }
  4573. return result;
  4574. }
  4575. getWorldPosition( target ) {
  4576. this.updateWorldMatrix( true, false );
  4577. return target.setFromMatrixPosition( this.matrixWorld );
  4578. }
  4579. getWorldQuaternion( target ) {
  4580. this.updateWorldMatrix( true, false );
  4581. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4582. return target;
  4583. }
  4584. getWorldScale( target ) {
  4585. this.updateWorldMatrix( true, false );
  4586. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4587. return target;
  4588. }
  4589. getWorldDirection( target ) {
  4590. this.updateWorldMatrix( true, false );
  4591. const e = this.matrixWorld.elements;
  4592. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4593. }
  4594. raycast( /* raycaster, intersects */ ) {}
  4595. traverse( callback ) {
  4596. callback( this );
  4597. const children = this.children;
  4598. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4599. children[ i ].traverse( callback );
  4600. }
  4601. }
  4602. traverseVisible( callback ) {
  4603. if ( this.visible === false ) return;
  4604. callback( this );
  4605. const children = this.children;
  4606. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4607. children[ i ].traverseVisible( callback );
  4608. }
  4609. }
  4610. traverseAncestors( callback ) {
  4611. const parent = this.parent;
  4612. if ( parent !== null ) {
  4613. callback( parent );
  4614. parent.traverseAncestors( callback );
  4615. }
  4616. }
  4617. updateMatrix() {
  4618. this.matrix.compose( this.position, this.quaternion, this.scale );
  4619. this.matrixWorldNeedsUpdate = true;
  4620. }
  4621. updateMatrixWorld( force ) {
  4622. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4623. if ( this.matrixWorldNeedsUpdate || force ) {
  4624. if ( this.parent === null ) {
  4625. this.matrixWorld.copy( this.matrix );
  4626. } else {
  4627. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4628. }
  4629. this.matrixWorldNeedsUpdate = false;
  4630. force = true;
  4631. }
  4632. // update children
  4633. const children = this.children;
  4634. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4635. const child = children[ i ];
  4636. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4637. child.updateMatrixWorld( force );
  4638. }
  4639. }
  4640. }
  4641. updateWorldMatrix( updateParents, updateChildren ) {
  4642. const parent = this.parent;
  4643. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4644. parent.updateWorldMatrix( true, false );
  4645. }
  4646. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4647. if ( this.parent === null ) {
  4648. this.matrixWorld.copy( this.matrix );
  4649. } else {
  4650. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4651. }
  4652. // update children
  4653. if ( updateChildren === true ) {
  4654. const children = this.children;
  4655. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4656. const child = children[ i ];
  4657. if ( child.matrixWorldAutoUpdate === true ) {
  4658. child.updateWorldMatrix( false, true );
  4659. }
  4660. }
  4661. }
  4662. }
  4663. toJSON( meta ) {
  4664. // meta is a string when called from JSON.stringify
  4665. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4666. const output = {};
  4667. // meta is a hash used to collect geometries, materials.
  4668. // not providing it implies that this is the root object
  4669. // being serialized.
  4670. if ( isRootObject ) {
  4671. // initialize meta obj
  4672. meta = {
  4673. geometries: {},
  4674. materials: {},
  4675. textures: {},
  4676. images: {},
  4677. shapes: {},
  4678. skeletons: {},
  4679. animations: {},
  4680. nodes: {}
  4681. };
  4682. output.metadata = {
  4683. version: 4.6,
  4684. type: 'Object',
  4685. generator: 'Object3D.toJSON'
  4686. };
  4687. }
  4688. // standard Object3D serialization
  4689. const object = {};
  4690. object.uuid = this.uuid;
  4691. object.type = this.type;
  4692. if ( this.name !== '' ) object.name = this.name;
  4693. if ( this.castShadow === true ) object.castShadow = true;
  4694. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4695. if ( this.visible === false ) object.visible = false;
  4696. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4697. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4698. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4699. object.layers = this.layers.mask;
  4700. object.matrix = this.matrix.toArray();
  4701. object.up = this.up.toArray();
  4702. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4703. // object specific properties
  4704. if ( this.isInstancedMesh ) {
  4705. object.type = 'InstancedMesh';
  4706. object.count = this.count;
  4707. object.instanceMatrix = this.instanceMatrix.toJSON();
  4708. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4709. }
  4710. //
  4711. function serialize( library, element ) {
  4712. if ( library[ element.uuid ] === undefined ) {
  4713. library[ element.uuid ] = element.toJSON( meta );
  4714. }
  4715. return element.uuid;
  4716. }
  4717. if ( this.isScene ) {
  4718. if ( this.background ) {
  4719. if ( this.background.isColor ) {
  4720. object.background = this.background.toJSON();
  4721. } else if ( this.background.isTexture ) {
  4722. object.background = this.background.toJSON( meta ).uuid;
  4723. }
  4724. }
  4725. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4726. object.environment = this.environment.toJSON( meta ).uuid;
  4727. }
  4728. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4729. object.geometry = serialize( meta.geometries, this.geometry );
  4730. const parameters = this.geometry.parameters;
  4731. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4732. const shapes = parameters.shapes;
  4733. if ( Array.isArray( shapes ) ) {
  4734. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4735. const shape = shapes[ i ];
  4736. serialize( meta.shapes, shape );
  4737. }
  4738. } else {
  4739. serialize( meta.shapes, shapes );
  4740. }
  4741. }
  4742. }
  4743. if ( this.isSkinnedMesh ) {
  4744. object.bindMode = this.bindMode;
  4745. object.bindMatrix = this.bindMatrix.toArray();
  4746. if ( this.skeleton !== undefined ) {
  4747. serialize( meta.skeletons, this.skeleton );
  4748. object.skeleton = this.skeleton.uuid;
  4749. }
  4750. }
  4751. if ( this.material !== undefined ) {
  4752. if ( Array.isArray( this.material ) ) {
  4753. const uuids = [];
  4754. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4755. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4756. }
  4757. object.material = uuids;
  4758. } else {
  4759. object.material = serialize( meta.materials, this.material );
  4760. }
  4761. }
  4762. //
  4763. if ( this.children.length > 0 ) {
  4764. object.children = [];
  4765. for ( let i = 0; i < this.children.length; i ++ ) {
  4766. object.children.push( this.children[ i ].toJSON( meta ).object );
  4767. }
  4768. }
  4769. //
  4770. if ( this.animations.length > 0 ) {
  4771. object.animations = [];
  4772. for ( let i = 0; i < this.animations.length; i ++ ) {
  4773. const animation = this.animations[ i ];
  4774. object.animations.push( serialize( meta.animations, animation ) );
  4775. }
  4776. }
  4777. if ( isRootObject ) {
  4778. const geometries = extractFromCache( meta.geometries );
  4779. const materials = extractFromCache( meta.materials );
  4780. const textures = extractFromCache( meta.textures );
  4781. const images = extractFromCache( meta.images );
  4782. const shapes = extractFromCache( meta.shapes );
  4783. const skeletons = extractFromCache( meta.skeletons );
  4784. const animations = extractFromCache( meta.animations );
  4785. const nodes = extractFromCache( meta.nodes );
  4786. if ( geometries.length > 0 ) output.geometries = geometries;
  4787. if ( materials.length > 0 ) output.materials = materials;
  4788. if ( textures.length > 0 ) output.textures = textures;
  4789. if ( images.length > 0 ) output.images = images;
  4790. if ( shapes.length > 0 ) output.shapes = shapes;
  4791. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4792. if ( animations.length > 0 ) output.animations = animations;
  4793. if ( nodes.length > 0 ) output.nodes = nodes;
  4794. }
  4795. output.object = object;
  4796. return output;
  4797. // extract data from the cache hash
  4798. // remove metadata on each item
  4799. // and return as array
  4800. function extractFromCache( cache ) {
  4801. const values = [];
  4802. for ( const key in cache ) {
  4803. const data = cache[ key ];
  4804. delete data.metadata;
  4805. values.push( data );
  4806. }
  4807. return values;
  4808. }
  4809. }
  4810. clone( recursive ) {
  4811. return new this.constructor().copy( this, recursive );
  4812. }
  4813. copy( source, recursive = true ) {
  4814. this.name = source.name;
  4815. this.up.copy( source.up );
  4816. this.position.copy( source.position );
  4817. this.rotation.order = source.rotation.order;
  4818. this.quaternion.copy( source.quaternion );
  4819. this.scale.copy( source.scale );
  4820. this.matrix.copy( source.matrix );
  4821. this.matrixWorld.copy( source.matrixWorld );
  4822. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4823. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4824. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4825. this.layers.mask = source.layers.mask;
  4826. this.visible = source.visible;
  4827. this.castShadow = source.castShadow;
  4828. this.receiveShadow = source.receiveShadow;
  4829. this.frustumCulled = source.frustumCulled;
  4830. this.renderOrder = source.renderOrder;
  4831. this.animations = source.animations.slice();
  4832. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4833. if ( recursive === true ) {
  4834. for ( let i = 0; i < source.children.length; i ++ ) {
  4835. const child = source.children[ i ];
  4836. this.add( child.clone() );
  4837. }
  4838. }
  4839. return this;
  4840. }
  4841. }
  4842. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4843. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4844. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4845. const _v0$1 = /*@__PURE__*/ new Vector3();
  4846. const _v1$3 = /*@__PURE__*/ new Vector3();
  4847. const _v2$2 = /*@__PURE__*/ new Vector3();
  4848. const _v3$1 = /*@__PURE__*/ new Vector3();
  4849. const _vab = /*@__PURE__*/ new Vector3();
  4850. const _vac = /*@__PURE__*/ new Vector3();
  4851. const _vbc = /*@__PURE__*/ new Vector3();
  4852. const _vap = /*@__PURE__*/ new Vector3();
  4853. const _vbp = /*@__PURE__*/ new Vector3();
  4854. const _vcp = /*@__PURE__*/ new Vector3();
  4855. let warnedGetUV = false;
  4856. class Triangle {
  4857. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4858. this.a = a;
  4859. this.b = b;
  4860. this.c = c;
  4861. }
  4862. static getNormal( a, b, c, target ) {
  4863. target.subVectors( c, b );
  4864. _v0$1.subVectors( a, b );
  4865. target.cross( _v0$1 );
  4866. const targetLengthSq = target.lengthSq();
  4867. if ( targetLengthSq > 0 ) {
  4868. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4869. }
  4870. return target.set( 0, 0, 0 );
  4871. }
  4872. // static/instance method to calculate barycentric coordinates
  4873. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4874. static getBarycoord( point, a, b, c, target ) {
  4875. _v0$1.subVectors( c, a );
  4876. _v1$3.subVectors( b, a );
  4877. _v2$2.subVectors( point, a );
  4878. const dot00 = _v0$1.dot( _v0$1 );
  4879. const dot01 = _v0$1.dot( _v1$3 );
  4880. const dot02 = _v0$1.dot( _v2$2 );
  4881. const dot11 = _v1$3.dot( _v1$3 );
  4882. const dot12 = _v1$3.dot( _v2$2 );
  4883. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4884. // collinear or singular triangle
  4885. if ( denom === 0 ) {
  4886. // arbitrary location outside of triangle?
  4887. // not sure if this is the best idea, maybe should be returning undefined
  4888. return target.set( - 2, - 1, - 1 );
  4889. }
  4890. const invDenom = 1 / denom;
  4891. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4892. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4893. // barycentric coordinates must always sum to 1
  4894. return target.set( 1 - u - v, v, u );
  4895. }
  4896. static containsPoint( point, a, b, c ) {
  4897. this.getBarycoord( point, a, b, c, _v3$1 );
  4898. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4899. }
  4900. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151
  4901. if ( warnedGetUV === false ) {
  4902. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4903. warnedGetUV = true;
  4904. }
  4905. return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );
  4906. }
  4907. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4908. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4909. target.setScalar( 0 );
  4910. target.addScaledVector( v1, _v3$1.x );
  4911. target.addScaledVector( v2, _v3$1.y );
  4912. target.addScaledVector( v3, _v3$1.z );
  4913. return target;
  4914. }
  4915. static isFrontFacing( a, b, c, direction ) {
  4916. _v0$1.subVectors( c, b );
  4917. _v1$3.subVectors( a, b );
  4918. // strictly front facing
  4919. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4920. }
  4921. set( a, b, c ) {
  4922. this.a.copy( a );
  4923. this.b.copy( b );
  4924. this.c.copy( c );
  4925. return this;
  4926. }
  4927. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4928. this.a.copy( points[ i0 ] );
  4929. this.b.copy( points[ i1 ] );
  4930. this.c.copy( points[ i2 ] );
  4931. return this;
  4932. }
  4933. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4934. this.a.fromBufferAttribute( attribute, i0 );
  4935. this.b.fromBufferAttribute( attribute, i1 );
  4936. this.c.fromBufferAttribute( attribute, i2 );
  4937. return this;
  4938. }
  4939. clone() {
  4940. return new this.constructor().copy( this );
  4941. }
  4942. copy( triangle ) {
  4943. this.a.copy( triangle.a );
  4944. this.b.copy( triangle.b );
  4945. this.c.copy( triangle.c );
  4946. return this;
  4947. }
  4948. getArea() {
  4949. _v0$1.subVectors( this.c, this.b );
  4950. _v1$3.subVectors( this.a, this.b );
  4951. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4952. }
  4953. getMidpoint( target ) {
  4954. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4955. }
  4956. getNormal( target ) {
  4957. return Triangle.getNormal( this.a, this.b, this.c, target );
  4958. }
  4959. getPlane( target ) {
  4960. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4961. }
  4962. getBarycoord( point, target ) {
  4963. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4964. }
  4965. getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151
  4966. if ( warnedGetUV === false ) {
  4967. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4968. warnedGetUV = true;
  4969. }
  4970. return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4971. }
  4972. getInterpolation( point, v1, v2, v3, target ) {
  4973. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4974. }
  4975. containsPoint( point ) {
  4976. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4977. }
  4978. isFrontFacing( direction ) {
  4979. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4980. }
  4981. intersectsBox( box ) {
  4982. return box.intersectsTriangle( this );
  4983. }
  4984. closestPointToPoint( p, target ) {
  4985. const a = this.a, b = this.b, c = this.c;
  4986. let v, w;
  4987. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4988. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4989. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4990. // basically, we're distinguishing which of the voronoi regions of the triangle
  4991. // the point lies in with the minimum amount of redundant computation.
  4992. _vab.subVectors( b, a );
  4993. _vac.subVectors( c, a );
  4994. _vap.subVectors( p, a );
  4995. const d1 = _vab.dot( _vap );
  4996. const d2 = _vac.dot( _vap );
  4997. if ( d1 <= 0 && d2 <= 0 ) {
  4998. // vertex region of A; barycentric coords (1, 0, 0)
  4999. return target.copy( a );
  5000. }
  5001. _vbp.subVectors( p, b );
  5002. const d3 = _vab.dot( _vbp );
  5003. const d4 = _vac.dot( _vbp );
  5004. if ( d3 >= 0 && d4 <= d3 ) {
  5005. // vertex region of B; barycentric coords (0, 1, 0)
  5006. return target.copy( b );
  5007. }
  5008. const vc = d1 * d4 - d3 * d2;
  5009. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5010. v = d1 / ( d1 - d3 );
  5011. // edge region of AB; barycentric coords (1-v, v, 0)
  5012. return target.copy( a ).addScaledVector( _vab, v );
  5013. }
  5014. _vcp.subVectors( p, c );
  5015. const d5 = _vab.dot( _vcp );
  5016. const d6 = _vac.dot( _vcp );
  5017. if ( d6 >= 0 && d5 <= d6 ) {
  5018. // vertex region of C; barycentric coords (0, 0, 1)
  5019. return target.copy( c );
  5020. }
  5021. const vb = d5 * d2 - d1 * d6;
  5022. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5023. w = d2 / ( d2 - d6 );
  5024. // edge region of AC; barycentric coords (1-w, 0, w)
  5025. return target.copy( a ).addScaledVector( _vac, w );
  5026. }
  5027. const va = d3 * d6 - d5 * d4;
  5028. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5029. _vbc.subVectors( c, b );
  5030. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5031. // edge region of BC; barycentric coords (0, 1-w, w)
  5032. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5033. }
  5034. // face region
  5035. const denom = 1 / ( va + vb + vc );
  5036. // u = va * denom
  5037. v = vb * denom;
  5038. w = vc * denom;
  5039. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5040. }
  5041. equals( triangle ) {
  5042. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5043. }
  5044. }
  5045. let _materialId = 0;
  5046. class Material extends EventDispatcher {
  5047. constructor() {
  5048. super();
  5049. this.isMaterial = true;
  5050. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5051. this.uuid = generateUUID();
  5052. this.name = '';
  5053. this.type = 'Material';
  5054. this.blending = NormalBlending;
  5055. this.side = FrontSide;
  5056. this.vertexColors = false;
  5057. this.opacity = 1;
  5058. this.transparent = false;
  5059. this.alphaHash = false;
  5060. this.blendSrc = SrcAlphaFactor;
  5061. this.blendDst = OneMinusSrcAlphaFactor;
  5062. this.blendEquation = AddEquation;
  5063. this.blendSrcAlpha = null;
  5064. this.blendDstAlpha = null;
  5065. this.blendEquationAlpha = null;
  5066. this.depthFunc = LessEqualDepth;
  5067. this.depthTest = true;
  5068. this.depthWrite = true;
  5069. this.stencilWriteMask = 0xff;
  5070. this.stencilFunc = AlwaysStencilFunc;
  5071. this.stencilRef = 0;
  5072. this.stencilFuncMask = 0xff;
  5073. this.stencilFail = KeepStencilOp;
  5074. this.stencilZFail = KeepStencilOp;
  5075. this.stencilZPass = KeepStencilOp;
  5076. this.stencilWrite = false;
  5077. this.clippingPlanes = null;
  5078. this.clipIntersection = false;
  5079. this.clipShadows = false;
  5080. this.shadowSide = null;
  5081. this.colorWrite = true;
  5082. this.precision = null; // override the renderer's default precision for this material
  5083. this.polygonOffset = false;
  5084. this.polygonOffsetFactor = 0;
  5085. this.polygonOffsetUnits = 0;
  5086. this.dithering = false;
  5087. this.alphaToCoverage = false;
  5088. this.premultipliedAlpha = false;
  5089. this.forceSinglePass = false;
  5090. this.visible = true;
  5091. this.toneMapped = true;
  5092. this.userData = {};
  5093. this.version = 0;
  5094. this._alphaTest = 0;
  5095. }
  5096. get alphaTest() {
  5097. return this._alphaTest;
  5098. }
  5099. set alphaTest( value ) {
  5100. if ( this._alphaTest > 0 !== value > 0 ) {
  5101. this.version ++;
  5102. }
  5103. this._alphaTest = value;
  5104. }
  5105. onBuild( /* shaderobject, renderer */ ) {}
  5106. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5107. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5108. customProgramCacheKey() {
  5109. return this.onBeforeCompile.toString();
  5110. }
  5111. setValues( values ) {
  5112. if ( values === undefined ) return;
  5113. for ( const key in values ) {
  5114. const newValue = values[ key ];
  5115. if ( newValue === undefined ) {
  5116. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5117. continue;
  5118. }
  5119. const currentValue = this[ key ];
  5120. if ( currentValue === undefined ) {
  5121. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5122. continue;
  5123. }
  5124. if ( currentValue && currentValue.isColor ) {
  5125. currentValue.set( newValue );
  5126. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5127. currentValue.copy( newValue );
  5128. } else {
  5129. this[ key ] = newValue;
  5130. }
  5131. }
  5132. }
  5133. toJSON( meta ) {
  5134. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5135. if ( isRootObject ) {
  5136. meta = {
  5137. textures: {},
  5138. images: {}
  5139. };
  5140. }
  5141. const data = {
  5142. metadata: {
  5143. version: 4.6,
  5144. type: 'Material',
  5145. generator: 'Material.toJSON'
  5146. }
  5147. };
  5148. // standard Material serialization
  5149. data.uuid = this.uuid;
  5150. data.type = this.type;
  5151. if ( this.name !== '' ) data.name = this.name;
  5152. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5153. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5154. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5155. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5156. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5157. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5158. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5159. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5160. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5161. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5162. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5163. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5164. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5165. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5166. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5167. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5168. }
  5169. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5170. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5171. }
  5172. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5173. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5174. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5175. }
  5176. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5177. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5178. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5179. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5180. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5181. }
  5182. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5183. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5184. }
  5185. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5186. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5187. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5188. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5189. }
  5190. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5191. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5192. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5193. if ( this.lightMap && this.lightMap.isTexture ) {
  5194. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5195. data.lightMapIntensity = this.lightMapIntensity;
  5196. }
  5197. if ( this.aoMap && this.aoMap.isTexture ) {
  5198. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5199. data.aoMapIntensity = this.aoMapIntensity;
  5200. }
  5201. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5202. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5203. data.bumpScale = this.bumpScale;
  5204. }
  5205. if ( this.normalMap && this.normalMap.isTexture ) {
  5206. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5207. data.normalMapType = this.normalMapType;
  5208. data.normalScale = this.normalScale.toArray();
  5209. }
  5210. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5211. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5212. data.displacementScale = this.displacementScale;
  5213. data.displacementBias = this.displacementBias;
  5214. }
  5215. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5216. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5217. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5218. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5219. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5220. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5221. if ( this.envMap && this.envMap.isTexture ) {
  5222. data.envMap = this.envMap.toJSON( meta ).uuid;
  5223. if ( this.combine !== undefined ) data.combine = this.combine;
  5224. }
  5225. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5226. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5227. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5228. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5229. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5230. }
  5231. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5232. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5233. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5234. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5235. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5236. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5237. if ( this.size !== undefined ) data.size = this.size;
  5238. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5239. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5240. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5241. if ( this.side !== FrontSide ) data.side = this.side;
  5242. if ( this.vertexColors === true ) data.vertexColors = true;
  5243. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5244. if ( this.transparent === true ) data.transparent = true;
  5245. data.depthFunc = this.depthFunc;
  5246. data.depthTest = this.depthTest;
  5247. data.depthWrite = this.depthWrite;
  5248. data.colorWrite = this.colorWrite;
  5249. data.stencilWrite = this.stencilWrite;
  5250. data.stencilWriteMask = this.stencilWriteMask;
  5251. data.stencilFunc = this.stencilFunc;
  5252. data.stencilRef = this.stencilRef;
  5253. data.stencilFuncMask = this.stencilFuncMask;
  5254. data.stencilFail = this.stencilFail;
  5255. data.stencilZFail = this.stencilZFail;
  5256. data.stencilZPass = this.stencilZPass;
  5257. // rotation (SpriteMaterial)
  5258. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5259. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5260. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5261. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5262. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5263. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5264. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5265. if ( this.scale !== undefined ) data.scale = this.scale;
  5266. if ( this.dithering === true ) data.dithering = true;
  5267. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5268. if ( this.alphaHash === true ) data.alphaHash = true;
  5269. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5270. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5271. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5272. if ( this.wireframe === true ) data.wireframe = true;
  5273. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5274. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5275. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5276. if ( this.flatShading === true ) data.flatShading = true;
  5277. if ( this.visible === false ) data.visible = false;
  5278. if ( this.toneMapped === false ) data.toneMapped = false;
  5279. if ( this.fog === false ) data.fog = false;
  5280. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5281. // TODO: Copied from Object3D.toJSON
  5282. function extractFromCache( cache ) {
  5283. const values = [];
  5284. for ( const key in cache ) {
  5285. const data = cache[ key ];
  5286. delete data.metadata;
  5287. values.push( data );
  5288. }
  5289. return values;
  5290. }
  5291. if ( isRootObject ) {
  5292. const textures = extractFromCache( meta.textures );
  5293. const images = extractFromCache( meta.images );
  5294. if ( textures.length > 0 ) data.textures = textures;
  5295. if ( images.length > 0 ) data.images = images;
  5296. }
  5297. return data;
  5298. }
  5299. clone() {
  5300. return new this.constructor().copy( this );
  5301. }
  5302. copy( source ) {
  5303. this.name = source.name;
  5304. this.blending = source.blending;
  5305. this.side = source.side;
  5306. this.vertexColors = source.vertexColors;
  5307. this.opacity = source.opacity;
  5308. this.transparent = source.transparent;
  5309. this.blendSrc = source.blendSrc;
  5310. this.blendDst = source.blendDst;
  5311. this.blendEquation = source.blendEquation;
  5312. this.blendSrcAlpha = source.blendSrcAlpha;
  5313. this.blendDstAlpha = source.blendDstAlpha;
  5314. this.blendEquationAlpha = source.blendEquationAlpha;
  5315. this.depthFunc = source.depthFunc;
  5316. this.depthTest = source.depthTest;
  5317. this.depthWrite = source.depthWrite;
  5318. this.stencilWriteMask = source.stencilWriteMask;
  5319. this.stencilFunc = source.stencilFunc;
  5320. this.stencilRef = source.stencilRef;
  5321. this.stencilFuncMask = source.stencilFuncMask;
  5322. this.stencilFail = source.stencilFail;
  5323. this.stencilZFail = source.stencilZFail;
  5324. this.stencilZPass = source.stencilZPass;
  5325. this.stencilWrite = source.stencilWrite;
  5326. const srcPlanes = source.clippingPlanes;
  5327. let dstPlanes = null;
  5328. if ( srcPlanes !== null ) {
  5329. const n = srcPlanes.length;
  5330. dstPlanes = new Array( n );
  5331. for ( let i = 0; i !== n; ++ i ) {
  5332. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5333. }
  5334. }
  5335. this.clippingPlanes = dstPlanes;
  5336. this.clipIntersection = source.clipIntersection;
  5337. this.clipShadows = source.clipShadows;
  5338. this.shadowSide = source.shadowSide;
  5339. this.colorWrite = source.colorWrite;
  5340. this.precision = source.precision;
  5341. this.polygonOffset = source.polygonOffset;
  5342. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5343. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5344. this.dithering = source.dithering;
  5345. this.alphaTest = source.alphaTest;
  5346. this.alphaHash = source.alphaHash;
  5347. this.alphaToCoverage = source.alphaToCoverage;
  5348. this.premultipliedAlpha = source.premultipliedAlpha;
  5349. this.forceSinglePass = source.forceSinglePass;
  5350. this.visible = source.visible;
  5351. this.toneMapped = source.toneMapped;
  5352. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5353. return this;
  5354. }
  5355. dispose() {
  5356. this.dispatchEvent( { type: 'dispose' } );
  5357. }
  5358. set needsUpdate( value ) {
  5359. if ( value === true ) this.version ++;
  5360. }
  5361. }
  5362. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5363. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5364. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5365. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5366. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5367. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5368. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5369. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5370. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5371. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5372. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5373. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5374. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5375. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5376. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5377. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5378. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5379. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5380. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5381. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5382. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5383. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5384. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5385. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5386. const _hslA = { h: 0, s: 0, l: 0 };
  5387. const _hslB = { h: 0, s: 0, l: 0 };
  5388. function hue2rgb( p, q, t ) {
  5389. if ( t < 0 ) t += 1;
  5390. if ( t > 1 ) t -= 1;
  5391. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5392. if ( t < 1 / 2 ) return q;
  5393. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5394. return p;
  5395. }
  5396. class Color {
  5397. constructor( r, g, b ) {
  5398. this.isColor = true;
  5399. this.r = 1;
  5400. this.g = 1;
  5401. this.b = 1;
  5402. return this.set( r, g, b );
  5403. }
  5404. set( r, g, b ) {
  5405. if ( g === undefined && b === undefined ) {
  5406. // r is THREE.Color, hex or string
  5407. const value = r;
  5408. if ( value && value.isColor ) {
  5409. this.copy( value );
  5410. } else if ( typeof value === 'number' ) {
  5411. this.setHex( value );
  5412. } else if ( typeof value === 'string' ) {
  5413. this.setStyle( value );
  5414. }
  5415. } else {
  5416. this.setRGB( r, g, b );
  5417. }
  5418. return this;
  5419. }
  5420. setScalar( scalar ) {
  5421. this.r = scalar;
  5422. this.g = scalar;
  5423. this.b = scalar;
  5424. return this;
  5425. }
  5426. setHex( hex, colorSpace = SRGBColorSpace ) {
  5427. hex = Math.floor( hex );
  5428. this.r = ( hex >> 16 & 255 ) / 255;
  5429. this.g = ( hex >> 8 & 255 ) / 255;
  5430. this.b = ( hex & 255 ) / 255;
  5431. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5432. return this;
  5433. }
  5434. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5435. this.r = r;
  5436. this.g = g;
  5437. this.b = b;
  5438. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5439. return this;
  5440. }
  5441. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5442. // h,s,l ranges are in 0.0 - 1.0
  5443. h = euclideanModulo( h, 1 );
  5444. s = clamp( s, 0, 1 );
  5445. l = clamp( l, 0, 1 );
  5446. if ( s === 0 ) {
  5447. this.r = this.g = this.b = l;
  5448. } else {
  5449. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5450. const q = ( 2 * l ) - p;
  5451. this.r = hue2rgb( q, p, h + 1 / 3 );
  5452. this.g = hue2rgb( q, p, h );
  5453. this.b = hue2rgb( q, p, h - 1 / 3 );
  5454. }
  5455. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5456. return this;
  5457. }
  5458. setStyle( style, colorSpace = SRGBColorSpace ) {
  5459. function handleAlpha( string ) {
  5460. if ( string === undefined ) return;
  5461. if ( parseFloat( string ) < 1 ) {
  5462. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5463. }
  5464. }
  5465. let m;
  5466. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5467. // rgb / hsl
  5468. let color;
  5469. const name = m[ 1 ];
  5470. const components = m[ 2 ];
  5471. switch ( name ) {
  5472. case 'rgb':
  5473. case 'rgba':
  5474. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5475. // rgb(255,0,0) rgba(255,0,0,0.5)
  5476. handleAlpha( color[ 4 ] );
  5477. return this.setRGB(
  5478. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5479. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5480. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5481. colorSpace
  5482. );
  5483. }
  5484. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5485. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5486. handleAlpha( color[ 4 ] );
  5487. return this.setRGB(
  5488. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5489. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5490. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5491. colorSpace
  5492. );
  5493. }
  5494. break;
  5495. case 'hsl':
  5496. case 'hsla':
  5497. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5498. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5499. handleAlpha( color[ 4 ] );
  5500. return this.setHSL(
  5501. parseFloat( color[ 1 ] ) / 360,
  5502. parseFloat( color[ 2 ] ) / 100,
  5503. parseFloat( color[ 3 ] ) / 100,
  5504. colorSpace
  5505. );
  5506. }
  5507. break;
  5508. default:
  5509. console.warn( 'THREE.Color: Unknown color model ' + style );
  5510. }
  5511. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5512. // hex color
  5513. const hex = m[ 1 ];
  5514. const size = hex.length;
  5515. if ( size === 3 ) {
  5516. // #ff0
  5517. return this.setRGB(
  5518. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5519. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5520. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5521. colorSpace
  5522. );
  5523. } else if ( size === 6 ) {
  5524. // #ff0000
  5525. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5526. } else {
  5527. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5528. }
  5529. } else if ( style && style.length > 0 ) {
  5530. return this.setColorName( style, colorSpace );
  5531. }
  5532. return this;
  5533. }
  5534. setColorName( style, colorSpace = SRGBColorSpace ) {
  5535. // color keywords
  5536. const hex = _colorKeywords[ style.toLowerCase() ];
  5537. if ( hex !== undefined ) {
  5538. // red
  5539. this.setHex( hex, colorSpace );
  5540. } else {
  5541. // unknown color
  5542. console.warn( 'THREE.Color: Unknown color ' + style );
  5543. }
  5544. return this;
  5545. }
  5546. clone() {
  5547. return new this.constructor( this.r, this.g, this.b );
  5548. }
  5549. copy( color ) {
  5550. this.r = color.r;
  5551. this.g = color.g;
  5552. this.b = color.b;
  5553. return this;
  5554. }
  5555. copySRGBToLinear( color ) {
  5556. this.r = SRGBToLinear( color.r );
  5557. this.g = SRGBToLinear( color.g );
  5558. this.b = SRGBToLinear( color.b );
  5559. return this;
  5560. }
  5561. copyLinearToSRGB( color ) {
  5562. this.r = LinearToSRGB( color.r );
  5563. this.g = LinearToSRGB( color.g );
  5564. this.b = LinearToSRGB( color.b );
  5565. return this;
  5566. }
  5567. convertSRGBToLinear() {
  5568. this.copySRGBToLinear( this );
  5569. return this;
  5570. }
  5571. convertLinearToSRGB() {
  5572. this.copyLinearToSRGB( this );
  5573. return this;
  5574. }
  5575. getHex( colorSpace = SRGBColorSpace ) {
  5576. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5577. 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 ) );
  5578. }
  5579. getHexString( colorSpace = SRGBColorSpace ) {
  5580. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5581. }
  5582. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5583. // h,s,l ranges are in 0.0 - 1.0
  5584. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5585. const r = _color.r, g = _color.g, b = _color.b;
  5586. const max = Math.max( r, g, b );
  5587. const min = Math.min( r, g, b );
  5588. let hue, saturation;
  5589. const lightness = ( min + max ) / 2.0;
  5590. if ( min === max ) {
  5591. hue = 0;
  5592. saturation = 0;
  5593. } else {
  5594. const delta = max - min;
  5595. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5596. switch ( max ) {
  5597. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5598. case g: hue = ( b - r ) / delta + 2; break;
  5599. case b: hue = ( r - g ) / delta + 4; break;
  5600. }
  5601. hue /= 6;
  5602. }
  5603. target.h = hue;
  5604. target.s = saturation;
  5605. target.l = lightness;
  5606. return target;
  5607. }
  5608. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5609. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5610. target.r = _color.r;
  5611. target.g = _color.g;
  5612. target.b = _color.b;
  5613. return target;
  5614. }
  5615. getStyle( colorSpace = SRGBColorSpace ) {
  5616. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5617. const r = _color.r, g = _color.g, b = _color.b;
  5618. if ( colorSpace !== SRGBColorSpace ) {
  5619. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5620. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5621. }
  5622. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5623. }
  5624. offsetHSL( h, s, l ) {
  5625. this.getHSL( _hslA );
  5626. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5627. }
  5628. add( color ) {
  5629. this.r += color.r;
  5630. this.g += color.g;
  5631. this.b += color.b;
  5632. return this;
  5633. }
  5634. addColors( color1, color2 ) {
  5635. this.r = color1.r + color2.r;
  5636. this.g = color1.g + color2.g;
  5637. this.b = color1.b + color2.b;
  5638. return this;
  5639. }
  5640. addScalar( s ) {
  5641. this.r += s;
  5642. this.g += s;
  5643. this.b += s;
  5644. return this;
  5645. }
  5646. sub( color ) {
  5647. this.r = Math.max( 0, this.r - color.r );
  5648. this.g = Math.max( 0, this.g - color.g );
  5649. this.b = Math.max( 0, this.b - color.b );
  5650. return this;
  5651. }
  5652. multiply( color ) {
  5653. this.r *= color.r;
  5654. this.g *= color.g;
  5655. this.b *= color.b;
  5656. return this;
  5657. }
  5658. multiplyScalar( s ) {
  5659. this.r *= s;
  5660. this.g *= s;
  5661. this.b *= s;
  5662. return this;
  5663. }
  5664. lerp( color, alpha ) {
  5665. this.r += ( color.r - this.r ) * alpha;
  5666. this.g += ( color.g - this.g ) * alpha;
  5667. this.b += ( color.b - this.b ) * alpha;
  5668. return this;
  5669. }
  5670. lerpColors( color1, color2, alpha ) {
  5671. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5672. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5673. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5674. return this;
  5675. }
  5676. lerpHSL( color, alpha ) {
  5677. this.getHSL( _hslA );
  5678. color.getHSL( _hslB );
  5679. const h = lerp( _hslA.h, _hslB.h, alpha );
  5680. const s = lerp( _hslA.s, _hslB.s, alpha );
  5681. const l = lerp( _hslA.l, _hslB.l, alpha );
  5682. this.setHSL( h, s, l );
  5683. return this;
  5684. }
  5685. setFromVector3( v ) {
  5686. this.r = v.x;
  5687. this.g = v.y;
  5688. this.b = v.z;
  5689. return this;
  5690. }
  5691. applyMatrix3( m ) {
  5692. const r = this.r, g = this.g, b = this.b;
  5693. const e = m.elements;
  5694. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5695. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5696. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5697. return this;
  5698. }
  5699. equals( c ) {
  5700. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5701. }
  5702. fromArray( array, offset = 0 ) {
  5703. this.r = array[ offset ];
  5704. this.g = array[ offset + 1 ];
  5705. this.b = array[ offset + 2 ];
  5706. return this;
  5707. }
  5708. toArray( array = [], offset = 0 ) {
  5709. array[ offset ] = this.r;
  5710. array[ offset + 1 ] = this.g;
  5711. array[ offset + 2 ] = this.b;
  5712. return array;
  5713. }
  5714. fromBufferAttribute( attribute, index ) {
  5715. this.r = attribute.getX( index );
  5716. this.g = attribute.getY( index );
  5717. this.b = attribute.getZ( index );
  5718. return this;
  5719. }
  5720. toJSON() {
  5721. return this.getHex();
  5722. }
  5723. *[ Symbol.iterator ]() {
  5724. yield this.r;
  5725. yield this.g;
  5726. yield this.b;
  5727. }
  5728. }
  5729. const _color = /*@__PURE__*/ new Color();
  5730. Color.NAMES = _colorKeywords;
  5731. class MeshBasicMaterial extends Material {
  5732. constructor( parameters ) {
  5733. super();
  5734. this.isMeshBasicMaterial = true;
  5735. this.type = 'MeshBasicMaterial';
  5736. this.color = new Color( 0xffffff ); // emissive
  5737. this.map = null;
  5738. this.lightMap = null;
  5739. this.lightMapIntensity = 1.0;
  5740. this.aoMap = null;
  5741. this.aoMapIntensity = 1.0;
  5742. this.specularMap = null;
  5743. this.alphaMap = null;
  5744. this.envMap = null;
  5745. this.combine = MultiplyOperation;
  5746. this.reflectivity = 1;
  5747. this.refractionRatio = 0.98;
  5748. this.wireframe = false;
  5749. this.wireframeLinewidth = 1;
  5750. this.wireframeLinecap = 'round';
  5751. this.wireframeLinejoin = 'round';
  5752. this.fog = true;
  5753. this.setValues( parameters );
  5754. }
  5755. copy( source ) {
  5756. super.copy( source );
  5757. this.color.copy( source.color );
  5758. this.map = source.map;
  5759. this.lightMap = source.lightMap;
  5760. this.lightMapIntensity = source.lightMapIntensity;
  5761. this.aoMap = source.aoMap;
  5762. this.aoMapIntensity = source.aoMapIntensity;
  5763. this.specularMap = source.specularMap;
  5764. this.alphaMap = source.alphaMap;
  5765. this.envMap = source.envMap;
  5766. this.combine = source.combine;
  5767. this.reflectivity = source.reflectivity;
  5768. this.refractionRatio = source.refractionRatio;
  5769. this.wireframe = source.wireframe;
  5770. this.wireframeLinewidth = source.wireframeLinewidth;
  5771. this.wireframeLinecap = source.wireframeLinecap;
  5772. this.wireframeLinejoin = source.wireframeLinejoin;
  5773. this.fog = source.fog;
  5774. return this;
  5775. }
  5776. }
  5777. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5778. const _tables = /*@__PURE__*/ _generateTables();
  5779. function _generateTables() {
  5780. // float32 to float16 helpers
  5781. const buffer = new ArrayBuffer( 4 );
  5782. const floatView = new Float32Array( buffer );
  5783. const uint32View = new Uint32Array( buffer );
  5784. const baseTable = new Uint32Array( 512 );
  5785. const shiftTable = new Uint32Array( 512 );
  5786. for ( let i = 0; i < 256; ++ i ) {
  5787. const e = i - 127;
  5788. // very small number (0, -0)
  5789. if ( e < - 27 ) {
  5790. baseTable[ i ] = 0x0000;
  5791. baseTable[ i | 0x100 ] = 0x8000;
  5792. shiftTable[ i ] = 24;
  5793. shiftTable[ i | 0x100 ] = 24;
  5794. // small number (denorm)
  5795. } else if ( e < - 14 ) {
  5796. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5797. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5798. shiftTable[ i ] = - e - 1;
  5799. shiftTable[ i | 0x100 ] = - e - 1;
  5800. // normal number
  5801. } else if ( e <= 15 ) {
  5802. baseTable[ i ] = ( e + 15 ) << 10;
  5803. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5804. shiftTable[ i ] = 13;
  5805. shiftTable[ i | 0x100 ] = 13;
  5806. // large number (Infinity, -Infinity)
  5807. } else if ( e < 128 ) {
  5808. baseTable[ i ] = 0x7c00;
  5809. baseTable[ i | 0x100 ] = 0xfc00;
  5810. shiftTable[ i ] = 24;
  5811. shiftTable[ i | 0x100 ] = 24;
  5812. // stay (NaN, Infinity, -Infinity)
  5813. } else {
  5814. baseTable[ i ] = 0x7c00;
  5815. baseTable[ i | 0x100 ] = 0xfc00;
  5816. shiftTable[ i ] = 13;
  5817. shiftTable[ i | 0x100 ] = 13;
  5818. }
  5819. }
  5820. // float16 to float32 helpers
  5821. const mantissaTable = new Uint32Array( 2048 );
  5822. const exponentTable = new Uint32Array( 64 );
  5823. const offsetTable = new Uint32Array( 64 );
  5824. for ( let i = 1; i < 1024; ++ i ) {
  5825. let m = i << 13; // zero pad mantissa bits
  5826. let e = 0; // zero exponent
  5827. // normalized
  5828. while ( ( m & 0x00800000 ) === 0 ) {
  5829. m <<= 1;
  5830. e -= 0x00800000; // decrement exponent
  5831. }
  5832. m &= ~ 0x00800000; // clear leading 1 bit
  5833. e += 0x38800000; // adjust bias
  5834. mantissaTable[ i ] = m | e;
  5835. }
  5836. for ( let i = 1024; i < 2048; ++ i ) {
  5837. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5838. }
  5839. for ( let i = 1; i < 31; ++ i ) {
  5840. exponentTable[ i ] = i << 23;
  5841. }
  5842. exponentTable[ 31 ] = 0x47800000;
  5843. exponentTable[ 32 ] = 0x80000000;
  5844. for ( let i = 33; i < 63; ++ i ) {
  5845. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5846. }
  5847. exponentTable[ 63 ] = 0xc7800000;
  5848. for ( let i = 1; i < 64; ++ i ) {
  5849. if ( i !== 32 ) {
  5850. offsetTable[ i ] = 1024;
  5851. }
  5852. }
  5853. return {
  5854. floatView: floatView,
  5855. uint32View: uint32View,
  5856. baseTable: baseTable,
  5857. shiftTable: shiftTable,
  5858. mantissaTable: mantissaTable,
  5859. exponentTable: exponentTable,
  5860. offsetTable: offsetTable
  5861. };
  5862. }
  5863. // float32 to float16
  5864. function toHalfFloat( val ) {
  5865. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5866. val = clamp( val, - 65504, 65504 );
  5867. _tables.floatView[ 0 ] = val;
  5868. const f = _tables.uint32View[ 0 ];
  5869. const e = ( f >> 23 ) & 0x1ff;
  5870. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5871. }
  5872. // float16 to float32
  5873. function fromHalfFloat( val ) {
  5874. const m = val >> 10;
  5875. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5876. return _tables.floatView[ 0 ];
  5877. }
  5878. const DataUtils = {
  5879. toHalfFloat: toHalfFloat,
  5880. fromHalfFloat: fromHalfFloat,
  5881. };
  5882. const _vector$8 = /*@__PURE__*/ new Vector3();
  5883. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5884. class BufferAttribute {
  5885. constructor( array, itemSize, normalized = false ) {
  5886. if ( Array.isArray( array ) ) {
  5887. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5888. }
  5889. this.isBufferAttribute = true;
  5890. this.name = '';
  5891. this.array = array;
  5892. this.itemSize = itemSize;
  5893. this.count = array !== undefined ? array.length / itemSize : 0;
  5894. this.normalized = normalized;
  5895. this.usage = StaticDrawUsage;
  5896. this.updateRange = { offset: 0, count: - 1 };
  5897. this.gpuType = FloatType;
  5898. this.version = 0;
  5899. }
  5900. onUploadCallback() {}
  5901. set needsUpdate( value ) {
  5902. if ( value === true ) this.version ++;
  5903. }
  5904. setUsage( value ) {
  5905. this.usage = value;
  5906. return this;
  5907. }
  5908. copy( source ) {
  5909. this.name = source.name;
  5910. this.array = new source.array.constructor( source.array );
  5911. this.itemSize = source.itemSize;
  5912. this.count = source.count;
  5913. this.normalized = source.normalized;
  5914. this.usage = source.usage;
  5915. this.gpuType = source.gpuType;
  5916. return this;
  5917. }
  5918. copyAt( index1, attribute, index2 ) {
  5919. index1 *= this.itemSize;
  5920. index2 *= attribute.itemSize;
  5921. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5922. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5923. }
  5924. return this;
  5925. }
  5926. copyArray( array ) {
  5927. this.array.set( array );
  5928. return this;
  5929. }
  5930. applyMatrix3( m ) {
  5931. if ( this.itemSize === 2 ) {
  5932. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5933. _vector2$1.fromBufferAttribute( this, i );
  5934. _vector2$1.applyMatrix3( m );
  5935. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5936. }
  5937. } else if ( this.itemSize === 3 ) {
  5938. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5939. _vector$8.fromBufferAttribute( this, i );
  5940. _vector$8.applyMatrix3( m );
  5941. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5942. }
  5943. }
  5944. return this;
  5945. }
  5946. applyMatrix4( m ) {
  5947. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5948. _vector$8.fromBufferAttribute( this, i );
  5949. _vector$8.applyMatrix4( m );
  5950. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5951. }
  5952. return this;
  5953. }
  5954. applyNormalMatrix( m ) {
  5955. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5956. _vector$8.fromBufferAttribute( this, i );
  5957. _vector$8.applyNormalMatrix( m );
  5958. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5959. }
  5960. return this;
  5961. }
  5962. transformDirection( m ) {
  5963. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5964. _vector$8.fromBufferAttribute( this, i );
  5965. _vector$8.transformDirection( m );
  5966. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5967. }
  5968. return this;
  5969. }
  5970. set( value, offset = 0 ) {
  5971. // Matching BufferAttribute constructor, do not normalize the array.
  5972. this.array.set( value, offset );
  5973. return this;
  5974. }
  5975. getComponent( index, component ) {
  5976. let value = this.array[ index * this.itemSize + component ];
  5977. if ( this.normalized ) value = denormalize( value, this.array );
  5978. return value;
  5979. }
  5980. setComponent( index, component, value ) {
  5981. if ( this.normalized ) value = normalize( value, this.array );
  5982. this.array[ index * this.itemSize + component ] = value;
  5983. return this;
  5984. }
  5985. getX( index ) {
  5986. let x = this.array[ index * this.itemSize ];
  5987. if ( this.normalized ) x = denormalize( x, this.array );
  5988. return x;
  5989. }
  5990. setX( index, x ) {
  5991. if ( this.normalized ) x = normalize( x, this.array );
  5992. this.array[ index * this.itemSize ] = x;
  5993. return this;
  5994. }
  5995. getY( index ) {
  5996. let y = this.array[ index * this.itemSize + 1 ];
  5997. if ( this.normalized ) y = denormalize( y, this.array );
  5998. return y;
  5999. }
  6000. setY( index, y ) {
  6001. if ( this.normalized ) y = normalize( y, this.array );
  6002. this.array[ index * this.itemSize + 1 ] = y;
  6003. return this;
  6004. }
  6005. getZ( index ) {
  6006. let z = this.array[ index * this.itemSize + 2 ];
  6007. if ( this.normalized ) z = denormalize( z, this.array );
  6008. return z;
  6009. }
  6010. setZ( index, z ) {
  6011. if ( this.normalized ) z = normalize( z, this.array );
  6012. this.array[ index * this.itemSize + 2 ] = z;
  6013. return this;
  6014. }
  6015. getW( index ) {
  6016. let w = this.array[ index * this.itemSize + 3 ];
  6017. if ( this.normalized ) w = denormalize( w, this.array );
  6018. return w;
  6019. }
  6020. setW( index, w ) {
  6021. if ( this.normalized ) w = normalize( w, this.array );
  6022. this.array[ index * this.itemSize + 3 ] = w;
  6023. return this;
  6024. }
  6025. setXY( index, x, y ) {
  6026. index *= this.itemSize;
  6027. if ( this.normalized ) {
  6028. x = normalize( x, this.array );
  6029. y = normalize( y, this.array );
  6030. }
  6031. this.array[ index + 0 ] = x;
  6032. this.array[ index + 1 ] = y;
  6033. return this;
  6034. }
  6035. setXYZ( index, x, y, z ) {
  6036. index *= this.itemSize;
  6037. if ( this.normalized ) {
  6038. x = normalize( x, this.array );
  6039. y = normalize( y, this.array );
  6040. z = normalize( z, this.array );
  6041. }
  6042. this.array[ index + 0 ] = x;
  6043. this.array[ index + 1 ] = y;
  6044. this.array[ index + 2 ] = z;
  6045. return this;
  6046. }
  6047. setXYZW( index, x, y, z, w ) {
  6048. index *= this.itemSize;
  6049. if ( this.normalized ) {
  6050. x = normalize( x, this.array );
  6051. y = normalize( y, this.array );
  6052. z = normalize( z, this.array );
  6053. w = normalize( w, this.array );
  6054. }
  6055. this.array[ index + 0 ] = x;
  6056. this.array[ index + 1 ] = y;
  6057. this.array[ index + 2 ] = z;
  6058. this.array[ index + 3 ] = w;
  6059. return this;
  6060. }
  6061. onUpload( callback ) {
  6062. this.onUploadCallback = callback;
  6063. return this;
  6064. }
  6065. clone() {
  6066. return new this.constructor( this.array, this.itemSize ).copy( this );
  6067. }
  6068. toJSON() {
  6069. const data = {
  6070. itemSize: this.itemSize,
  6071. type: this.array.constructor.name,
  6072. array: Array.from( this.array ),
  6073. normalized: this.normalized
  6074. };
  6075. if ( this.name !== '' ) data.name = this.name;
  6076. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6077. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  6078. return data;
  6079. }
  6080. }
  6081. //
  6082. class Int8BufferAttribute extends BufferAttribute {
  6083. constructor( array, itemSize, normalized ) {
  6084. super( new Int8Array( array ), itemSize, normalized );
  6085. }
  6086. }
  6087. class Uint8BufferAttribute extends BufferAttribute {
  6088. constructor( array, itemSize, normalized ) {
  6089. super( new Uint8Array( array ), itemSize, normalized );
  6090. }
  6091. }
  6092. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6093. constructor( array, itemSize, normalized ) {
  6094. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6095. }
  6096. }
  6097. class Int16BufferAttribute extends BufferAttribute {
  6098. constructor( array, itemSize, normalized ) {
  6099. super( new Int16Array( array ), itemSize, normalized );
  6100. }
  6101. }
  6102. class Uint16BufferAttribute extends BufferAttribute {
  6103. constructor( array, itemSize, normalized ) {
  6104. super( new Uint16Array( array ), itemSize, normalized );
  6105. }
  6106. }
  6107. class Int32BufferAttribute extends BufferAttribute {
  6108. constructor( array, itemSize, normalized ) {
  6109. super( new Int32Array( array ), itemSize, normalized );
  6110. }
  6111. }
  6112. class Uint32BufferAttribute extends BufferAttribute {
  6113. constructor( array, itemSize, normalized ) {
  6114. super( new Uint32Array( array ), itemSize, normalized );
  6115. }
  6116. }
  6117. class Float16BufferAttribute extends BufferAttribute {
  6118. constructor( array, itemSize, normalized ) {
  6119. super( new Uint16Array( array ), itemSize, normalized );
  6120. this.isFloat16BufferAttribute = true;
  6121. }
  6122. getX( index ) {
  6123. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6124. if ( this.normalized ) x = denormalize( x, this.array );
  6125. return x;
  6126. }
  6127. setX( index, x ) {
  6128. if ( this.normalized ) x = normalize( x, this.array );
  6129. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6130. return this;
  6131. }
  6132. getY( index ) {
  6133. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6134. if ( this.normalized ) y = denormalize( y, this.array );
  6135. return y;
  6136. }
  6137. setY( index, y ) {
  6138. if ( this.normalized ) y = normalize( y, this.array );
  6139. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6140. return this;
  6141. }
  6142. getZ( index ) {
  6143. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6144. if ( this.normalized ) z = denormalize( z, this.array );
  6145. return z;
  6146. }
  6147. setZ( index, z ) {
  6148. if ( this.normalized ) z = normalize( z, this.array );
  6149. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6150. return this;
  6151. }
  6152. getW( index ) {
  6153. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6154. if ( this.normalized ) w = denormalize( w, this.array );
  6155. return w;
  6156. }
  6157. setW( index, w ) {
  6158. if ( this.normalized ) w = normalize( w, this.array );
  6159. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6160. return this;
  6161. }
  6162. setXY( index, x, y ) {
  6163. index *= this.itemSize;
  6164. if ( this.normalized ) {
  6165. x = normalize( x, this.array );
  6166. y = normalize( y, this.array );
  6167. }
  6168. this.array[ index + 0 ] = toHalfFloat( x );
  6169. this.array[ index + 1 ] = toHalfFloat( y );
  6170. return this;
  6171. }
  6172. setXYZ( index, x, y, z ) {
  6173. index *= this.itemSize;
  6174. if ( this.normalized ) {
  6175. x = normalize( x, this.array );
  6176. y = normalize( y, this.array );
  6177. z = normalize( z, this.array );
  6178. }
  6179. this.array[ index + 0 ] = toHalfFloat( x );
  6180. this.array[ index + 1 ] = toHalfFloat( y );
  6181. this.array[ index + 2 ] = toHalfFloat( z );
  6182. return this;
  6183. }
  6184. setXYZW( index, x, y, z, w ) {
  6185. index *= this.itemSize;
  6186. if ( this.normalized ) {
  6187. x = normalize( x, this.array );
  6188. y = normalize( y, this.array );
  6189. z = normalize( z, this.array );
  6190. w = normalize( w, this.array );
  6191. }
  6192. this.array[ index + 0 ] = toHalfFloat( x );
  6193. this.array[ index + 1 ] = toHalfFloat( y );
  6194. this.array[ index + 2 ] = toHalfFloat( z );
  6195. this.array[ index + 3 ] = toHalfFloat( w );
  6196. return this;
  6197. }
  6198. }
  6199. class Float32BufferAttribute extends BufferAttribute {
  6200. constructor( array, itemSize, normalized ) {
  6201. super( new Float32Array( array ), itemSize, normalized );
  6202. }
  6203. }
  6204. class Float64BufferAttribute extends BufferAttribute {
  6205. constructor( array, itemSize, normalized ) {
  6206. super( new Float64Array( array ), itemSize, normalized );
  6207. }
  6208. }
  6209. let _id$2 = 0;
  6210. const _m1 = /*@__PURE__*/ new Matrix4();
  6211. const _obj = /*@__PURE__*/ new Object3D();
  6212. const _offset = /*@__PURE__*/ new Vector3();
  6213. const _box$1 = /*@__PURE__*/ new Box3();
  6214. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6215. const _vector$7 = /*@__PURE__*/ new Vector3();
  6216. class BufferGeometry extends EventDispatcher {
  6217. constructor() {
  6218. super();
  6219. this.isBufferGeometry = true;
  6220. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6221. this.uuid = generateUUID();
  6222. this.name = '';
  6223. this.type = 'BufferGeometry';
  6224. this.index = null;
  6225. this.attributes = {};
  6226. this.morphAttributes = {};
  6227. this.morphTargetsRelative = false;
  6228. this.groups = [];
  6229. this.boundingBox = null;
  6230. this.boundingSphere = null;
  6231. this.drawRange = { start: 0, count: Infinity };
  6232. this.userData = {};
  6233. }
  6234. getIndex() {
  6235. return this.index;
  6236. }
  6237. setIndex( index ) {
  6238. if ( Array.isArray( index ) ) {
  6239. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6240. } else {
  6241. this.index = index;
  6242. }
  6243. return this;
  6244. }
  6245. getAttribute( name ) {
  6246. return this.attributes[ name ];
  6247. }
  6248. setAttribute( name, attribute ) {
  6249. this.attributes[ name ] = attribute;
  6250. return this;
  6251. }
  6252. deleteAttribute( name ) {
  6253. delete this.attributes[ name ];
  6254. return this;
  6255. }
  6256. hasAttribute( name ) {
  6257. return this.attributes[ name ] !== undefined;
  6258. }
  6259. addGroup( start, count, materialIndex = 0 ) {
  6260. this.groups.push( {
  6261. start: start,
  6262. count: count,
  6263. materialIndex: materialIndex
  6264. } );
  6265. }
  6266. clearGroups() {
  6267. this.groups = [];
  6268. }
  6269. setDrawRange( start, count ) {
  6270. this.drawRange.start = start;
  6271. this.drawRange.count = count;
  6272. }
  6273. applyMatrix4( matrix ) {
  6274. const position = this.attributes.position;
  6275. if ( position !== undefined ) {
  6276. position.applyMatrix4( matrix );
  6277. position.needsUpdate = true;
  6278. }
  6279. const normal = this.attributes.normal;
  6280. if ( normal !== undefined ) {
  6281. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6282. normal.applyNormalMatrix( normalMatrix );
  6283. normal.needsUpdate = true;
  6284. }
  6285. const tangent = this.attributes.tangent;
  6286. if ( tangent !== undefined ) {
  6287. tangent.transformDirection( matrix );
  6288. tangent.needsUpdate = true;
  6289. }
  6290. if ( this.boundingBox !== null ) {
  6291. this.computeBoundingBox();
  6292. }
  6293. if ( this.boundingSphere !== null ) {
  6294. this.computeBoundingSphere();
  6295. }
  6296. return this;
  6297. }
  6298. applyQuaternion( q ) {
  6299. _m1.makeRotationFromQuaternion( q );
  6300. this.applyMatrix4( _m1 );
  6301. return this;
  6302. }
  6303. rotateX( angle ) {
  6304. // rotate geometry around world x-axis
  6305. _m1.makeRotationX( angle );
  6306. this.applyMatrix4( _m1 );
  6307. return this;
  6308. }
  6309. rotateY( angle ) {
  6310. // rotate geometry around world y-axis
  6311. _m1.makeRotationY( angle );
  6312. this.applyMatrix4( _m1 );
  6313. return this;
  6314. }
  6315. rotateZ( angle ) {
  6316. // rotate geometry around world z-axis
  6317. _m1.makeRotationZ( angle );
  6318. this.applyMatrix4( _m1 );
  6319. return this;
  6320. }
  6321. translate( x, y, z ) {
  6322. // translate geometry
  6323. _m1.makeTranslation( x, y, z );
  6324. this.applyMatrix4( _m1 );
  6325. return this;
  6326. }
  6327. scale( x, y, z ) {
  6328. // scale geometry
  6329. _m1.makeScale( x, y, z );
  6330. this.applyMatrix4( _m1 );
  6331. return this;
  6332. }
  6333. lookAt( vector ) {
  6334. _obj.lookAt( vector );
  6335. _obj.updateMatrix();
  6336. this.applyMatrix4( _obj.matrix );
  6337. return this;
  6338. }
  6339. center() {
  6340. this.computeBoundingBox();
  6341. this.boundingBox.getCenter( _offset ).negate();
  6342. this.translate( _offset.x, _offset.y, _offset.z );
  6343. return this;
  6344. }
  6345. setFromPoints( points ) {
  6346. const position = [];
  6347. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6348. const point = points[ i ];
  6349. position.push( point.x, point.y, point.z || 0 );
  6350. }
  6351. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6352. return this;
  6353. }
  6354. computeBoundingBox() {
  6355. if ( this.boundingBox === null ) {
  6356. this.boundingBox = new Box3();
  6357. }
  6358. const position = this.attributes.position;
  6359. const morphAttributesPosition = this.morphAttributes.position;
  6360. if ( position && position.isGLBufferAttribute ) {
  6361. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6362. this.boundingBox.set(
  6363. new Vector3( - Infinity, - Infinity, - Infinity ),
  6364. new Vector3( + Infinity, + Infinity, + Infinity )
  6365. );
  6366. return;
  6367. }
  6368. if ( position !== undefined ) {
  6369. this.boundingBox.setFromBufferAttribute( position );
  6370. // process morph attributes if present
  6371. if ( morphAttributesPosition ) {
  6372. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6373. const morphAttribute = morphAttributesPosition[ i ];
  6374. _box$1.setFromBufferAttribute( morphAttribute );
  6375. if ( this.morphTargetsRelative ) {
  6376. _vector$7.addVectors( this.boundingBox.min, _box$1.min );
  6377. this.boundingBox.expandByPoint( _vector$7 );
  6378. _vector$7.addVectors( this.boundingBox.max, _box$1.max );
  6379. this.boundingBox.expandByPoint( _vector$7 );
  6380. } else {
  6381. this.boundingBox.expandByPoint( _box$1.min );
  6382. this.boundingBox.expandByPoint( _box$1.max );
  6383. }
  6384. }
  6385. }
  6386. } else {
  6387. this.boundingBox.makeEmpty();
  6388. }
  6389. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6390. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6391. }
  6392. }
  6393. computeBoundingSphere() {
  6394. if ( this.boundingSphere === null ) {
  6395. this.boundingSphere = new Sphere();
  6396. }
  6397. const position = this.attributes.position;
  6398. const morphAttributesPosition = this.morphAttributes.position;
  6399. if ( position && position.isGLBufferAttribute ) {
  6400. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6401. this.boundingSphere.set( new Vector3(), Infinity );
  6402. return;
  6403. }
  6404. if ( position ) {
  6405. // first, find the center of the bounding sphere
  6406. const center = this.boundingSphere.center;
  6407. _box$1.setFromBufferAttribute( position );
  6408. // process morph attributes if present
  6409. if ( morphAttributesPosition ) {
  6410. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6411. const morphAttribute = morphAttributesPosition[ i ];
  6412. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6413. if ( this.morphTargetsRelative ) {
  6414. _vector$7.addVectors( _box$1.min, _boxMorphTargets.min );
  6415. _box$1.expandByPoint( _vector$7 );
  6416. _vector$7.addVectors( _box$1.max, _boxMorphTargets.max );
  6417. _box$1.expandByPoint( _vector$7 );
  6418. } else {
  6419. _box$1.expandByPoint( _boxMorphTargets.min );
  6420. _box$1.expandByPoint( _boxMorphTargets.max );
  6421. }
  6422. }
  6423. }
  6424. _box$1.getCenter( center );
  6425. // second, try to find a boundingSphere with a radius smaller than the
  6426. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6427. let maxRadiusSq = 0;
  6428. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6429. _vector$7.fromBufferAttribute( position, i );
  6430. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6431. }
  6432. // process morph attributes if present
  6433. if ( morphAttributesPosition ) {
  6434. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6435. const morphAttribute = morphAttributesPosition[ i ];
  6436. const morphTargetsRelative = this.morphTargetsRelative;
  6437. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6438. _vector$7.fromBufferAttribute( morphAttribute, j );
  6439. if ( morphTargetsRelative ) {
  6440. _offset.fromBufferAttribute( position, j );
  6441. _vector$7.add( _offset );
  6442. }
  6443. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6444. }
  6445. }
  6446. }
  6447. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6448. if ( isNaN( this.boundingSphere.radius ) ) {
  6449. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6450. }
  6451. }
  6452. }
  6453. computeTangents() {
  6454. const index = this.index;
  6455. const attributes = this.attributes;
  6456. // based on http://www.terathon.com/code/tangent.html
  6457. // (per vertex tangents)
  6458. if ( index === null ||
  6459. attributes.position === undefined ||
  6460. attributes.normal === undefined ||
  6461. attributes.uv === undefined ) {
  6462. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6463. return;
  6464. }
  6465. const indices = index.array;
  6466. const positions = attributes.position.array;
  6467. const normals = attributes.normal.array;
  6468. const uvs = attributes.uv.array;
  6469. const nVertices = positions.length / 3;
  6470. if ( this.hasAttribute( 'tangent' ) === false ) {
  6471. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6472. }
  6473. const tangents = this.getAttribute( 'tangent' ).array;
  6474. const tan1 = [], tan2 = [];
  6475. for ( let i = 0; i < nVertices; i ++ ) {
  6476. tan1[ i ] = new Vector3();
  6477. tan2[ i ] = new Vector3();
  6478. }
  6479. const vA = new Vector3(),
  6480. vB = new Vector3(),
  6481. vC = new Vector3(),
  6482. uvA = new Vector2(),
  6483. uvB = new Vector2(),
  6484. uvC = new Vector2(),
  6485. sdir = new Vector3(),
  6486. tdir = new Vector3();
  6487. function handleTriangle( a, b, c ) {
  6488. vA.fromArray( positions, a * 3 );
  6489. vB.fromArray( positions, b * 3 );
  6490. vC.fromArray( positions, c * 3 );
  6491. uvA.fromArray( uvs, a * 2 );
  6492. uvB.fromArray( uvs, b * 2 );
  6493. uvC.fromArray( uvs, c * 2 );
  6494. vB.sub( vA );
  6495. vC.sub( vA );
  6496. uvB.sub( uvA );
  6497. uvC.sub( uvA );
  6498. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6499. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6500. if ( ! isFinite( r ) ) return;
  6501. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6502. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6503. tan1[ a ].add( sdir );
  6504. tan1[ b ].add( sdir );
  6505. tan1[ c ].add( sdir );
  6506. tan2[ a ].add( tdir );
  6507. tan2[ b ].add( tdir );
  6508. tan2[ c ].add( tdir );
  6509. }
  6510. let groups = this.groups;
  6511. if ( groups.length === 0 ) {
  6512. groups = [ {
  6513. start: 0,
  6514. count: indices.length
  6515. } ];
  6516. }
  6517. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6518. const group = groups[ i ];
  6519. const start = group.start;
  6520. const count = group.count;
  6521. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6522. handleTriangle(
  6523. indices[ j + 0 ],
  6524. indices[ j + 1 ],
  6525. indices[ j + 2 ]
  6526. );
  6527. }
  6528. }
  6529. const tmp = new Vector3(), tmp2 = new Vector3();
  6530. const n = new Vector3(), n2 = new Vector3();
  6531. function handleVertex( v ) {
  6532. n.fromArray( normals, v * 3 );
  6533. n2.copy( n );
  6534. const t = tan1[ v ];
  6535. // Gram-Schmidt orthogonalize
  6536. tmp.copy( t );
  6537. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6538. // Calculate handedness
  6539. tmp2.crossVectors( n2, t );
  6540. const test = tmp2.dot( tan2[ v ] );
  6541. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6542. tangents[ v * 4 ] = tmp.x;
  6543. tangents[ v * 4 + 1 ] = tmp.y;
  6544. tangents[ v * 4 + 2 ] = tmp.z;
  6545. tangents[ v * 4 + 3 ] = w;
  6546. }
  6547. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6548. const group = groups[ i ];
  6549. const start = group.start;
  6550. const count = group.count;
  6551. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6552. handleVertex( indices[ j + 0 ] );
  6553. handleVertex( indices[ j + 1 ] );
  6554. handleVertex( indices[ j + 2 ] );
  6555. }
  6556. }
  6557. }
  6558. computeVertexNormals() {
  6559. const index = this.index;
  6560. const positionAttribute = this.getAttribute( 'position' );
  6561. if ( positionAttribute !== undefined ) {
  6562. let normalAttribute = this.getAttribute( 'normal' );
  6563. if ( normalAttribute === undefined ) {
  6564. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6565. this.setAttribute( 'normal', normalAttribute );
  6566. } else {
  6567. // reset existing normals to zero
  6568. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6569. normalAttribute.setXYZ( i, 0, 0, 0 );
  6570. }
  6571. }
  6572. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6573. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6574. const cb = new Vector3(), ab = new Vector3();
  6575. // indexed elements
  6576. if ( index ) {
  6577. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6578. const vA = index.getX( i + 0 );
  6579. const vB = index.getX( i + 1 );
  6580. const vC = index.getX( i + 2 );
  6581. pA.fromBufferAttribute( positionAttribute, vA );
  6582. pB.fromBufferAttribute( positionAttribute, vB );
  6583. pC.fromBufferAttribute( positionAttribute, vC );
  6584. cb.subVectors( pC, pB );
  6585. ab.subVectors( pA, pB );
  6586. cb.cross( ab );
  6587. nA.fromBufferAttribute( normalAttribute, vA );
  6588. nB.fromBufferAttribute( normalAttribute, vB );
  6589. nC.fromBufferAttribute( normalAttribute, vC );
  6590. nA.add( cb );
  6591. nB.add( cb );
  6592. nC.add( cb );
  6593. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6594. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6595. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6596. }
  6597. } else {
  6598. // non-indexed elements (unconnected triangle soup)
  6599. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6600. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6601. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6602. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6603. cb.subVectors( pC, pB );
  6604. ab.subVectors( pA, pB );
  6605. cb.cross( ab );
  6606. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6607. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6608. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6609. }
  6610. }
  6611. this.normalizeNormals();
  6612. normalAttribute.needsUpdate = true;
  6613. }
  6614. }
  6615. normalizeNormals() {
  6616. const normals = this.attributes.normal;
  6617. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6618. _vector$7.fromBufferAttribute( normals, i );
  6619. _vector$7.normalize();
  6620. normals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  6621. }
  6622. }
  6623. toNonIndexed() {
  6624. function convertBufferAttribute( attribute, indices ) {
  6625. const array = attribute.array;
  6626. const itemSize = attribute.itemSize;
  6627. const normalized = attribute.normalized;
  6628. const array2 = new array.constructor( indices.length * itemSize );
  6629. let index = 0, index2 = 0;
  6630. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6631. if ( attribute.isInterleavedBufferAttribute ) {
  6632. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6633. } else {
  6634. index = indices[ i ] * itemSize;
  6635. }
  6636. for ( let j = 0; j < itemSize; j ++ ) {
  6637. array2[ index2 ++ ] = array[ index ++ ];
  6638. }
  6639. }
  6640. return new BufferAttribute( array2, itemSize, normalized );
  6641. }
  6642. //
  6643. if ( this.index === null ) {
  6644. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6645. return this;
  6646. }
  6647. const geometry2 = new BufferGeometry();
  6648. const indices = this.index.array;
  6649. const attributes = this.attributes;
  6650. // attributes
  6651. for ( const name in attributes ) {
  6652. const attribute = attributes[ name ];
  6653. const newAttribute = convertBufferAttribute( attribute, indices );
  6654. geometry2.setAttribute( name, newAttribute );
  6655. }
  6656. // morph attributes
  6657. const morphAttributes = this.morphAttributes;
  6658. for ( const name in morphAttributes ) {
  6659. const morphArray = [];
  6660. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6661. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6662. const attribute = morphAttribute[ i ];
  6663. const newAttribute = convertBufferAttribute( attribute, indices );
  6664. morphArray.push( newAttribute );
  6665. }
  6666. geometry2.morphAttributes[ name ] = morphArray;
  6667. }
  6668. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6669. // groups
  6670. const groups = this.groups;
  6671. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6672. const group = groups[ i ];
  6673. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6674. }
  6675. return geometry2;
  6676. }
  6677. toJSON() {
  6678. const data = {
  6679. metadata: {
  6680. version: 4.6,
  6681. type: 'BufferGeometry',
  6682. generator: 'BufferGeometry.toJSON'
  6683. }
  6684. };
  6685. // standard BufferGeometry serialization
  6686. data.uuid = this.uuid;
  6687. data.type = this.type;
  6688. if ( this.name !== '' ) data.name = this.name;
  6689. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6690. if ( this.parameters !== undefined ) {
  6691. const parameters = this.parameters;
  6692. for ( const key in parameters ) {
  6693. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6694. }
  6695. return data;
  6696. }
  6697. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6698. data.data = { attributes: {} };
  6699. const index = this.index;
  6700. if ( index !== null ) {
  6701. data.data.index = {
  6702. type: index.array.constructor.name,
  6703. array: Array.prototype.slice.call( index.array )
  6704. };
  6705. }
  6706. const attributes = this.attributes;
  6707. for ( const key in attributes ) {
  6708. const attribute = attributes[ key ];
  6709. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6710. }
  6711. const morphAttributes = {};
  6712. let hasMorphAttributes = false;
  6713. for ( const key in this.morphAttributes ) {
  6714. const attributeArray = this.morphAttributes[ key ];
  6715. const array = [];
  6716. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6717. const attribute = attributeArray[ i ];
  6718. array.push( attribute.toJSON( data.data ) );
  6719. }
  6720. if ( array.length > 0 ) {
  6721. morphAttributes[ key ] = array;
  6722. hasMorphAttributes = true;
  6723. }
  6724. }
  6725. if ( hasMorphAttributes ) {
  6726. data.data.morphAttributes = morphAttributes;
  6727. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6728. }
  6729. const groups = this.groups;
  6730. if ( groups.length > 0 ) {
  6731. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6732. }
  6733. const boundingSphere = this.boundingSphere;
  6734. if ( boundingSphere !== null ) {
  6735. data.data.boundingSphere = {
  6736. center: boundingSphere.center.toArray(),
  6737. radius: boundingSphere.radius
  6738. };
  6739. }
  6740. return data;
  6741. }
  6742. clone() {
  6743. return new this.constructor().copy( this );
  6744. }
  6745. copy( source ) {
  6746. // reset
  6747. this.index = null;
  6748. this.attributes = {};
  6749. this.morphAttributes = {};
  6750. this.groups = [];
  6751. this.boundingBox = null;
  6752. this.boundingSphere = null;
  6753. // used for storing cloned, shared data
  6754. const data = {};
  6755. // name
  6756. this.name = source.name;
  6757. // index
  6758. const index = source.index;
  6759. if ( index !== null ) {
  6760. this.setIndex( index.clone( data ) );
  6761. }
  6762. // attributes
  6763. const attributes = source.attributes;
  6764. for ( const name in attributes ) {
  6765. const attribute = attributes[ name ];
  6766. this.setAttribute( name, attribute.clone( data ) );
  6767. }
  6768. // morph attributes
  6769. const morphAttributes = source.morphAttributes;
  6770. for ( const name in morphAttributes ) {
  6771. const array = [];
  6772. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6773. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6774. array.push( morphAttribute[ i ].clone( data ) );
  6775. }
  6776. this.morphAttributes[ name ] = array;
  6777. }
  6778. this.morphTargetsRelative = source.morphTargetsRelative;
  6779. // groups
  6780. const groups = source.groups;
  6781. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6782. const group = groups[ i ];
  6783. this.addGroup( group.start, group.count, group.materialIndex );
  6784. }
  6785. // bounding box
  6786. const boundingBox = source.boundingBox;
  6787. if ( boundingBox !== null ) {
  6788. this.boundingBox = boundingBox.clone();
  6789. }
  6790. // bounding sphere
  6791. const boundingSphere = source.boundingSphere;
  6792. if ( boundingSphere !== null ) {
  6793. this.boundingSphere = boundingSphere.clone();
  6794. }
  6795. // draw range
  6796. this.drawRange.start = source.drawRange.start;
  6797. this.drawRange.count = source.drawRange.count;
  6798. // user data
  6799. this.userData = source.userData;
  6800. return this;
  6801. }
  6802. dispose() {
  6803. this.dispatchEvent( { type: 'dispose' } );
  6804. }
  6805. }
  6806. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6807. const _ray$3 = /*@__PURE__*/ new Ray();
  6808. const _sphere$5 = /*@__PURE__*/ new Sphere();
  6809. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6810. const _vA$1 = /*@__PURE__*/ new Vector3();
  6811. const _vB$1 = /*@__PURE__*/ new Vector3();
  6812. const _vC$1 = /*@__PURE__*/ new Vector3();
  6813. const _tempA = /*@__PURE__*/ new Vector3();
  6814. const _morphA = /*@__PURE__*/ new Vector3();
  6815. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6816. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6817. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6818. const _normalA = /*@__PURE__*/ new Vector3();
  6819. const _normalB = /*@__PURE__*/ new Vector3();
  6820. const _normalC = /*@__PURE__*/ new Vector3();
  6821. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6822. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6823. class Mesh extends Object3D {
  6824. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6825. super();
  6826. this.isMesh = true;
  6827. this.type = 'Mesh';
  6828. this.geometry = geometry;
  6829. this.material = material;
  6830. this.updateMorphTargets();
  6831. }
  6832. copy( source, recursive ) {
  6833. super.copy( source, recursive );
  6834. if ( source.morphTargetInfluences !== undefined ) {
  6835. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6836. }
  6837. if ( source.morphTargetDictionary !== undefined ) {
  6838. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6839. }
  6840. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6841. this.geometry = source.geometry;
  6842. return this;
  6843. }
  6844. updateMorphTargets() {
  6845. const geometry = this.geometry;
  6846. const morphAttributes = geometry.morphAttributes;
  6847. const keys = Object.keys( morphAttributes );
  6848. if ( keys.length > 0 ) {
  6849. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6850. if ( morphAttribute !== undefined ) {
  6851. this.morphTargetInfluences = [];
  6852. this.morphTargetDictionary = {};
  6853. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6854. const name = morphAttribute[ m ].name || String( m );
  6855. this.morphTargetInfluences.push( 0 );
  6856. this.morphTargetDictionary[ name ] = m;
  6857. }
  6858. }
  6859. }
  6860. }
  6861. getVertexPosition( index, target ) {
  6862. const geometry = this.geometry;
  6863. const position = geometry.attributes.position;
  6864. const morphPosition = geometry.morphAttributes.position;
  6865. const morphTargetsRelative = geometry.morphTargetsRelative;
  6866. target.fromBufferAttribute( position, index );
  6867. const morphInfluences = this.morphTargetInfluences;
  6868. if ( morphPosition && morphInfluences ) {
  6869. _morphA.set( 0, 0, 0 );
  6870. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6871. const influence = morphInfluences[ i ];
  6872. const morphAttribute = morphPosition[ i ];
  6873. if ( influence === 0 ) continue;
  6874. _tempA.fromBufferAttribute( morphAttribute, index );
  6875. if ( morphTargetsRelative ) {
  6876. _morphA.addScaledVector( _tempA, influence );
  6877. } else {
  6878. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6879. }
  6880. }
  6881. target.add( _morphA );
  6882. }
  6883. return target;
  6884. }
  6885. raycast( raycaster, intersects ) {
  6886. const geometry = this.geometry;
  6887. const material = this.material;
  6888. const matrixWorld = this.matrixWorld;
  6889. if ( material === undefined ) return;
  6890. // test with bounding sphere in world space
  6891. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6892. _sphere$5.copy( geometry.boundingSphere );
  6893. _sphere$5.applyMatrix4( matrixWorld );
  6894. // check distance from ray origin to bounding sphere
  6895. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6896. if ( _sphere$5.containsPoint( _ray$3.origin ) === false ) {
  6897. if ( _ray$3.intersectSphere( _sphere$5, _sphereHitAt ) === null ) return;
  6898. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6899. }
  6900. // convert ray to local space of mesh
  6901. _inverseMatrix$3.copy( matrixWorld ).invert();
  6902. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6903. // test with bounding box in local space
  6904. if ( geometry.boundingBox !== null ) {
  6905. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6906. }
  6907. // test for intersections with geometry
  6908. this._computeIntersections( raycaster, intersects, _ray$3 );
  6909. }
  6910. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6911. let intersection;
  6912. const geometry = this.geometry;
  6913. const material = this.material;
  6914. const index = geometry.index;
  6915. const position = geometry.attributes.position;
  6916. const uv = geometry.attributes.uv;
  6917. const uv1 = geometry.attributes.uv1;
  6918. const normal = geometry.attributes.normal;
  6919. const groups = geometry.groups;
  6920. const drawRange = geometry.drawRange;
  6921. if ( index !== null ) {
  6922. // indexed buffer geometry
  6923. if ( Array.isArray( material ) ) {
  6924. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6925. const group = groups[ i ];
  6926. const groupMaterial = material[ group.materialIndex ];
  6927. const start = Math.max( group.start, drawRange.start );
  6928. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6929. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6930. const a = index.getX( j );
  6931. const b = index.getX( j + 1 );
  6932. const c = index.getX( j + 2 );
  6933. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6934. if ( intersection ) {
  6935. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6936. intersection.face.materialIndex = group.materialIndex;
  6937. intersects.push( intersection );
  6938. }
  6939. }
  6940. }
  6941. } else {
  6942. const start = Math.max( 0, drawRange.start );
  6943. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6944. for ( let i = start, il = end; i < il; i += 3 ) {
  6945. const a = index.getX( i );
  6946. const b = index.getX( i + 1 );
  6947. const c = index.getX( i + 2 );
  6948. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6949. if ( intersection ) {
  6950. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6951. intersects.push( intersection );
  6952. }
  6953. }
  6954. }
  6955. } else if ( position !== undefined ) {
  6956. // non-indexed buffer geometry
  6957. if ( Array.isArray( material ) ) {
  6958. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6959. const group = groups[ i ];
  6960. const groupMaterial = material[ group.materialIndex ];
  6961. const start = Math.max( group.start, drawRange.start );
  6962. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6963. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6964. const a = j;
  6965. const b = j + 1;
  6966. const c = j + 2;
  6967. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6968. if ( intersection ) {
  6969. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6970. intersection.face.materialIndex = group.materialIndex;
  6971. intersects.push( intersection );
  6972. }
  6973. }
  6974. }
  6975. } else {
  6976. const start = Math.max( 0, drawRange.start );
  6977. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6978. for ( let i = start, il = end; i < il; i += 3 ) {
  6979. const a = i;
  6980. const b = i + 1;
  6981. const c = i + 2;
  6982. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6983. if ( intersection ) {
  6984. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6985. intersects.push( intersection );
  6986. }
  6987. }
  6988. }
  6989. }
  6990. }
  6991. }
  6992. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6993. let intersect;
  6994. if ( material.side === BackSide ) {
  6995. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6996. } else {
  6997. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6998. }
  6999. if ( intersect === null ) return null;
  7000. _intersectionPointWorld.copy( point );
  7001. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7002. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7003. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7004. return {
  7005. distance: distance,
  7006. point: _intersectionPointWorld.clone(),
  7007. object: object
  7008. };
  7009. }
  7010. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7011. object.getVertexPosition( a, _vA$1 );
  7012. object.getVertexPosition( b, _vB$1 );
  7013. object.getVertexPosition( c, _vC$1 );
  7014. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7015. if ( intersection ) {
  7016. if ( uv ) {
  7017. _uvA$1.fromBufferAttribute( uv, a );
  7018. _uvB$1.fromBufferAttribute( uv, b );
  7019. _uvC$1.fromBufferAttribute( uv, c );
  7020. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7021. }
  7022. if ( uv1 ) {
  7023. _uvA$1.fromBufferAttribute( uv1, a );
  7024. _uvB$1.fromBufferAttribute( uv1, b );
  7025. _uvC$1.fromBufferAttribute( uv1, c );
  7026. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7027. intersection.uv2 = intersection.uv1; // @deprecated, r152
  7028. }
  7029. if ( normal ) {
  7030. _normalA.fromBufferAttribute( normal, a );
  7031. _normalB.fromBufferAttribute( normal, b );
  7032. _normalC.fromBufferAttribute( normal, c );
  7033. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7034. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7035. intersection.normal.multiplyScalar( - 1 );
  7036. }
  7037. }
  7038. const face = {
  7039. a: a,
  7040. b: b,
  7041. c: c,
  7042. normal: new Vector3(),
  7043. materialIndex: 0
  7044. };
  7045. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7046. intersection.face = face;
  7047. }
  7048. return intersection;
  7049. }
  7050. class BoxGeometry extends BufferGeometry {
  7051. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7052. super();
  7053. this.type = 'BoxGeometry';
  7054. this.parameters = {
  7055. width: width,
  7056. height: height,
  7057. depth: depth,
  7058. widthSegments: widthSegments,
  7059. heightSegments: heightSegments,
  7060. depthSegments: depthSegments
  7061. };
  7062. const scope = this;
  7063. // segments
  7064. widthSegments = Math.floor( widthSegments );
  7065. heightSegments = Math.floor( heightSegments );
  7066. depthSegments = Math.floor( depthSegments );
  7067. // buffers
  7068. const indices = [];
  7069. const vertices = [];
  7070. const normals = [];
  7071. const uvs = [];
  7072. // helper variables
  7073. let numberOfVertices = 0;
  7074. let groupStart = 0;
  7075. // build each side of the box geometry
  7076. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7077. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7078. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7079. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7080. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7081. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7082. // build geometry
  7083. this.setIndex( indices );
  7084. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7085. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7086. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7087. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7088. const segmentWidth = width / gridX;
  7089. const segmentHeight = height / gridY;
  7090. const widthHalf = width / 2;
  7091. const heightHalf = height / 2;
  7092. const depthHalf = depth / 2;
  7093. const gridX1 = gridX + 1;
  7094. const gridY1 = gridY + 1;
  7095. let vertexCounter = 0;
  7096. let groupCount = 0;
  7097. const vector = new Vector3();
  7098. // generate vertices, normals and uvs
  7099. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7100. const y = iy * segmentHeight - heightHalf;
  7101. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7102. const x = ix * segmentWidth - widthHalf;
  7103. // set values to correct vector component
  7104. vector[ u ] = x * udir;
  7105. vector[ v ] = y * vdir;
  7106. vector[ w ] = depthHalf;
  7107. // now apply vector to vertex buffer
  7108. vertices.push( vector.x, vector.y, vector.z );
  7109. // set values to correct vector component
  7110. vector[ u ] = 0;
  7111. vector[ v ] = 0;
  7112. vector[ w ] = depth > 0 ? 1 : - 1;
  7113. // now apply vector to normal buffer
  7114. normals.push( vector.x, vector.y, vector.z );
  7115. // uvs
  7116. uvs.push( ix / gridX );
  7117. uvs.push( 1 - ( iy / gridY ) );
  7118. // counters
  7119. vertexCounter += 1;
  7120. }
  7121. }
  7122. // indices
  7123. // 1. you need three indices to draw a single face
  7124. // 2. a single segment consists of two faces
  7125. // 3. so we need to generate six (2*3) indices per segment
  7126. for ( let iy = 0; iy < gridY; iy ++ ) {
  7127. for ( let ix = 0; ix < gridX; ix ++ ) {
  7128. const a = numberOfVertices + ix + gridX1 * iy;
  7129. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7130. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7131. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7132. // faces
  7133. indices.push( a, b, d );
  7134. indices.push( b, c, d );
  7135. // increase counter
  7136. groupCount += 6;
  7137. }
  7138. }
  7139. // add a group to the geometry. this will ensure multi material support
  7140. scope.addGroup( groupStart, groupCount, materialIndex );
  7141. // calculate new start value for groups
  7142. groupStart += groupCount;
  7143. // update total number of vertices
  7144. numberOfVertices += vertexCounter;
  7145. }
  7146. }
  7147. copy( source ) {
  7148. super.copy( source );
  7149. this.parameters = Object.assign( {}, source.parameters );
  7150. return this;
  7151. }
  7152. static fromJSON( data ) {
  7153. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7154. }
  7155. }
  7156. /**
  7157. * Uniform Utilities
  7158. */
  7159. function cloneUniforms( src ) {
  7160. const dst = {};
  7161. for ( const u in src ) {
  7162. dst[ u ] = {};
  7163. for ( const p in src[ u ] ) {
  7164. const property = src[ u ][ p ];
  7165. if ( property && ( property.isColor ||
  7166. property.isMatrix3 || property.isMatrix4 ||
  7167. property.isVector2 || property.isVector3 || property.isVector4 ||
  7168. property.isTexture || property.isQuaternion ) ) {
  7169. if ( property.isRenderTargetTexture ) {
  7170. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7171. dst[ u ][ p ] = null;
  7172. } else {
  7173. dst[ u ][ p ] = property.clone();
  7174. }
  7175. } else if ( Array.isArray( property ) ) {
  7176. dst[ u ][ p ] = property.slice();
  7177. } else {
  7178. dst[ u ][ p ] = property;
  7179. }
  7180. }
  7181. }
  7182. return dst;
  7183. }
  7184. function mergeUniforms( uniforms ) {
  7185. const merged = {};
  7186. for ( let u = 0; u < uniforms.length; u ++ ) {
  7187. const tmp = cloneUniforms( uniforms[ u ] );
  7188. for ( const p in tmp ) {
  7189. merged[ p ] = tmp[ p ];
  7190. }
  7191. }
  7192. return merged;
  7193. }
  7194. function cloneUniformsGroups( src ) {
  7195. const dst = [];
  7196. for ( let u = 0; u < src.length; u ++ ) {
  7197. dst.push( src[ u ].clone() );
  7198. }
  7199. return dst;
  7200. }
  7201. function getUnlitUniformColorSpace( renderer ) {
  7202. if ( renderer.getRenderTarget() === null ) {
  7203. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7204. return renderer.outputColorSpace;
  7205. }
  7206. return ColorManagement.workingColorSpace;
  7207. }
  7208. // Legacy
  7209. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7210. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7211. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7212. class ShaderMaterial extends Material {
  7213. constructor( parameters ) {
  7214. super();
  7215. this.isShaderMaterial = true;
  7216. this.type = 'ShaderMaterial';
  7217. this.defines = {};
  7218. this.uniforms = {};
  7219. this.uniformsGroups = [];
  7220. this.vertexShader = default_vertex;
  7221. this.fragmentShader = default_fragment;
  7222. this.linewidth = 1;
  7223. this.wireframe = false;
  7224. this.wireframeLinewidth = 1;
  7225. this.fog = false; // set to use scene fog
  7226. this.lights = false; // set to use scene lights
  7227. this.clipping = false; // set to use user-defined clipping planes
  7228. this.forceSinglePass = true;
  7229. this.extensions = {
  7230. derivatives: false, // set to use derivatives
  7231. fragDepth: false, // set to use fragment depth values
  7232. drawBuffers: false, // set to use draw buffers
  7233. shaderTextureLOD: false // set to use shader texture LOD
  7234. };
  7235. // When rendered geometry doesn't include these attributes but the material does,
  7236. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7237. this.defaultAttributeValues = {
  7238. 'color': [ 1, 1, 1 ],
  7239. 'uv': [ 0, 0 ],
  7240. 'uv1': [ 0, 0 ]
  7241. };
  7242. this.index0AttributeName = undefined;
  7243. this.uniformsNeedUpdate = false;
  7244. this.glslVersion = null;
  7245. if ( parameters !== undefined ) {
  7246. this.setValues( parameters );
  7247. }
  7248. }
  7249. copy( source ) {
  7250. super.copy( source );
  7251. this.fragmentShader = source.fragmentShader;
  7252. this.vertexShader = source.vertexShader;
  7253. this.uniforms = cloneUniforms( source.uniforms );
  7254. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7255. this.defines = Object.assign( {}, source.defines );
  7256. this.wireframe = source.wireframe;
  7257. this.wireframeLinewidth = source.wireframeLinewidth;
  7258. this.fog = source.fog;
  7259. this.lights = source.lights;
  7260. this.clipping = source.clipping;
  7261. this.extensions = Object.assign( {}, source.extensions );
  7262. this.glslVersion = source.glslVersion;
  7263. return this;
  7264. }
  7265. toJSON( meta ) {
  7266. const data = super.toJSON( meta );
  7267. data.glslVersion = this.glslVersion;
  7268. data.uniforms = {};
  7269. for ( const name in this.uniforms ) {
  7270. const uniform = this.uniforms[ name ];
  7271. const value = uniform.value;
  7272. if ( value && value.isTexture ) {
  7273. data.uniforms[ name ] = {
  7274. type: 't',
  7275. value: value.toJSON( meta ).uuid
  7276. };
  7277. } else if ( value && value.isColor ) {
  7278. data.uniforms[ name ] = {
  7279. type: 'c',
  7280. value: value.getHex()
  7281. };
  7282. } else if ( value && value.isVector2 ) {
  7283. data.uniforms[ name ] = {
  7284. type: 'v2',
  7285. value: value.toArray()
  7286. };
  7287. } else if ( value && value.isVector3 ) {
  7288. data.uniforms[ name ] = {
  7289. type: 'v3',
  7290. value: value.toArray()
  7291. };
  7292. } else if ( value && value.isVector4 ) {
  7293. data.uniforms[ name ] = {
  7294. type: 'v4',
  7295. value: value.toArray()
  7296. };
  7297. } else if ( value && value.isMatrix3 ) {
  7298. data.uniforms[ name ] = {
  7299. type: 'm3',
  7300. value: value.toArray()
  7301. };
  7302. } else if ( value && value.isMatrix4 ) {
  7303. data.uniforms[ name ] = {
  7304. type: 'm4',
  7305. value: value.toArray()
  7306. };
  7307. } else {
  7308. data.uniforms[ name ] = {
  7309. value: value
  7310. };
  7311. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7312. }
  7313. }
  7314. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7315. data.vertexShader = this.vertexShader;
  7316. data.fragmentShader = this.fragmentShader;
  7317. data.lights = this.lights;
  7318. data.clipping = this.clipping;
  7319. const extensions = {};
  7320. for ( const key in this.extensions ) {
  7321. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7322. }
  7323. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7324. return data;
  7325. }
  7326. }
  7327. class Camera extends Object3D {
  7328. constructor() {
  7329. super();
  7330. this.isCamera = true;
  7331. this.type = 'Camera';
  7332. this.matrixWorldInverse = new Matrix4();
  7333. this.projectionMatrix = new Matrix4();
  7334. this.projectionMatrixInverse = new Matrix4();
  7335. this.coordinateSystem = WebGLCoordinateSystem;
  7336. }
  7337. copy( source, recursive ) {
  7338. super.copy( source, recursive );
  7339. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7340. this.projectionMatrix.copy( source.projectionMatrix );
  7341. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7342. this.coordinateSystem = source.coordinateSystem;
  7343. return this;
  7344. }
  7345. getWorldDirection( target ) {
  7346. return super.getWorldDirection( target ).negate();
  7347. }
  7348. updateMatrixWorld( force ) {
  7349. super.updateMatrixWorld( force );
  7350. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7351. }
  7352. updateWorldMatrix( updateParents, updateChildren ) {
  7353. super.updateWorldMatrix( updateParents, updateChildren );
  7354. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7355. }
  7356. clone() {
  7357. return new this.constructor().copy( this );
  7358. }
  7359. }
  7360. class PerspectiveCamera extends Camera {
  7361. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7362. super();
  7363. this.isPerspectiveCamera = true;
  7364. this.type = 'PerspectiveCamera';
  7365. this.fov = fov;
  7366. this.zoom = 1;
  7367. this.near = near;
  7368. this.far = far;
  7369. this.focus = 10;
  7370. this.aspect = aspect;
  7371. this.view = null;
  7372. this.filmGauge = 35; // width of the film (default in millimeters)
  7373. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7374. this.updateProjectionMatrix();
  7375. }
  7376. copy( source, recursive ) {
  7377. super.copy( source, recursive );
  7378. this.fov = source.fov;
  7379. this.zoom = source.zoom;
  7380. this.near = source.near;
  7381. this.far = source.far;
  7382. this.focus = source.focus;
  7383. this.aspect = source.aspect;
  7384. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7385. this.filmGauge = source.filmGauge;
  7386. this.filmOffset = source.filmOffset;
  7387. return this;
  7388. }
  7389. /**
  7390. * Sets the FOV by focal length in respect to the current .filmGauge.
  7391. *
  7392. * The default film gauge is 35, so that the focal length can be specified for
  7393. * a 35mm (full frame) camera.
  7394. *
  7395. * Values for focal length and film gauge must have the same unit.
  7396. */
  7397. setFocalLength( focalLength ) {
  7398. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7399. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7400. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7401. this.updateProjectionMatrix();
  7402. }
  7403. /**
  7404. * Calculates the focal length from the current .fov and .filmGauge.
  7405. */
  7406. getFocalLength() {
  7407. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7408. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7409. }
  7410. getEffectiveFOV() {
  7411. return RAD2DEG * 2 * Math.atan(
  7412. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7413. }
  7414. getFilmWidth() {
  7415. // film not completely covered in portrait format (aspect < 1)
  7416. return this.filmGauge * Math.min( this.aspect, 1 );
  7417. }
  7418. getFilmHeight() {
  7419. // film not completely covered in landscape format (aspect > 1)
  7420. return this.filmGauge / Math.max( this.aspect, 1 );
  7421. }
  7422. /**
  7423. * Sets an offset in a larger frustum. This is useful for multi-window or
  7424. * multi-monitor/multi-machine setups.
  7425. *
  7426. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7427. * the monitors are in grid like this
  7428. *
  7429. * +---+---+---+
  7430. * | A | B | C |
  7431. * +---+---+---+
  7432. * | D | E | F |
  7433. * +---+---+---+
  7434. *
  7435. * then for each monitor you would call it like this
  7436. *
  7437. * const w = 1920;
  7438. * const h = 1080;
  7439. * const fullWidth = w * 3;
  7440. * const fullHeight = h * 2;
  7441. *
  7442. * --A--
  7443. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7444. * --B--
  7445. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7446. * --C--
  7447. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7448. * --D--
  7449. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7450. * --E--
  7451. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7452. * --F--
  7453. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7454. *
  7455. * Note there is no reason monitors have to be the same size or in a grid.
  7456. */
  7457. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7458. this.aspect = fullWidth / fullHeight;
  7459. if ( this.view === null ) {
  7460. this.view = {
  7461. enabled: true,
  7462. fullWidth: 1,
  7463. fullHeight: 1,
  7464. offsetX: 0,
  7465. offsetY: 0,
  7466. width: 1,
  7467. height: 1
  7468. };
  7469. }
  7470. this.view.enabled = true;
  7471. this.view.fullWidth = fullWidth;
  7472. this.view.fullHeight = fullHeight;
  7473. this.view.offsetX = x;
  7474. this.view.offsetY = y;
  7475. this.view.width = width;
  7476. this.view.height = height;
  7477. this.updateProjectionMatrix();
  7478. }
  7479. clearViewOffset() {
  7480. if ( this.view !== null ) {
  7481. this.view.enabled = false;
  7482. }
  7483. this.updateProjectionMatrix();
  7484. }
  7485. updateProjectionMatrix() {
  7486. const near = this.near;
  7487. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7488. let height = 2 * top;
  7489. let width = this.aspect * height;
  7490. let left = - 0.5 * width;
  7491. const view = this.view;
  7492. if ( this.view !== null && this.view.enabled ) {
  7493. const fullWidth = view.fullWidth,
  7494. fullHeight = view.fullHeight;
  7495. left += view.offsetX * width / fullWidth;
  7496. top -= view.offsetY * height / fullHeight;
  7497. width *= view.width / fullWidth;
  7498. height *= view.height / fullHeight;
  7499. }
  7500. const skew = this.filmOffset;
  7501. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7502. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7503. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7504. }
  7505. toJSON( meta ) {
  7506. const data = super.toJSON( meta );
  7507. data.object.fov = this.fov;
  7508. data.object.zoom = this.zoom;
  7509. data.object.near = this.near;
  7510. data.object.far = this.far;
  7511. data.object.focus = this.focus;
  7512. data.object.aspect = this.aspect;
  7513. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7514. data.object.filmGauge = this.filmGauge;
  7515. data.object.filmOffset = this.filmOffset;
  7516. return data;
  7517. }
  7518. }
  7519. const fov = - 90; // negative fov is not an error
  7520. const aspect = 1;
  7521. class CubeCamera extends Object3D {
  7522. constructor( near, far, renderTarget ) {
  7523. super();
  7524. this.type = 'CubeCamera';
  7525. this.renderTarget = renderTarget;
  7526. this.coordinateSystem = null;
  7527. this.activeMipmapLevel = 0;
  7528. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7529. cameraPX.layers = this.layers;
  7530. this.add( cameraPX );
  7531. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7532. cameraNX.layers = this.layers;
  7533. this.add( cameraNX );
  7534. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7535. cameraPY.layers = this.layers;
  7536. this.add( cameraPY );
  7537. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7538. cameraNY.layers = this.layers;
  7539. this.add( cameraNY );
  7540. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7541. cameraPZ.layers = this.layers;
  7542. this.add( cameraPZ );
  7543. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7544. cameraNZ.layers = this.layers;
  7545. this.add( cameraNZ );
  7546. }
  7547. updateCoordinateSystem() {
  7548. const coordinateSystem = this.coordinateSystem;
  7549. const cameras = this.children.concat();
  7550. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7551. for ( const camera of cameras ) this.remove( camera );
  7552. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7553. cameraPX.up.set( 0, 1, 0 );
  7554. cameraPX.lookAt( 1, 0, 0 );
  7555. cameraNX.up.set( 0, 1, 0 );
  7556. cameraNX.lookAt( - 1, 0, 0 );
  7557. cameraPY.up.set( 0, 0, - 1 );
  7558. cameraPY.lookAt( 0, 1, 0 );
  7559. cameraNY.up.set( 0, 0, 1 );
  7560. cameraNY.lookAt( 0, - 1, 0 );
  7561. cameraPZ.up.set( 0, 1, 0 );
  7562. cameraPZ.lookAt( 0, 0, 1 );
  7563. cameraNZ.up.set( 0, 1, 0 );
  7564. cameraNZ.lookAt( 0, 0, - 1 );
  7565. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7566. cameraPX.up.set( 0, - 1, 0 );
  7567. cameraPX.lookAt( - 1, 0, 0 );
  7568. cameraNX.up.set( 0, - 1, 0 );
  7569. cameraNX.lookAt( 1, 0, 0 );
  7570. cameraPY.up.set( 0, 0, 1 );
  7571. cameraPY.lookAt( 0, 1, 0 );
  7572. cameraNY.up.set( 0, 0, - 1 );
  7573. cameraNY.lookAt( 0, - 1, 0 );
  7574. cameraPZ.up.set( 0, - 1, 0 );
  7575. cameraPZ.lookAt( 0, 0, 1 );
  7576. cameraNZ.up.set( 0, - 1, 0 );
  7577. cameraNZ.lookAt( 0, 0, - 1 );
  7578. } else {
  7579. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7580. }
  7581. for ( const camera of cameras ) {
  7582. this.add( camera );
  7583. camera.updateMatrixWorld();
  7584. }
  7585. }
  7586. update( renderer, scene ) {
  7587. if ( this.parent === null ) this.updateMatrixWorld();
  7588. const { renderTarget, activeMipmapLevel } = this;
  7589. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7590. this.coordinateSystem = renderer.coordinateSystem;
  7591. this.updateCoordinateSystem();
  7592. }
  7593. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7594. const currentRenderTarget = renderer.getRenderTarget();
  7595. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7596. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7597. const currentXrEnabled = renderer.xr.enabled;
  7598. renderer.xr.enabled = false;
  7599. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7600. renderTarget.texture.generateMipmaps = false;
  7601. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7602. renderer.render( scene, cameraPX );
  7603. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7604. renderer.render( scene, cameraNX );
  7605. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7606. renderer.render( scene, cameraPY );
  7607. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7608. renderer.render( scene, cameraNY );
  7609. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7610. renderer.render( scene, cameraPZ );
  7611. // mipmaps are generated during the last call of render()
  7612. // at this point, all sides of the cube render target are defined
  7613. renderTarget.texture.generateMipmaps = generateMipmaps;
  7614. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7615. renderer.render( scene, cameraNZ );
  7616. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7617. renderer.xr.enabled = currentXrEnabled;
  7618. renderTarget.texture.needsPMREMUpdate = true;
  7619. }
  7620. }
  7621. class CubeTexture extends Texture {
  7622. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7623. images = images !== undefined ? images : [];
  7624. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7625. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7626. this.isCubeTexture = true;
  7627. this.flipY = false;
  7628. }
  7629. get images() {
  7630. return this.image;
  7631. }
  7632. set images( value ) {
  7633. this.image = value;
  7634. }
  7635. }
  7636. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7637. constructor( size = 1, options = {} ) {
  7638. super( size, size, options );
  7639. this.isWebGLCubeRenderTarget = true;
  7640. const image = { width: size, height: size, depth: 1 };
  7641. const images = [ image, image, image, image, image, image ];
  7642. if ( options.encoding !== undefined ) {
  7643. // @deprecated, r152
  7644. warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  7645. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  7646. }
  7647. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7648. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7649. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7650. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7651. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7652. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7653. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7654. this.texture.isRenderTargetTexture = true;
  7655. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7656. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7657. }
  7658. fromEquirectangularTexture( renderer, texture ) {
  7659. this.texture.type = texture.type;
  7660. this.texture.colorSpace = texture.colorSpace;
  7661. this.texture.generateMipmaps = texture.generateMipmaps;
  7662. this.texture.minFilter = texture.minFilter;
  7663. this.texture.magFilter = texture.magFilter;
  7664. const shader = {
  7665. uniforms: {
  7666. tEquirect: { value: null },
  7667. },
  7668. vertexShader: /* glsl */`
  7669. varying vec3 vWorldDirection;
  7670. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7671. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7672. }
  7673. void main() {
  7674. vWorldDirection = transformDirection( position, modelMatrix );
  7675. #include <begin_vertex>
  7676. #include <project_vertex>
  7677. }
  7678. `,
  7679. fragmentShader: /* glsl */`
  7680. uniform sampler2D tEquirect;
  7681. varying vec3 vWorldDirection;
  7682. #include <common>
  7683. void main() {
  7684. vec3 direction = normalize( vWorldDirection );
  7685. vec2 sampleUV = equirectUv( direction );
  7686. gl_FragColor = texture2D( tEquirect, sampleUV );
  7687. }
  7688. `
  7689. };
  7690. const geometry = new BoxGeometry( 5, 5, 5 );
  7691. const material = new ShaderMaterial( {
  7692. name: 'CubemapFromEquirect',
  7693. uniforms: cloneUniforms( shader.uniforms ),
  7694. vertexShader: shader.vertexShader,
  7695. fragmentShader: shader.fragmentShader,
  7696. side: BackSide,
  7697. blending: NoBlending
  7698. } );
  7699. material.uniforms.tEquirect.value = texture;
  7700. const mesh = new Mesh( geometry, material );
  7701. const currentMinFilter = texture.minFilter;
  7702. // Avoid blurred poles
  7703. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7704. const camera = new CubeCamera( 1, 10, this );
  7705. camera.update( renderer, mesh );
  7706. texture.minFilter = currentMinFilter;
  7707. mesh.geometry.dispose();
  7708. mesh.material.dispose();
  7709. return this;
  7710. }
  7711. clear( renderer, color, depth, stencil ) {
  7712. const currentRenderTarget = renderer.getRenderTarget();
  7713. for ( let i = 0; i < 6; i ++ ) {
  7714. renderer.setRenderTarget( this, i );
  7715. renderer.clear( color, depth, stencil );
  7716. }
  7717. renderer.setRenderTarget( currentRenderTarget );
  7718. }
  7719. }
  7720. const _vector1 = /*@__PURE__*/ new Vector3();
  7721. const _vector2 = /*@__PURE__*/ new Vector3();
  7722. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7723. class Plane {
  7724. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7725. this.isPlane = true;
  7726. // normal is assumed to be normalized
  7727. this.normal = normal;
  7728. this.constant = constant;
  7729. }
  7730. set( normal, constant ) {
  7731. this.normal.copy( normal );
  7732. this.constant = constant;
  7733. return this;
  7734. }
  7735. setComponents( x, y, z, w ) {
  7736. this.normal.set( x, y, z );
  7737. this.constant = w;
  7738. return this;
  7739. }
  7740. setFromNormalAndCoplanarPoint( normal, point ) {
  7741. this.normal.copy( normal );
  7742. this.constant = - point.dot( this.normal );
  7743. return this;
  7744. }
  7745. setFromCoplanarPoints( a, b, c ) {
  7746. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7747. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7748. this.setFromNormalAndCoplanarPoint( normal, a );
  7749. return this;
  7750. }
  7751. copy( plane ) {
  7752. this.normal.copy( plane.normal );
  7753. this.constant = plane.constant;
  7754. return this;
  7755. }
  7756. normalize() {
  7757. // Note: will lead to a divide by zero if the plane is invalid.
  7758. const inverseNormalLength = 1.0 / this.normal.length();
  7759. this.normal.multiplyScalar( inverseNormalLength );
  7760. this.constant *= inverseNormalLength;
  7761. return this;
  7762. }
  7763. negate() {
  7764. this.constant *= - 1;
  7765. this.normal.negate();
  7766. return this;
  7767. }
  7768. distanceToPoint( point ) {
  7769. return this.normal.dot( point ) + this.constant;
  7770. }
  7771. distanceToSphere( sphere ) {
  7772. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7773. }
  7774. projectPoint( point, target ) {
  7775. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7776. }
  7777. intersectLine( line, target ) {
  7778. const direction = line.delta( _vector1 );
  7779. const denominator = this.normal.dot( direction );
  7780. if ( denominator === 0 ) {
  7781. // line is coplanar, return origin
  7782. if ( this.distanceToPoint( line.start ) === 0 ) {
  7783. return target.copy( line.start );
  7784. }
  7785. // Unsure if this is the correct method to handle this case.
  7786. return null;
  7787. }
  7788. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7789. if ( t < 0 || t > 1 ) {
  7790. return null;
  7791. }
  7792. return target.copy( line.start ).addScaledVector( direction, t );
  7793. }
  7794. intersectsLine( line ) {
  7795. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7796. const startSign = this.distanceToPoint( line.start );
  7797. const endSign = this.distanceToPoint( line.end );
  7798. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7799. }
  7800. intersectsBox( box ) {
  7801. return box.intersectsPlane( this );
  7802. }
  7803. intersectsSphere( sphere ) {
  7804. return sphere.intersectsPlane( this );
  7805. }
  7806. coplanarPoint( target ) {
  7807. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7808. }
  7809. applyMatrix4( matrix, optionalNormalMatrix ) {
  7810. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7811. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7812. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7813. this.constant = - referencePoint.dot( normal );
  7814. return this;
  7815. }
  7816. translate( offset ) {
  7817. this.constant -= offset.dot( this.normal );
  7818. return this;
  7819. }
  7820. equals( plane ) {
  7821. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7822. }
  7823. clone() {
  7824. return new this.constructor().copy( this );
  7825. }
  7826. }
  7827. const _sphere$4 = /*@__PURE__*/ new Sphere();
  7828. const _vector$6 = /*@__PURE__*/ new Vector3();
  7829. class Frustum {
  7830. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7831. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7832. }
  7833. set( p0, p1, p2, p3, p4, p5 ) {
  7834. const planes = this.planes;
  7835. planes[ 0 ].copy( p0 );
  7836. planes[ 1 ].copy( p1 );
  7837. planes[ 2 ].copy( p2 );
  7838. planes[ 3 ].copy( p3 );
  7839. planes[ 4 ].copy( p4 );
  7840. planes[ 5 ].copy( p5 );
  7841. return this;
  7842. }
  7843. copy( frustum ) {
  7844. const planes = this.planes;
  7845. for ( let i = 0; i < 6; i ++ ) {
  7846. planes[ i ].copy( frustum.planes[ i ] );
  7847. }
  7848. return this;
  7849. }
  7850. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7851. const planes = this.planes;
  7852. const me = m.elements;
  7853. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7854. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7855. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7856. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7857. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7858. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7859. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7860. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7861. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7862. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7863. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7864. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7865. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7866. } else {
  7867. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7868. }
  7869. return this;
  7870. }
  7871. intersectsObject( object ) {
  7872. if ( object.boundingSphere !== undefined ) {
  7873. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7874. _sphere$4.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7875. } else {
  7876. const geometry = object.geometry;
  7877. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7878. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7879. }
  7880. return this.intersectsSphere( _sphere$4 );
  7881. }
  7882. intersectsSprite( sprite ) {
  7883. _sphere$4.center.set( 0, 0, 0 );
  7884. _sphere$4.radius = 0.7071067811865476;
  7885. _sphere$4.applyMatrix4( sprite.matrixWorld );
  7886. return this.intersectsSphere( _sphere$4 );
  7887. }
  7888. intersectsSphere( sphere ) {
  7889. const planes = this.planes;
  7890. const center = sphere.center;
  7891. const negRadius = - sphere.radius;
  7892. for ( let i = 0; i < 6; i ++ ) {
  7893. const distance = planes[ i ].distanceToPoint( center );
  7894. if ( distance < negRadius ) {
  7895. return false;
  7896. }
  7897. }
  7898. return true;
  7899. }
  7900. intersectsBox( box ) {
  7901. const planes = this.planes;
  7902. for ( let i = 0; i < 6; i ++ ) {
  7903. const plane = planes[ i ];
  7904. // corner at max distance
  7905. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7906. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7907. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7908. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  7909. return false;
  7910. }
  7911. }
  7912. return true;
  7913. }
  7914. containsPoint( point ) {
  7915. const planes = this.planes;
  7916. for ( let i = 0; i < 6; i ++ ) {
  7917. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7918. return false;
  7919. }
  7920. }
  7921. return true;
  7922. }
  7923. clone() {
  7924. return new this.constructor().copy( this );
  7925. }
  7926. }
  7927. function WebGLAnimation() {
  7928. let context = null;
  7929. let isAnimating = false;
  7930. let animationLoop = null;
  7931. let requestId = null;
  7932. function onAnimationFrame( time, frame ) {
  7933. animationLoop( time, frame );
  7934. requestId = context.requestAnimationFrame( onAnimationFrame );
  7935. }
  7936. return {
  7937. start: function () {
  7938. if ( isAnimating === true ) return;
  7939. if ( animationLoop === null ) return;
  7940. requestId = context.requestAnimationFrame( onAnimationFrame );
  7941. isAnimating = true;
  7942. },
  7943. stop: function () {
  7944. context.cancelAnimationFrame( requestId );
  7945. isAnimating = false;
  7946. },
  7947. setAnimationLoop: function ( callback ) {
  7948. animationLoop = callback;
  7949. },
  7950. setContext: function ( value ) {
  7951. context = value;
  7952. }
  7953. };
  7954. }
  7955. function WebGLAttributes( gl, capabilities ) {
  7956. const isWebGL2 = capabilities.isWebGL2;
  7957. const buffers = new WeakMap();
  7958. function createBuffer( attribute, bufferType ) {
  7959. const array = attribute.array;
  7960. const usage = attribute.usage;
  7961. const buffer = gl.createBuffer();
  7962. gl.bindBuffer( bufferType, buffer );
  7963. gl.bufferData( bufferType, array, usage );
  7964. attribute.onUploadCallback();
  7965. let type;
  7966. if ( array instanceof Float32Array ) {
  7967. type = gl.FLOAT;
  7968. } else if ( array instanceof Uint16Array ) {
  7969. if ( attribute.isFloat16BufferAttribute ) {
  7970. if ( isWebGL2 ) {
  7971. type = gl.HALF_FLOAT;
  7972. } else {
  7973. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7974. }
  7975. } else {
  7976. type = gl.UNSIGNED_SHORT;
  7977. }
  7978. } else if ( array instanceof Int16Array ) {
  7979. type = gl.SHORT;
  7980. } else if ( array instanceof Uint32Array ) {
  7981. type = gl.UNSIGNED_INT;
  7982. } else if ( array instanceof Int32Array ) {
  7983. type = gl.INT;
  7984. } else if ( array instanceof Int8Array ) {
  7985. type = gl.BYTE;
  7986. } else if ( array instanceof Uint8Array ) {
  7987. type = gl.UNSIGNED_BYTE;
  7988. } else if ( array instanceof Uint8ClampedArray ) {
  7989. type = gl.UNSIGNED_BYTE;
  7990. } else {
  7991. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7992. }
  7993. return {
  7994. buffer: buffer,
  7995. type: type,
  7996. bytesPerElement: array.BYTES_PER_ELEMENT,
  7997. version: attribute.version
  7998. };
  7999. }
  8000. function updateBuffer( buffer, attribute, bufferType ) {
  8001. const array = attribute.array;
  8002. const updateRange = attribute.updateRange;
  8003. gl.bindBuffer( bufferType, buffer );
  8004. if ( updateRange.count === - 1 ) {
  8005. // Not using update ranges
  8006. gl.bufferSubData( bufferType, 0, array );
  8007. } else {
  8008. if ( isWebGL2 ) {
  8009. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8010. array, updateRange.offset, updateRange.count );
  8011. } else {
  8012. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8013. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8014. }
  8015. updateRange.count = - 1; // reset range
  8016. }
  8017. attribute.onUploadCallback();
  8018. }
  8019. //
  8020. function get( attribute ) {
  8021. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8022. return buffers.get( attribute );
  8023. }
  8024. function remove( attribute ) {
  8025. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8026. const data = buffers.get( attribute );
  8027. if ( data ) {
  8028. gl.deleteBuffer( data.buffer );
  8029. buffers.delete( attribute );
  8030. }
  8031. }
  8032. function update( attribute, bufferType ) {
  8033. if ( attribute.isGLBufferAttribute ) {
  8034. const cached = buffers.get( attribute );
  8035. if ( ! cached || cached.version < attribute.version ) {
  8036. buffers.set( attribute, {
  8037. buffer: attribute.buffer,
  8038. type: attribute.type,
  8039. bytesPerElement: attribute.elementSize,
  8040. version: attribute.version
  8041. } );
  8042. }
  8043. return;
  8044. }
  8045. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8046. const data = buffers.get( attribute );
  8047. if ( data === undefined ) {
  8048. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8049. } else if ( data.version < attribute.version ) {
  8050. updateBuffer( data.buffer, attribute, bufferType );
  8051. data.version = attribute.version;
  8052. }
  8053. }
  8054. return {
  8055. get: get,
  8056. remove: remove,
  8057. update: update
  8058. };
  8059. }
  8060. class PlaneGeometry extends BufferGeometry {
  8061. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8062. super();
  8063. this.type = 'PlaneGeometry';
  8064. this.parameters = {
  8065. width: width,
  8066. height: height,
  8067. widthSegments: widthSegments,
  8068. heightSegments: heightSegments
  8069. };
  8070. const width_half = width / 2;
  8071. const height_half = height / 2;
  8072. const gridX = Math.floor( widthSegments );
  8073. const gridY = Math.floor( heightSegments );
  8074. const gridX1 = gridX + 1;
  8075. const gridY1 = gridY + 1;
  8076. const segment_width = width / gridX;
  8077. const segment_height = height / gridY;
  8078. //
  8079. const indices = [];
  8080. const vertices = [];
  8081. const normals = [];
  8082. const uvs = [];
  8083. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8084. const y = iy * segment_height - height_half;
  8085. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8086. const x = ix * segment_width - width_half;
  8087. vertices.push( x, - y, 0 );
  8088. normals.push( 0, 0, 1 );
  8089. uvs.push( ix / gridX );
  8090. uvs.push( 1 - ( iy / gridY ) );
  8091. }
  8092. }
  8093. for ( let iy = 0; iy < gridY; iy ++ ) {
  8094. for ( let ix = 0; ix < gridX; ix ++ ) {
  8095. const a = ix + gridX1 * iy;
  8096. const b = ix + gridX1 * ( iy + 1 );
  8097. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8098. const d = ( ix + 1 ) + gridX1 * iy;
  8099. indices.push( a, b, d );
  8100. indices.push( b, c, d );
  8101. }
  8102. }
  8103. this.setIndex( indices );
  8104. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8105. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8106. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8107. }
  8108. copy( source ) {
  8109. super.copy( source );
  8110. this.parameters = Object.assign( {}, source.parameters );
  8111. return this;
  8112. }
  8113. static fromJSON( data ) {
  8114. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8115. }
  8116. }
  8117. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8118. 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";
  8119. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8120. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8121. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8122. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8123. 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_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";
  8124. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8125. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8126. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8127. 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";
  8128. 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";
  8129. 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 = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = 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";
  8130. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  8131. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8132. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8133. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8134. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8135. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8136. 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";
  8137. 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";
  8138. 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";
  8139. 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_v0 0.339\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_v1 0.276\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_v4 0.046\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_v5 0.016\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_v6 0.0038\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";
  8140. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8141. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8142. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8143. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8144. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8145. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8146. 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}";
  8147. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  8148. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  8149. 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";
  8150. 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";
  8151. 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";
  8152. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8153. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8154. 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";
  8155. 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";
  8156. 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}";
  8157. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8158. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8159. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8160. 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";
  8161. 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";
  8162. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  8163. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8164. 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";
  8165. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8166. 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";
  8167. 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\tanisotropyV /= material.anisotropy;\n\tmaterial.anisotropy = saturate( material.anisotropy );\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";
  8168. 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 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = 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\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += 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\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += 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}";
  8169. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal;\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";
  8170. 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";
  8171. 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";
  8172. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8173. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8174. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8175. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  8176. 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";
  8177. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8178. 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";
  8179. 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";
  8180. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8181. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8182. 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";
  8183. 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";
  8184. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  8185. 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";
  8186. 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;";
  8187. 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";
  8188. 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";
  8189. 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";
  8190. 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";
  8191. 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";
  8192. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8193. 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";
  8194. 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";
  8195. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8196. 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 );";
  8197. 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}";
  8198. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8199. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8200. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8201. 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";
  8202. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8203. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8204. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8205. 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";
  8206. 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";
  8207. 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}";
  8208. 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";
  8209. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  8210. 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";
  8211. 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";
  8212. 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";
  8213. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8214. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8215. 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}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8216. 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";
  8217. 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";
  8218. 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";
  8219. 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";
  8220. 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";
  8221. 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_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8222. 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}";
  8223. 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}";
  8224. 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}";
  8225. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8226. 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}";
  8227. 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}";
  8228. const vertex$e = "#include <common>\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 <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8229. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8230. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\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 <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  8231. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8232. 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}";
  8233. 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}";
  8234. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8235. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8236. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#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}";
  8237. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8238. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\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 <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}";
  8239. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8240. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <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}";
  8241. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8242. 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 <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 <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8243. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8244. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\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 <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}";
  8245. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8246. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <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}";
  8247. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\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 ) + clearcoatSpecular * 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}";
  8248. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <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}";
  8249. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8250. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8251. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8252. const vertex$2 = "#include <common>\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 <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8253. 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}";
  8254. 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}";
  8255. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8256. const ShaderChunk = {
  8257. alphahash_fragment: alphahash_fragment,
  8258. alphahash_pars_fragment: alphahash_pars_fragment,
  8259. alphamap_fragment: alphamap_fragment,
  8260. alphamap_pars_fragment: alphamap_pars_fragment,
  8261. alphatest_fragment: alphatest_fragment,
  8262. alphatest_pars_fragment: alphatest_pars_fragment,
  8263. aomap_fragment: aomap_fragment,
  8264. aomap_pars_fragment: aomap_pars_fragment,
  8265. begin_vertex: begin_vertex,
  8266. beginnormal_vertex: beginnormal_vertex,
  8267. bsdfs: bsdfs,
  8268. iridescence_fragment: iridescence_fragment,
  8269. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8270. clipping_planes_fragment: clipping_planes_fragment,
  8271. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8272. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8273. clipping_planes_vertex: clipping_planes_vertex,
  8274. color_fragment: color_fragment,
  8275. color_pars_fragment: color_pars_fragment,
  8276. color_pars_vertex: color_pars_vertex,
  8277. color_vertex: color_vertex,
  8278. common: common,
  8279. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8280. defaultnormal_vertex: defaultnormal_vertex,
  8281. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8282. displacementmap_vertex: displacementmap_vertex,
  8283. emissivemap_fragment: emissivemap_fragment,
  8284. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8285. colorspace_fragment: colorspace_fragment,
  8286. colorspace_pars_fragment: colorspace_pars_fragment,
  8287. envmap_fragment: envmap_fragment,
  8288. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8289. envmap_pars_fragment: envmap_pars_fragment,
  8290. envmap_pars_vertex: envmap_pars_vertex,
  8291. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8292. envmap_vertex: envmap_vertex,
  8293. fog_vertex: fog_vertex,
  8294. fog_pars_vertex: fog_pars_vertex,
  8295. fog_fragment: fog_fragment,
  8296. fog_pars_fragment: fog_pars_fragment,
  8297. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8298. lightmap_fragment: lightmap_fragment,
  8299. lightmap_pars_fragment: lightmap_pars_fragment,
  8300. lights_lambert_fragment: lights_lambert_fragment,
  8301. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8302. lights_pars_begin: lights_pars_begin,
  8303. lights_toon_fragment: lights_toon_fragment,
  8304. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8305. lights_phong_fragment: lights_phong_fragment,
  8306. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8307. lights_physical_fragment: lights_physical_fragment,
  8308. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8309. lights_fragment_begin: lights_fragment_begin,
  8310. lights_fragment_maps: lights_fragment_maps,
  8311. lights_fragment_end: lights_fragment_end,
  8312. logdepthbuf_fragment: logdepthbuf_fragment,
  8313. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8314. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8315. logdepthbuf_vertex: logdepthbuf_vertex,
  8316. map_fragment: map_fragment,
  8317. map_pars_fragment: map_pars_fragment,
  8318. map_particle_fragment: map_particle_fragment,
  8319. map_particle_pars_fragment: map_particle_pars_fragment,
  8320. metalnessmap_fragment: metalnessmap_fragment,
  8321. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8322. morphcolor_vertex: morphcolor_vertex,
  8323. morphnormal_vertex: morphnormal_vertex,
  8324. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8325. morphtarget_vertex: morphtarget_vertex,
  8326. normal_fragment_begin: normal_fragment_begin,
  8327. normal_fragment_maps: normal_fragment_maps,
  8328. normal_pars_fragment: normal_pars_fragment,
  8329. normal_pars_vertex: normal_pars_vertex,
  8330. normal_vertex: normal_vertex,
  8331. normalmap_pars_fragment: normalmap_pars_fragment,
  8332. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8333. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8334. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8335. iridescence_pars_fragment: iridescence_pars_fragment,
  8336. opaque_fragment: opaque_fragment,
  8337. packing: packing,
  8338. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8339. project_vertex: project_vertex,
  8340. dithering_fragment: dithering_fragment,
  8341. dithering_pars_fragment: dithering_pars_fragment,
  8342. roughnessmap_fragment: roughnessmap_fragment,
  8343. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8344. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8345. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8346. shadowmap_vertex: shadowmap_vertex,
  8347. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8348. skinbase_vertex: skinbase_vertex,
  8349. skinning_pars_vertex: skinning_pars_vertex,
  8350. skinning_vertex: skinning_vertex,
  8351. skinnormal_vertex: skinnormal_vertex,
  8352. specularmap_fragment: specularmap_fragment,
  8353. specularmap_pars_fragment: specularmap_pars_fragment,
  8354. tonemapping_fragment: tonemapping_fragment,
  8355. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8356. transmission_fragment: transmission_fragment,
  8357. transmission_pars_fragment: transmission_pars_fragment,
  8358. uv_pars_fragment: uv_pars_fragment,
  8359. uv_pars_vertex: uv_pars_vertex,
  8360. uv_vertex: uv_vertex,
  8361. worldpos_vertex: worldpos_vertex,
  8362. background_vert: vertex$h,
  8363. background_frag: fragment$h,
  8364. backgroundCube_vert: vertex$g,
  8365. backgroundCube_frag: fragment$g,
  8366. cube_vert: vertex$f,
  8367. cube_frag: fragment$f,
  8368. depth_vert: vertex$e,
  8369. depth_frag: fragment$e,
  8370. distanceRGBA_vert: vertex$d,
  8371. distanceRGBA_frag: fragment$d,
  8372. equirect_vert: vertex$c,
  8373. equirect_frag: fragment$c,
  8374. linedashed_vert: vertex$b,
  8375. linedashed_frag: fragment$b,
  8376. meshbasic_vert: vertex$a,
  8377. meshbasic_frag: fragment$a,
  8378. meshlambert_vert: vertex$9,
  8379. meshlambert_frag: fragment$9,
  8380. meshmatcap_vert: vertex$8,
  8381. meshmatcap_frag: fragment$8,
  8382. meshnormal_vert: vertex$7,
  8383. meshnormal_frag: fragment$7,
  8384. meshphong_vert: vertex$6,
  8385. meshphong_frag: fragment$6,
  8386. meshphysical_vert: vertex$5,
  8387. meshphysical_frag: fragment$5,
  8388. meshtoon_vert: vertex$4,
  8389. meshtoon_frag: fragment$4,
  8390. points_vert: vertex$3,
  8391. points_frag: fragment$3,
  8392. shadow_vert: vertex$2,
  8393. shadow_frag: fragment$2,
  8394. sprite_vert: vertex$1,
  8395. sprite_frag: fragment$1
  8396. };
  8397. /**
  8398. * Uniforms library for shared webgl shaders
  8399. */
  8400. const UniformsLib = {
  8401. common: {
  8402. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8403. opacity: { value: 1.0 },
  8404. map: { value: null },
  8405. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8406. alphaMap: { value: null },
  8407. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8408. alphaTest: { value: 0 }
  8409. },
  8410. specularmap: {
  8411. specularMap: { value: null },
  8412. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8413. },
  8414. envmap: {
  8415. envMap: { value: null },
  8416. flipEnvMap: { value: - 1 },
  8417. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8418. ior: { value: 1.5 }, // physical
  8419. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8420. },
  8421. aomap: {
  8422. aoMap: { value: null },
  8423. aoMapIntensity: { value: 1 },
  8424. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8425. },
  8426. lightmap: {
  8427. lightMap: { value: null },
  8428. lightMapIntensity: { value: 1 },
  8429. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8430. },
  8431. bumpmap: {
  8432. bumpMap: { value: null },
  8433. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8434. bumpScale: { value: 1 }
  8435. },
  8436. normalmap: {
  8437. normalMap: { value: null },
  8438. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8439. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8440. },
  8441. displacementmap: {
  8442. displacementMap: { value: null },
  8443. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8444. displacementScale: { value: 1 },
  8445. displacementBias: { value: 0 }
  8446. },
  8447. emissivemap: {
  8448. emissiveMap: { value: null },
  8449. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8450. },
  8451. metalnessmap: {
  8452. metalnessMap: { value: null },
  8453. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8454. },
  8455. roughnessmap: {
  8456. roughnessMap: { value: null },
  8457. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8458. },
  8459. gradientmap: {
  8460. gradientMap: { value: null }
  8461. },
  8462. fog: {
  8463. fogDensity: { value: 0.00025 },
  8464. fogNear: { value: 1 },
  8465. fogFar: { value: 2000 },
  8466. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8467. },
  8468. lights: {
  8469. ambientLightColor: { value: [] },
  8470. lightProbe: { value: [] },
  8471. directionalLights: { value: [], properties: {
  8472. direction: {},
  8473. color: {}
  8474. } },
  8475. directionalLightShadows: { value: [], properties: {
  8476. shadowBias: {},
  8477. shadowNormalBias: {},
  8478. shadowRadius: {},
  8479. shadowMapSize: {}
  8480. } },
  8481. directionalShadowMap: { value: [] },
  8482. directionalShadowMatrix: { value: [] },
  8483. spotLights: { value: [], properties: {
  8484. color: {},
  8485. position: {},
  8486. direction: {},
  8487. distance: {},
  8488. coneCos: {},
  8489. penumbraCos: {},
  8490. decay: {}
  8491. } },
  8492. spotLightShadows: { value: [], properties: {
  8493. shadowBias: {},
  8494. shadowNormalBias: {},
  8495. shadowRadius: {},
  8496. shadowMapSize: {}
  8497. } },
  8498. spotLightMap: { value: [] },
  8499. spotShadowMap: { value: [] },
  8500. spotLightMatrix: { value: [] },
  8501. pointLights: { value: [], properties: {
  8502. color: {},
  8503. position: {},
  8504. decay: {},
  8505. distance: {}
  8506. } },
  8507. pointLightShadows: { value: [], properties: {
  8508. shadowBias: {},
  8509. shadowNormalBias: {},
  8510. shadowRadius: {},
  8511. shadowMapSize: {},
  8512. shadowCameraNear: {},
  8513. shadowCameraFar: {}
  8514. } },
  8515. pointShadowMap: { value: [] },
  8516. pointShadowMatrix: { value: [] },
  8517. hemisphereLights: { value: [], properties: {
  8518. direction: {},
  8519. skyColor: {},
  8520. groundColor: {}
  8521. } },
  8522. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8523. rectAreaLights: { value: [], properties: {
  8524. color: {},
  8525. position: {},
  8526. width: {},
  8527. height: {}
  8528. } },
  8529. ltc_1: { value: null },
  8530. ltc_2: { value: null }
  8531. },
  8532. points: {
  8533. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8534. opacity: { value: 1.0 },
  8535. size: { value: 1.0 },
  8536. scale: { value: 1.0 },
  8537. map: { value: null },
  8538. alphaMap: { value: null },
  8539. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8540. alphaTest: { value: 0 },
  8541. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8542. },
  8543. sprite: {
  8544. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8545. opacity: { value: 1.0 },
  8546. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8547. rotation: { value: 0.0 },
  8548. map: { value: null },
  8549. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8550. alphaMap: { value: null },
  8551. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8552. alphaTest: { value: 0 }
  8553. }
  8554. };
  8555. const ShaderLib = {
  8556. basic: {
  8557. uniforms: /*@__PURE__*/ mergeUniforms( [
  8558. UniformsLib.common,
  8559. UniformsLib.specularmap,
  8560. UniformsLib.envmap,
  8561. UniformsLib.aomap,
  8562. UniformsLib.lightmap,
  8563. UniformsLib.fog
  8564. ] ),
  8565. vertexShader: ShaderChunk.meshbasic_vert,
  8566. fragmentShader: ShaderChunk.meshbasic_frag
  8567. },
  8568. lambert: {
  8569. uniforms: /*@__PURE__*/ mergeUniforms( [
  8570. UniformsLib.common,
  8571. UniformsLib.specularmap,
  8572. UniformsLib.envmap,
  8573. UniformsLib.aomap,
  8574. UniformsLib.lightmap,
  8575. UniformsLib.emissivemap,
  8576. UniformsLib.bumpmap,
  8577. UniformsLib.normalmap,
  8578. UniformsLib.displacementmap,
  8579. UniformsLib.fog,
  8580. UniformsLib.lights,
  8581. {
  8582. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8583. }
  8584. ] ),
  8585. vertexShader: ShaderChunk.meshlambert_vert,
  8586. fragmentShader: ShaderChunk.meshlambert_frag
  8587. },
  8588. phong: {
  8589. uniforms: /*@__PURE__*/ mergeUniforms( [
  8590. UniformsLib.common,
  8591. UniformsLib.specularmap,
  8592. UniformsLib.envmap,
  8593. UniformsLib.aomap,
  8594. UniformsLib.lightmap,
  8595. UniformsLib.emissivemap,
  8596. UniformsLib.bumpmap,
  8597. UniformsLib.normalmap,
  8598. UniformsLib.displacementmap,
  8599. UniformsLib.fog,
  8600. UniformsLib.lights,
  8601. {
  8602. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8603. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8604. shininess: { value: 30 }
  8605. }
  8606. ] ),
  8607. vertexShader: ShaderChunk.meshphong_vert,
  8608. fragmentShader: ShaderChunk.meshphong_frag
  8609. },
  8610. standard: {
  8611. uniforms: /*@__PURE__*/ mergeUniforms( [
  8612. UniformsLib.common,
  8613. UniformsLib.envmap,
  8614. UniformsLib.aomap,
  8615. UniformsLib.lightmap,
  8616. UniformsLib.emissivemap,
  8617. UniformsLib.bumpmap,
  8618. UniformsLib.normalmap,
  8619. UniformsLib.displacementmap,
  8620. UniformsLib.roughnessmap,
  8621. UniformsLib.metalnessmap,
  8622. UniformsLib.fog,
  8623. UniformsLib.lights,
  8624. {
  8625. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8626. roughness: { value: 1.0 },
  8627. metalness: { value: 0.0 },
  8628. envMapIntensity: { value: 1 } // temporary
  8629. }
  8630. ] ),
  8631. vertexShader: ShaderChunk.meshphysical_vert,
  8632. fragmentShader: ShaderChunk.meshphysical_frag
  8633. },
  8634. toon: {
  8635. uniforms: /*@__PURE__*/ mergeUniforms( [
  8636. UniformsLib.common,
  8637. UniformsLib.aomap,
  8638. UniformsLib.lightmap,
  8639. UniformsLib.emissivemap,
  8640. UniformsLib.bumpmap,
  8641. UniformsLib.normalmap,
  8642. UniformsLib.displacementmap,
  8643. UniformsLib.gradientmap,
  8644. UniformsLib.fog,
  8645. UniformsLib.lights,
  8646. {
  8647. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8648. }
  8649. ] ),
  8650. vertexShader: ShaderChunk.meshtoon_vert,
  8651. fragmentShader: ShaderChunk.meshtoon_frag
  8652. },
  8653. matcap: {
  8654. uniforms: /*@__PURE__*/ mergeUniforms( [
  8655. UniformsLib.common,
  8656. UniformsLib.bumpmap,
  8657. UniformsLib.normalmap,
  8658. UniformsLib.displacementmap,
  8659. UniformsLib.fog,
  8660. {
  8661. matcap: { value: null }
  8662. }
  8663. ] ),
  8664. vertexShader: ShaderChunk.meshmatcap_vert,
  8665. fragmentShader: ShaderChunk.meshmatcap_frag
  8666. },
  8667. points: {
  8668. uniforms: /*@__PURE__*/ mergeUniforms( [
  8669. UniformsLib.points,
  8670. UniformsLib.fog
  8671. ] ),
  8672. vertexShader: ShaderChunk.points_vert,
  8673. fragmentShader: ShaderChunk.points_frag
  8674. },
  8675. dashed: {
  8676. uniforms: /*@__PURE__*/ mergeUniforms( [
  8677. UniformsLib.common,
  8678. UniformsLib.fog,
  8679. {
  8680. scale: { value: 1 },
  8681. dashSize: { value: 1 },
  8682. totalSize: { value: 2 }
  8683. }
  8684. ] ),
  8685. vertexShader: ShaderChunk.linedashed_vert,
  8686. fragmentShader: ShaderChunk.linedashed_frag
  8687. },
  8688. depth: {
  8689. uniforms: /*@__PURE__*/ mergeUniforms( [
  8690. UniformsLib.common,
  8691. UniformsLib.displacementmap
  8692. ] ),
  8693. vertexShader: ShaderChunk.depth_vert,
  8694. fragmentShader: ShaderChunk.depth_frag
  8695. },
  8696. normal: {
  8697. uniforms: /*@__PURE__*/ mergeUniforms( [
  8698. UniformsLib.common,
  8699. UniformsLib.bumpmap,
  8700. UniformsLib.normalmap,
  8701. UniformsLib.displacementmap,
  8702. {
  8703. opacity: { value: 1.0 }
  8704. }
  8705. ] ),
  8706. vertexShader: ShaderChunk.meshnormal_vert,
  8707. fragmentShader: ShaderChunk.meshnormal_frag
  8708. },
  8709. sprite: {
  8710. uniforms: /*@__PURE__*/ mergeUniforms( [
  8711. UniformsLib.sprite,
  8712. UniformsLib.fog
  8713. ] ),
  8714. vertexShader: ShaderChunk.sprite_vert,
  8715. fragmentShader: ShaderChunk.sprite_frag
  8716. },
  8717. background: {
  8718. uniforms: {
  8719. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8720. t2D: { value: null },
  8721. backgroundIntensity: { value: 1 }
  8722. },
  8723. vertexShader: ShaderChunk.background_vert,
  8724. fragmentShader: ShaderChunk.background_frag
  8725. },
  8726. backgroundCube: {
  8727. uniforms: {
  8728. envMap: { value: null },
  8729. flipEnvMap: { value: - 1 },
  8730. backgroundBlurriness: { value: 0 },
  8731. backgroundIntensity: { value: 1 }
  8732. },
  8733. vertexShader: ShaderChunk.backgroundCube_vert,
  8734. fragmentShader: ShaderChunk.backgroundCube_frag
  8735. },
  8736. cube: {
  8737. uniforms: {
  8738. tCube: { value: null },
  8739. tFlip: { value: - 1 },
  8740. opacity: { value: 1.0 }
  8741. },
  8742. vertexShader: ShaderChunk.cube_vert,
  8743. fragmentShader: ShaderChunk.cube_frag
  8744. },
  8745. equirect: {
  8746. uniforms: {
  8747. tEquirect: { value: null },
  8748. },
  8749. vertexShader: ShaderChunk.equirect_vert,
  8750. fragmentShader: ShaderChunk.equirect_frag
  8751. },
  8752. distanceRGBA: {
  8753. uniforms: /*@__PURE__*/ mergeUniforms( [
  8754. UniformsLib.common,
  8755. UniformsLib.displacementmap,
  8756. {
  8757. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8758. nearDistance: { value: 1 },
  8759. farDistance: { value: 1000 }
  8760. }
  8761. ] ),
  8762. vertexShader: ShaderChunk.distanceRGBA_vert,
  8763. fragmentShader: ShaderChunk.distanceRGBA_frag
  8764. },
  8765. shadow: {
  8766. uniforms: /*@__PURE__*/ mergeUniforms( [
  8767. UniformsLib.lights,
  8768. UniformsLib.fog,
  8769. {
  8770. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8771. opacity: { value: 1.0 }
  8772. },
  8773. ] ),
  8774. vertexShader: ShaderChunk.shadow_vert,
  8775. fragmentShader: ShaderChunk.shadow_frag
  8776. }
  8777. };
  8778. ShaderLib.physical = {
  8779. uniforms: /*@__PURE__*/ mergeUniforms( [
  8780. ShaderLib.standard.uniforms,
  8781. {
  8782. clearcoat: { value: 0 },
  8783. clearcoatMap: { value: null },
  8784. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8785. clearcoatNormalMap: { value: null },
  8786. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8787. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8788. clearcoatRoughness: { value: 0 },
  8789. clearcoatRoughnessMap: { value: null },
  8790. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8791. iridescence: { value: 0 },
  8792. iridescenceMap: { value: null },
  8793. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8794. iridescenceIOR: { value: 1.3 },
  8795. iridescenceThicknessMinimum: { value: 100 },
  8796. iridescenceThicknessMaximum: { value: 400 },
  8797. iridescenceThicknessMap: { value: null },
  8798. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8799. sheen: { value: 0 },
  8800. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8801. sheenColorMap: { value: null },
  8802. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8803. sheenRoughness: { value: 1 },
  8804. sheenRoughnessMap: { value: null },
  8805. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8806. transmission: { value: 0 },
  8807. transmissionMap: { value: null },
  8808. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8809. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8810. transmissionSamplerMap: { value: null },
  8811. thickness: { value: 0 },
  8812. thicknessMap: { value: null },
  8813. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8814. attenuationDistance: { value: 0 },
  8815. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8816. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8817. specularColorMap: { value: null },
  8818. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8819. specularIntensity: { value: 1 },
  8820. specularIntensityMap: { value: null },
  8821. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8822. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8823. anisotropyMap: { value: null },
  8824. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8825. }
  8826. ] ),
  8827. vertexShader: ShaderChunk.meshphysical_vert,
  8828. fragmentShader: ShaderChunk.meshphysical_frag
  8829. };
  8830. const _rgb = { r: 0, b: 0, g: 0 };
  8831. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8832. const clearColor = new Color( 0x000000 );
  8833. let clearAlpha = alpha === true ? 0 : 1;
  8834. let planeMesh;
  8835. let boxMesh;
  8836. let currentBackground = null;
  8837. let currentBackgroundVersion = 0;
  8838. let currentTonemapping = null;
  8839. function render( renderList, scene ) {
  8840. let forceClear = false;
  8841. let background = scene.isScene === true ? scene.background : null;
  8842. if ( background && background.isTexture ) {
  8843. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8844. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8845. }
  8846. if ( background === null ) {
  8847. setClear( clearColor, clearAlpha );
  8848. } else if ( background && background.isColor ) {
  8849. setClear( background, 1 );
  8850. forceClear = true;
  8851. }
  8852. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8853. if ( environmentBlendMode === 'additive' ) {
  8854. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8855. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8856. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8857. }
  8858. if ( renderer.autoClear || forceClear ) {
  8859. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8860. }
  8861. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8862. if ( boxMesh === undefined ) {
  8863. boxMesh = new Mesh(
  8864. new BoxGeometry( 1, 1, 1 ),
  8865. new ShaderMaterial( {
  8866. name: 'BackgroundCubeMaterial',
  8867. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8868. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8869. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8870. side: BackSide,
  8871. depthTest: false,
  8872. depthWrite: false,
  8873. fog: false
  8874. } )
  8875. );
  8876. boxMesh.geometry.deleteAttribute( 'normal' );
  8877. boxMesh.geometry.deleteAttribute( 'uv' );
  8878. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8879. this.matrixWorld.copyPosition( camera.matrixWorld );
  8880. };
  8881. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8882. Object.defineProperty( boxMesh.material, 'envMap', {
  8883. get: function () {
  8884. return this.uniforms.envMap.value;
  8885. }
  8886. } );
  8887. objects.update( boxMesh );
  8888. }
  8889. boxMesh.material.uniforms.envMap.value = background;
  8890. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8891. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8892. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8893. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8894. if ( currentBackground !== background ||
  8895. currentBackgroundVersion !== background.version ||
  8896. currentTonemapping !== renderer.toneMapping ) {
  8897. boxMesh.material.needsUpdate = true;
  8898. currentBackground = background;
  8899. currentBackgroundVersion = background.version;
  8900. currentTonemapping = renderer.toneMapping;
  8901. }
  8902. boxMesh.layers.enableAll();
  8903. // push to the pre-sorted opaque render list
  8904. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8905. } else if ( background && background.isTexture ) {
  8906. if ( planeMesh === undefined ) {
  8907. planeMesh = new Mesh(
  8908. new PlaneGeometry( 2, 2 ),
  8909. new ShaderMaterial( {
  8910. name: 'BackgroundMaterial',
  8911. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8912. vertexShader: ShaderLib.background.vertexShader,
  8913. fragmentShader: ShaderLib.background.fragmentShader,
  8914. side: FrontSide,
  8915. depthTest: false,
  8916. depthWrite: false,
  8917. fog: false
  8918. } )
  8919. );
  8920. planeMesh.geometry.deleteAttribute( 'normal' );
  8921. // add "map" material property so the renderer can evaluate it like for built-in materials
  8922. Object.defineProperty( planeMesh.material, 'map', {
  8923. get: function () {
  8924. return this.uniforms.t2D.value;
  8925. }
  8926. } );
  8927. objects.update( planeMesh );
  8928. }
  8929. planeMesh.material.uniforms.t2D.value = background;
  8930. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8931. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8932. if ( background.matrixAutoUpdate === true ) {
  8933. background.updateMatrix();
  8934. }
  8935. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8936. if ( currentBackground !== background ||
  8937. currentBackgroundVersion !== background.version ||
  8938. currentTonemapping !== renderer.toneMapping ) {
  8939. planeMesh.material.needsUpdate = true;
  8940. currentBackground = background;
  8941. currentBackgroundVersion = background.version;
  8942. currentTonemapping = renderer.toneMapping;
  8943. }
  8944. planeMesh.layers.enableAll();
  8945. // push to the pre-sorted opaque render list
  8946. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8947. }
  8948. }
  8949. function setClear( color, alpha ) {
  8950. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8951. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8952. }
  8953. return {
  8954. getClearColor: function () {
  8955. return clearColor;
  8956. },
  8957. setClearColor: function ( color, alpha = 1 ) {
  8958. clearColor.set( color );
  8959. clearAlpha = alpha;
  8960. setClear( clearColor, clearAlpha );
  8961. },
  8962. getClearAlpha: function () {
  8963. return clearAlpha;
  8964. },
  8965. setClearAlpha: function ( alpha ) {
  8966. clearAlpha = alpha;
  8967. setClear( clearColor, clearAlpha );
  8968. },
  8969. render: render
  8970. };
  8971. }
  8972. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8973. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8974. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8975. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8976. const bindingStates = {};
  8977. const defaultState = createBindingState( null );
  8978. let currentState = defaultState;
  8979. let forceUpdate = false;
  8980. function setup( object, material, program, geometry, index ) {
  8981. let updateBuffers = false;
  8982. if ( vaoAvailable ) {
  8983. const state = getBindingState( geometry, program, material );
  8984. if ( currentState !== state ) {
  8985. currentState = state;
  8986. bindVertexArrayObject( currentState.object );
  8987. }
  8988. updateBuffers = needsUpdate( object, geometry, program, index );
  8989. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8990. } else {
  8991. const wireframe = ( material.wireframe === true );
  8992. if ( currentState.geometry !== geometry.id ||
  8993. currentState.program !== program.id ||
  8994. currentState.wireframe !== wireframe ) {
  8995. currentState.geometry = geometry.id;
  8996. currentState.program = program.id;
  8997. currentState.wireframe = wireframe;
  8998. updateBuffers = true;
  8999. }
  9000. }
  9001. if ( index !== null ) {
  9002. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9003. }
  9004. if ( updateBuffers || forceUpdate ) {
  9005. forceUpdate = false;
  9006. setupVertexAttributes( object, material, program, geometry );
  9007. if ( index !== null ) {
  9008. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9009. }
  9010. }
  9011. }
  9012. function createVertexArrayObject() {
  9013. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9014. return extension.createVertexArrayOES();
  9015. }
  9016. function bindVertexArrayObject( vao ) {
  9017. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9018. return extension.bindVertexArrayOES( vao );
  9019. }
  9020. function deleteVertexArrayObject( vao ) {
  9021. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9022. return extension.deleteVertexArrayOES( vao );
  9023. }
  9024. function getBindingState( geometry, program, material ) {
  9025. const wireframe = ( material.wireframe === true );
  9026. let programMap = bindingStates[ geometry.id ];
  9027. if ( programMap === undefined ) {
  9028. programMap = {};
  9029. bindingStates[ geometry.id ] = programMap;
  9030. }
  9031. let stateMap = programMap[ program.id ];
  9032. if ( stateMap === undefined ) {
  9033. stateMap = {};
  9034. programMap[ program.id ] = stateMap;
  9035. }
  9036. let state = stateMap[ wireframe ];
  9037. if ( state === undefined ) {
  9038. state = createBindingState( createVertexArrayObject() );
  9039. stateMap[ wireframe ] = state;
  9040. }
  9041. return state;
  9042. }
  9043. function createBindingState( vao ) {
  9044. const newAttributes = [];
  9045. const enabledAttributes = [];
  9046. const attributeDivisors = [];
  9047. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9048. newAttributes[ i ] = 0;
  9049. enabledAttributes[ i ] = 0;
  9050. attributeDivisors[ i ] = 0;
  9051. }
  9052. return {
  9053. // for backward compatibility on non-VAO support browser
  9054. geometry: null,
  9055. program: null,
  9056. wireframe: false,
  9057. newAttributes: newAttributes,
  9058. enabledAttributes: enabledAttributes,
  9059. attributeDivisors: attributeDivisors,
  9060. object: vao,
  9061. attributes: {},
  9062. index: null
  9063. };
  9064. }
  9065. function needsUpdate( object, geometry, program, index ) {
  9066. const cachedAttributes = currentState.attributes;
  9067. const geometryAttributes = geometry.attributes;
  9068. let attributesNum = 0;
  9069. const programAttributes = program.getAttributes();
  9070. for ( const name in programAttributes ) {
  9071. const programAttribute = programAttributes[ name ];
  9072. if ( programAttribute.location >= 0 ) {
  9073. const cachedAttribute = cachedAttributes[ name ];
  9074. let geometryAttribute = geometryAttributes[ name ];
  9075. if ( geometryAttribute === undefined ) {
  9076. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9077. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9078. }
  9079. if ( cachedAttribute === undefined ) return true;
  9080. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9081. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9082. attributesNum ++;
  9083. }
  9084. }
  9085. if ( currentState.attributesNum !== attributesNum ) return true;
  9086. if ( currentState.index !== index ) return true;
  9087. return false;
  9088. }
  9089. function saveCache( object, geometry, program, index ) {
  9090. const cache = {};
  9091. const attributes = geometry.attributes;
  9092. let attributesNum = 0;
  9093. const programAttributes = program.getAttributes();
  9094. for ( const name in programAttributes ) {
  9095. const programAttribute = programAttributes[ name ];
  9096. if ( programAttribute.location >= 0 ) {
  9097. let attribute = attributes[ name ];
  9098. if ( attribute === undefined ) {
  9099. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9100. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9101. }
  9102. const data = {};
  9103. data.attribute = attribute;
  9104. if ( attribute && attribute.data ) {
  9105. data.data = attribute.data;
  9106. }
  9107. cache[ name ] = data;
  9108. attributesNum ++;
  9109. }
  9110. }
  9111. currentState.attributes = cache;
  9112. currentState.attributesNum = attributesNum;
  9113. currentState.index = index;
  9114. }
  9115. function initAttributes() {
  9116. const newAttributes = currentState.newAttributes;
  9117. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9118. newAttributes[ i ] = 0;
  9119. }
  9120. }
  9121. function enableAttribute( attribute ) {
  9122. enableAttributeAndDivisor( attribute, 0 );
  9123. }
  9124. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9125. const newAttributes = currentState.newAttributes;
  9126. const enabledAttributes = currentState.enabledAttributes;
  9127. const attributeDivisors = currentState.attributeDivisors;
  9128. newAttributes[ attribute ] = 1;
  9129. if ( enabledAttributes[ attribute ] === 0 ) {
  9130. gl.enableVertexAttribArray( attribute );
  9131. enabledAttributes[ attribute ] = 1;
  9132. }
  9133. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9134. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9135. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9136. attributeDivisors[ attribute ] = meshPerAttribute;
  9137. }
  9138. }
  9139. function disableUnusedAttributes() {
  9140. const newAttributes = currentState.newAttributes;
  9141. const enabledAttributes = currentState.enabledAttributes;
  9142. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9143. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9144. gl.disableVertexAttribArray( i );
  9145. enabledAttributes[ i ] = 0;
  9146. }
  9147. }
  9148. }
  9149. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9150. if ( integer === true ) {
  9151. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9152. } else {
  9153. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9154. }
  9155. }
  9156. function setupVertexAttributes( object, material, program, geometry ) {
  9157. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9158. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9159. }
  9160. initAttributes();
  9161. const geometryAttributes = geometry.attributes;
  9162. const programAttributes = program.getAttributes();
  9163. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9164. for ( const name in programAttributes ) {
  9165. const programAttribute = programAttributes[ name ];
  9166. if ( programAttribute.location >= 0 ) {
  9167. let geometryAttribute = geometryAttributes[ name ];
  9168. if ( geometryAttribute === undefined ) {
  9169. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9170. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9171. }
  9172. if ( geometryAttribute !== undefined ) {
  9173. const normalized = geometryAttribute.normalized;
  9174. const size = geometryAttribute.itemSize;
  9175. const attribute = attributes.get( geometryAttribute );
  9176. // TODO Attribute may not be available on context restore
  9177. if ( attribute === undefined ) continue;
  9178. const buffer = attribute.buffer;
  9179. const type = attribute.type;
  9180. const bytesPerElement = attribute.bytesPerElement;
  9181. // check for integer attributes (WebGL 2 only)
  9182. const integer = ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ) );
  9183. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9184. const data = geometryAttribute.data;
  9185. const stride = data.stride;
  9186. const offset = geometryAttribute.offset;
  9187. if ( data.isInstancedInterleavedBuffer ) {
  9188. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9189. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9190. }
  9191. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9192. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9193. }
  9194. } else {
  9195. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9196. enableAttribute( programAttribute.location + i );
  9197. }
  9198. }
  9199. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9200. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9201. vertexAttribPointer(
  9202. programAttribute.location + i,
  9203. size / programAttribute.locationSize,
  9204. type,
  9205. normalized,
  9206. stride * bytesPerElement,
  9207. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9208. integer
  9209. );
  9210. }
  9211. } else {
  9212. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9213. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9214. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9215. }
  9216. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9217. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9218. }
  9219. } else {
  9220. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9221. enableAttribute( programAttribute.location + i );
  9222. }
  9223. }
  9224. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9225. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9226. vertexAttribPointer(
  9227. programAttribute.location + i,
  9228. size / programAttribute.locationSize,
  9229. type,
  9230. normalized,
  9231. size * bytesPerElement,
  9232. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9233. integer
  9234. );
  9235. }
  9236. }
  9237. } else if ( materialDefaultAttributeValues !== undefined ) {
  9238. const value = materialDefaultAttributeValues[ name ];
  9239. if ( value !== undefined ) {
  9240. switch ( value.length ) {
  9241. case 2:
  9242. gl.vertexAttrib2fv( programAttribute.location, value );
  9243. break;
  9244. case 3:
  9245. gl.vertexAttrib3fv( programAttribute.location, value );
  9246. break;
  9247. case 4:
  9248. gl.vertexAttrib4fv( programAttribute.location, value );
  9249. break;
  9250. default:
  9251. gl.vertexAttrib1fv( programAttribute.location, value );
  9252. }
  9253. }
  9254. }
  9255. }
  9256. }
  9257. disableUnusedAttributes();
  9258. }
  9259. function dispose() {
  9260. reset();
  9261. for ( const geometryId in bindingStates ) {
  9262. const programMap = bindingStates[ geometryId ];
  9263. for ( const programId in programMap ) {
  9264. const stateMap = programMap[ programId ];
  9265. for ( const wireframe in stateMap ) {
  9266. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9267. delete stateMap[ wireframe ];
  9268. }
  9269. delete programMap[ programId ];
  9270. }
  9271. delete bindingStates[ geometryId ];
  9272. }
  9273. }
  9274. function releaseStatesOfGeometry( geometry ) {
  9275. if ( bindingStates[ geometry.id ] === undefined ) return;
  9276. const programMap = bindingStates[ geometry.id ];
  9277. for ( const programId in programMap ) {
  9278. const stateMap = programMap[ programId ];
  9279. for ( const wireframe in stateMap ) {
  9280. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9281. delete stateMap[ wireframe ];
  9282. }
  9283. delete programMap[ programId ];
  9284. }
  9285. delete bindingStates[ geometry.id ];
  9286. }
  9287. function releaseStatesOfProgram( program ) {
  9288. for ( const geometryId in bindingStates ) {
  9289. const programMap = bindingStates[ geometryId ];
  9290. if ( programMap[ program.id ] === undefined ) continue;
  9291. const stateMap = programMap[ program.id ];
  9292. for ( const wireframe in stateMap ) {
  9293. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9294. delete stateMap[ wireframe ];
  9295. }
  9296. delete programMap[ program.id ];
  9297. }
  9298. }
  9299. function reset() {
  9300. resetDefaultState();
  9301. forceUpdate = true;
  9302. if ( currentState === defaultState ) return;
  9303. currentState = defaultState;
  9304. bindVertexArrayObject( currentState.object );
  9305. }
  9306. // for backward-compatibility
  9307. function resetDefaultState() {
  9308. defaultState.geometry = null;
  9309. defaultState.program = null;
  9310. defaultState.wireframe = false;
  9311. }
  9312. return {
  9313. setup: setup,
  9314. reset: reset,
  9315. resetDefaultState: resetDefaultState,
  9316. dispose: dispose,
  9317. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9318. releaseStatesOfProgram: releaseStatesOfProgram,
  9319. initAttributes: initAttributes,
  9320. enableAttribute: enableAttribute,
  9321. disableUnusedAttributes: disableUnusedAttributes
  9322. };
  9323. }
  9324. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9325. const isWebGL2 = capabilities.isWebGL2;
  9326. let mode;
  9327. function setMode( value ) {
  9328. mode = value;
  9329. }
  9330. function render( start, count ) {
  9331. gl.drawArrays( mode, start, count );
  9332. info.update( count, mode, 1 );
  9333. }
  9334. function renderInstances( start, count, primcount ) {
  9335. if ( primcount === 0 ) return;
  9336. let extension, methodName;
  9337. if ( isWebGL2 ) {
  9338. extension = gl;
  9339. methodName = 'drawArraysInstanced';
  9340. } else {
  9341. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9342. methodName = 'drawArraysInstancedANGLE';
  9343. if ( extension === null ) {
  9344. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9345. return;
  9346. }
  9347. }
  9348. extension[ methodName ]( mode, start, count, primcount );
  9349. info.update( count, mode, primcount );
  9350. }
  9351. //
  9352. this.setMode = setMode;
  9353. this.render = render;
  9354. this.renderInstances = renderInstances;
  9355. }
  9356. function WebGLCapabilities( gl, extensions, parameters ) {
  9357. let maxAnisotropy;
  9358. function getMaxAnisotropy() {
  9359. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9360. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9361. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9362. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9363. } else {
  9364. maxAnisotropy = 0;
  9365. }
  9366. return maxAnisotropy;
  9367. }
  9368. function getMaxPrecision( precision ) {
  9369. if ( precision === 'highp' ) {
  9370. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9371. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9372. return 'highp';
  9373. }
  9374. precision = 'mediump';
  9375. }
  9376. if ( precision === 'mediump' ) {
  9377. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9378. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9379. return 'mediump';
  9380. }
  9381. }
  9382. return 'lowp';
  9383. }
  9384. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9385. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9386. const maxPrecision = getMaxPrecision( precision );
  9387. if ( maxPrecision !== precision ) {
  9388. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9389. precision = maxPrecision;
  9390. }
  9391. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9392. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9393. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9394. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9395. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9396. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9397. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9398. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9399. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9400. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9401. const vertexTextures = maxVertexTextures > 0;
  9402. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9403. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9404. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  9405. return {
  9406. isWebGL2: isWebGL2,
  9407. drawBuffers: drawBuffers,
  9408. getMaxAnisotropy: getMaxAnisotropy,
  9409. getMaxPrecision: getMaxPrecision,
  9410. precision: precision,
  9411. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9412. maxTextures: maxTextures,
  9413. maxVertexTextures: maxVertexTextures,
  9414. maxTextureSize: maxTextureSize,
  9415. maxCubemapSize: maxCubemapSize,
  9416. maxAttributes: maxAttributes,
  9417. maxVertexUniforms: maxVertexUniforms,
  9418. maxVaryings: maxVaryings,
  9419. maxFragmentUniforms: maxFragmentUniforms,
  9420. vertexTextures: vertexTextures,
  9421. floatFragmentTextures: floatFragmentTextures,
  9422. floatVertexTextures: floatVertexTextures,
  9423. maxSamples: maxSamples
  9424. };
  9425. }
  9426. function WebGLClipping( properties ) {
  9427. const scope = this;
  9428. let globalState = null,
  9429. numGlobalPlanes = 0,
  9430. localClippingEnabled = false,
  9431. renderingShadows = false;
  9432. const plane = new Plane(),
  9433. viewNormalMatrix = new Matrix3(),
  9434. uniform = { value: null, needsUpdate: false };
  9435. this.uniform = uniform;
  9436. this.numPlanes = 0;
  9437. this.numIntersection = 0;
  9438. this.init = function ( planes, enableLocalClipping ) {
  9439. const enabled =
  9440. planes.length !== 0 ||
  9441. enableLocalClipping ||
  9442. // enable state of previous frame - the clipping code has to
  9443. // run another frame in order to reset the state:
  9444. numGlobalPlanes !== 0 ||
  9445. localClippingEnabled;
  9446. localClippingEnabled = enableLocalClipping;
  9447. numGlobalPlanes = planes.length;
  9448. return enabled;
  9449. };
  9450. this.beginShadows = function () {
  9451. renderingShadows = true;
  9452. projectPlanes( null );
  9453. };
  9454. this.endShadows = function () {
  9455. renderingShadows = false;
  9456. };
  9457. this.setGlobalState = function ( planes, camera ) {
  9458. globalState = projectPlanes( planes, camera, 0 );
  9459. };
  9460. this.setState = function ( material, camera, useCache ) {
  9461. const planes = material.clippingPlanes,
  9462. clipIntersection = material.clipIntersection,
  9463. clipShadows = material.clipShadows;
  9464. const materialProperties = properties.get( material );
  9465. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9466. // there's no local clipping
  9467. if ( renderingShadows ) {
  9468. // there's no global clipping
  9469. projectPlanes( null );
  9470. } else {
  9471. resetGlobalState();
  9472. }
  9473. } else {
  9474. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9475. lGlobal = nGlobal * 4;
  9476. let dstArray = materialProperties.clippingState || null;
  9477. uniform.value = dstArray; // ensure unique state
  9478. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9479. for ( let i = 0; i !== lGlobal; ++ i ) {
  9480. dstArray[ i ] = globalState[ i ];
  9481. }
  9482. materialProperties.clippingState = dstArray;
  9483. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9484. this.numPlanes += nGlobal;
  9485. }
  9486. };
  9487. function resetGlobalState() {
  9488. if ( uniform.value !== globalState ) {
  9489. uniform.value = globalState;
  9490. uniform.needsUpdate = numGlobalPlanes > 0;
  9491. }
  9492. scope.numPlanes = numGlobalPlanes;
  9493. scope.numIntersection = 0;
  9494. }
  9495. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9496. const nPlanes = planes !== null ? planes.length : 0;
  9497. let dstArray = null;
  9498. if ( nPlanes !== 0 ) {
  9499. dstArray = uniform.value;
  9500. if ( skipTransform !== true || dstArray === null ) {
  9501. const flatSize = dstOffset + nPlanes * 4,
  9502. viewMatrix = camera.matrixWorldInverse;
  9503. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9504. if ( dstArray === null || dstArray.length < flatSize ) {
  9505. dstArray = new Float32Array( flatSize );
  9506. }
  9507. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9508. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9509. plane.normal.toArray( dstArray, i4 );
  9510. dstArray[ i4 + 3 ] = plane.constant;
  9511. }
  9512. }
  9513. uniform.value = dstArray;
  9514. uniform.needsUpdate = true;
  9515. }
  9516. scope.numPlanes = nPlanes;
  9517. scope.numIntersection = 0;
  9518. return dstArray;
  9519. }
  9520. }
  9521. function WebGLCubeMaps( renderer ) {
  9522. let cubemaps = new WeakMap();
  9523. function mapTextureMapping( texture, mapping ) {
  9524. if ( mapping === EquirectangularReflectionMapping ) {
  9525. texture.mapping = CubeReflectionMapping;
  9526. } else if ( mapping === EquirectangularRefractionMapping ) {
  9527. texture.mapping = CubeRefractionMapping;
  9528. }
  9529. return texture;
  9530. }
  9531. function get( texture ) {
  9532. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9533. const mapping = texture.mapping;
  9534. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9535. if ( cubemaps.has( texture ) ) {
  9536. const cubemap = cubemaps.get( texture ).texture;
  9537. return mapTextureMapping( cubemap, texture.mapping );
  9538. } else {
  9539. const image = texture.image;
  9540. if ( image && image.height > 0 ) {
  9541. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9542. renderTarget.fromEquirectangularTexture( renderer, texture );
  9543. cubemaps.set( texture, renderTarget );
  9544. texture.addEventListener( 'dispose', onTextureDispose );
  9545. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9546. } else {
  9547. // image not yet ready. try the conversion next frame
  9548. return null;
  9549. }
  9550. }
  9551. }
  9552. }
  9553. return texture;
  9554. }
  9555. function onTextureDispose( event ) {
  9556. const texture = event.target;
  9557. texture.removeEventListener( 'dispose', onTextureDispose );
  9558. const cubemap = cubemaps.get( texture );
  9559. if ( cubemap !== undefined ) {
  9560. cubemaps.delete( texture );
  9561. cubemap.dispose();
  9562. }
  9563. }
  9564. function dispose() {
  9565. cubemaps = new WeakMap();
  9566. }
  9567. return {
  9568. get: get,
  9569. dispose: dispose
  9570. };
  9571. }
  9572. class OrthographicCamera extends Camera {
  9573. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9574. super();
  9575. this.isOrthographicCamera = true;
  9576. this.type = 'OrthographicCamera';
  9577. this.zoom = 1;
  9578. this.view = null;
  9579. this.left = left;
  9580. this.right = right;
  9581. this.top = top;
  9582. this.bottom = bottom;
  9583. this.near = near;
  9584. this.far = far;
  9585. this.updateProjectionMatrix();
  9586. }
  9587. copy( source, recursive ) {
  9588. super.copy( source, recursive );
  9589. this.left = source.left;
  9590. this.right = source.right;
  9591. this.top = source.top;
  9592. this.bottom = source.bottom;
  9593. this.near = source.near;
  9594. this.far = source.far;
  9595. this.zoom = source.zoom;
  9596. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9597. return this;
  9598. }
  9599. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9600. if ( this.view === null ) {
  9601. this.view = {
  9602. enabled: true,
  9603. fullWidth: 1,
  9604. fullHeight: 1,
  9605. offsetX: 0,
  9606. offsetY: 0,
  9607. width: 1,
  9608. height: 1
  9609. };
  9610. }
  9611. this.view.enabled = true;
  9612. this.view.fullWidth = fullWidth;
  9613. this.view.fullHeight = fullHeight;
  9614. this.view.offsetX = x;
  9615. this.view.offsetY = y;
  9616. this.view.width = width;
  9617. this.view.height = height;
  9618. this.updateProjectionMatrix();
  9619. }
  9620. clearViewOffset() {
  9621. if ( this.view !== null ) {
  9622. this.view.enabled = false;
  9623. }
  9624. this.updateProjectionMatrix();
  9625. }
  9626. updateProjectionMatrix() {
  9627. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9628. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9629. const cx = ( this.right + this.left ) / 2;
  9630. const cy = ( this.top + this.bottom ) / 2;
  9631. let left = cx - dx;
  9632. let right = cx + dx;
  9633. let top = cy + dy;
  9634. let bottom = cy - dy;
  9635. if ( this.view !== null && this.view.enabled ) {
  9636. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9637. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9638. left += scaleW * this.view.offsetX;
  9639. right = left + scaleW * this.view.width;
  9640. top -= scaleH * this.view.offsetY;
  9641. bottom = top - scaleH * this.view.height;
  9642. }
  9643. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9644. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9645. }
  9646. toJSON( meta ) {
  9647. const data = super.toJSON( meta );
  9648. data.object.zoom = this.zoom;
  9649. data.object.left = this.left;
  9650. data.object.right = this.right;
  9651. data.object.top = this.top;
  9652. data.object.bottom = this.bottom;
  9653. data.object.near = this.near;
  9654. data.object.far = this.far;
  9655. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9656. return data;
  9657. }
  9658. }
  9659. const LOD_MIN = 4;
  9660. // The standard deviations (radians) associated with the extra mips. These are
  9661. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9662. // geometric shadowing function. These sigma values squared must match the
  9663. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9664. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9665. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9666. // samples and exit early, but not recompile the shader.
  9667. const MAX_SAMPLES = 20;
  9668. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9669. const _clearColor = /*@__PURE__*/ new Color();
  9670. let _oldTarget = null;
  9671. // Golden Ratio
  9672. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9673. const INV_PHI = 1 / PHI;
  9674. // Vertices of a dodecahedron (except the opposites, which represent the
  9675. // same axis), used as axis directions evenly spread on a sphere.
  9676. const _axisDirections = [
  9677. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9678. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9679. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9680. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9681. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9682. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9683. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9684. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9685. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9686. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9687. /**
  9688. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9689. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9690. * blur to be quickly accessed based on material roughness. It is packed into a
  9691. * special CubeUV format that allows us to perform custom interpolation so that
  9692. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9693. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9694. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9695. * higher roughness levels. In this way we maintain resolution to smoothly
  9696. * interpolate diffuse lighting while limiting sampling computation.
  9697. *
  9698. * Paper: Fast, Accurate Image-Based Lighting
  9699. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9700. */
  9701. class PMREMGenerator {
  9702. constructor( renderer ) {
  9703. this._renderer = renderer;
  9704. this._pingPongRenderTarget = null;
  9705. this._lodMax = 0;
  9706. this._cubeSize = 0;
  9707. this._lodPlanes = [];
  9708. this._sizeLods = [];
  9709. this._sigmas = [];
  9710. this._blurMaterial = null;
  9711. this._cubemapMaterial = null;
  9712. this._equirectMaterial = null;
  9713. this._compileMaterial( this._blurMaterial );
  9714. }
  9715. /**
  9716. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9717. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9718. * in radians to be applied to the scene before PMREM generation. Optional near
  9719. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9720. * is placed at the origin).
  9721. */
  9722. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9723. _oldTarget = this._renderer.getRenderTarget();
  9724. this._setSize( 256 );
  9725. const cubeUVRenderTarget = this._allocateTargets();
  9726. cubeUVRenderTarget.depthBuffer = true;
  9727. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9728. if ( sigma > 0 ) {
  9729. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9730. }
  9731. this._applyPMREM( cubeUVRenderTarget );
  9732. this._cleanup( cubeUVRenderTarget );
  9733. return cubeUVRenderTarget;
  9734. }
  9735. /**
  9736. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9737. * or HDR. The ideal input image size is 1k (1024 x 512),
  9738. * as this matches best with the 256 x 256 cubemap output.
  9739. */
  9740. fromEquirectangular( equirectangular, renderTarget = null ) {
  9741. return this._fromTexture( equirectangular, renderTarget );
  9742. }
  9743. /**
  9744. * Generates a PMREM from an cubemap texture, which can be either LDR
  9745. * or HDR. The ideal input cube size is 256 x 256,
  9746. * as this matches best with the 256 x 256 cubemap output.
  9747. */
  9748. fromCubemap( cubemap, renderTarget = null ) {
  9749. return this._fromTexture( cubemap, renderTarget );
  9750. }
  9751. /**
  9752. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9753. * your texture's network fetch for increased concurrency.
  9754. */
  9755. compileCubemapShader() {
  9756. if ( this._cubemapMaterial === null ) {
  9757. this._cubemapMaterial = _getCubemapMaterial();
  9758. this._compileMaterial( this._cubemapMaterial );
  9759. }
  9760. }
  9761. /**
  9762. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9763. * your texture's network fetch for increased concurrency.
  9764. */
  9765. compileEquirectangularShader() {
  9766. if ( this._equirectMaterial === null ) {
  9767. this._equirectMaterial = _getEquirectMaterial();
  9768. this._compileMaterial( this._equirectMaterial );
  9769. }
  9770. }
  9771. /**
  9772. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9773. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9774. * one of them will cause any others to also become unusable.
  9775. */
  9776. dispose() {
  9777. this._dispose();
  9778. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9779. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9780. }
  9781. // private interface
  9782. _setSize( cubeSize ) {
  9783. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9784. this._cubeSize = Math.pow( 2, this._lodMax );
  9785. }
  9786. _dispose() {
  9787. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9788. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9789. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9790. this._lodPlanes[ i ].dispose();
  9791. }
  9792. }
  9793. _cleanup( outputTarget ) {
  9794. this._renderer.setRenderTarget( _oldTarget );
  9795. outputTarget.scissorTest = false;
  9796. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9797. }
  9798. _fromTexture( texture, renderTarget ) {
  9799. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9800. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9801. } else { // Equirectangular
  9802. this._setSize( texture.image.width / 4 );
  9803. }
  9804. _oldTarget = this._renderer.getRenderTarget();
  9805. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9806. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9807. this._applyPMREM( cubeUVRenderTarget );
  9808. this._cleanup( cubeUVRenderTarget );
  9809. return cubeUVRenderTarget;
  9810. }
  9811. _allocateTargets() {
  9812. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9813. const height = 4 * this._cubeSize;
  9814. const params = {
  9815. magFilter: LinearFilter,
  9816. minFilter: LinearFilter,
  9817. generateMipmaps: false,
  9818. type: HalfFloatType,
  9819. format: RGBAFormat,
  9820. colorSpace: LinearSRGBColorSpace,
  9821. depthBuffer: false
  9822. };
  9823. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9824. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9825. if ( this._pingPongRenderTarget !== null ) {
  9826. this._dispose();
  9827. }
  9828. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9829. const { _lodMax } = this;
  9830. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9831. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9832. }
  9833. return cubeUVRenderTarget;
  9834. }
  9835. _compileMaterial( material ) {
  9836. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9837. this._renderer.compile( tmpMesh, _flatCamera );
  9838. }
  9839. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9840. const fov = 90;
  9841. const aspect = 1;
  9842. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9843. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9844. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9845. const renderer = this._renderer;
  9846. const originalAutoClear = renderer.autoClear;
  9847. const toneMapping = renderer.toneMapping;
  9848. renderer.getClearColor( _clearColor );
  9849. renderer.toneMapping = NoToneMapping;
  9850. renderer.autoClear = false;
  9851. const backgroundMaterial = new MeshBasicMaterial( {
  9852. name: 'PMREM.Background',
  9853. side: BackSide,
  9854. depthWrite: false,
  9855. depthTest: false,
  9856. } );
  9857. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9858. let useSolidColor = false;
  9859. const background = scene.background;
  9860. if ( background ) {
  9861. if ( background.isColor ) {
  9862. backgroundMaterial.color.copy( background );
  9863. scene.background = null;
  9864. useSolidColor = true;
  9865. }
  9866. } else {
  9867. backgroundMaterial.color.copy( _clearColor );
  9868. useSolidColor = true;
  9869. }
  9870. for ( let i = 0; i < 6; i ++ ) {
  9871. const col = i % 3;
  9872. if ( col === 0 ) {
  9873. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9874. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9875. } else if ( col === 1 ) {
  9876. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9877. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9878. } else {
  9879. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9880. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9881. }
  9882. const size = this._cubeSize;
  9883. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9884. renderer.setRenderTarget( cubeUVRenderTarget );
  9885. if ( useSolidColor ) {
  9886. renderer.render( backgroundBox, cubeCamera );
  9887. }
  9888. renderer.render( scene, cubeCamera );
  9889. }
  9890. backgroundBox.geometry.dispose();
  9891. backgroundBox.material.dispose();
  9892. renderer.toneMapping = toneMapping;
  9893. renderer.autoClear = originalAutoClear;
  9894. scene.background = background;
  9895. }
  9896. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9897. const renderer = this._renderer;
  9898. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9899. if ( isCubeTexture ) {
  9900. if ( this._cubemapMaterial === null ) {
  9901. this._cubemapMaterial = _getCubemapMaterial();
  9902. }
  9903. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9904. } else {
  9905. if ( this._equirectMaterial === null ) {
  9906. this._equirectMaterial = _getEquirectMaterial();
  9907. }
  9908. }
  9909. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9910. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9911. const uniforms = material.uniforms;
  9912. uniforms[ 'envMap' ].value = texture;
  9913. const size = this._cubeSize;
  9914. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9915. renderer.setRenderTarget( cubeUVRenderTarget );
  9916. renderer.render( mesh, _flatCamera );
  9917. }
  9918. _applyPMREM( cubeUVRenderTarget ) {
  9919. const renderer = this._renderer;
  9920. const autoClear = renderer.autoClear;
  9921. renderer.autoClear = false;
  9922. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9923. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9924. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9925. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9926. }
  9927. renderer.autoClear = autoClear;
  9928. }
  9929. /**
  9930. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9931. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9932. * the blur latitudinally (around the poles), and then longitudinally (towards
  9933. * the poles) to approximate the orthogonally-separable blur. It is least
  9934. * accurate at the poles, but still does a decent job.
  9935. */
  9936. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9937. const pingPongRenderTarget = this._pingPongRenderTarget;
  9938. this._halfBlur(
  9939. cubeUVRenderTarget,
  9940. pingPongRenderTarget,
  9941. lodIn,
  9942. lodOut,
  9943. sigma,
  9944. 'latitudinal',
  9945. poleAxis );
  9946. this._halfBlur(
  9947. pingPongRenderTarget,
  9948. cubeUVRenderTarget,
  9949. lodOut,
  9950. lodOut,
  9951. sigma,
  9952. 'longitudinal',
  9953. poleAxis );
  9954. }
  9955. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9956. const renderer = this._renderer;
  9957. const blurMaterial = this._blurMaterial;
  9958. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9959. console.error(
  9960. 'blur direction must be either latitudinal or longitudinal!' );
  9961. }
  9962. // Number of standard deviations at which to cut off the discrete approximation.
  9963. const STANDARD_DEVIATIONS = 3;
  9964. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9965. const blurUniforms = blurMaterial.uniforms;
  9966. const pixels = this._sizeLods[ lodIn ] - 1;
  9967. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9968. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9969. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9970. if ( samples > MAX_SAMPLES ) {
  9971. console.warn( `sigmaRadians, ${
  9972. sigmaRadians}, is too large and will clip, as it requested ${
  9973. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9974. }
  9975. const weights = [];
  9976. let sum = 0;
  9977. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9978. const x = i / sigmaPixels;
  9979. const weight = Math.exp( - x * x / 2 );
  9980. weights.push( weight );
  9981. if ( i === 0 ) {
  9982. sum += weight;
  9983. } else if ( i < samples ) {
  9984. sum += 2 * weight;
  9985. }
  9986. }
  9987. for ( let i = 0; i < weights.length; i ++ ) {
  9988. weights[ i ] = weights[ i ] / sum;
  9989. }
  9990. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9991. blurUniforms[ 'samples' ].value = samples;
  9992. blurUniforms[ 'weights' ].value = weights;
  9993. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9994. if ( poleAxis ) {
  9995. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9996. }
  9997. const { _lodMax } = this;
  9998. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9999. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10000. const outputSize = this._sizeLods[ lodOut ];
  10001. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10002. const y = 4 * ( this._cubeSize - outputSize );
  10003. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10004. renderer.setRenderTarget( targetOut );
  10005. renderer.render( blurMesh, _flatCamera );
  10006. }
  10007. }
  10008. function _createPlanes( lodMax ) {
  10009. const lodPlanes = [];
  10010. const sizeLods = [];
  10011. const sigmas = [];
  10012. let lod = lodMax;
  10013. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10014. for ( let i = 0; i < totalLods; i ++ ) {
  10015. const sizeLod = Math.pow( 2, lod );
  10016. sizeLods.push( sizeLod );
  10017. let sigma = 1.0 / sizeLod;
  10018. if ( i > lodMax - LOD_MIN ) {
  10019. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10020. } else if ( i === 0 ) {
  10021. sigma = 0;
  10022. }
  10023. sigmas.push( sigma );
  10024. const texelSize = 1.0 / ( sizeLod - 2 );
  10025. const min = - texelSize;
  10026. const max = 1 + texelSize;
  10027. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10028. const cubeFaces = 6;
  10029. const vertices = 6;
  10030. const positionSize = 3;
  10031. const uvSize = 2;
  10032. const faceIndexSize = 1;
  10033. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10034. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10035. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10036. for ( let face = 0; face < cubeFaces; face ++ ) {
  10037. const x = ( face % 3 ) * 2 / 3 - 1;
  10038. const y = face > 2 ? 0 : - 1;
  10039. const coordinates = [
  10040. x, y, 0,
  10041. x + 2 / 3, y, 0,
  10042. x + 2 / 3, y + 1, 0,
  10043. x, y, 0,
  10044. x + 2 / 3, y + 1, 0,
  10045. x, y + 1, 0
  10046. ];
  10047. position.set( coordinates, positionSize * vertices * face );
  10048. uv.set( uv1, uvSize * vertices * face );
  10049. const fill = [ face, face, face, face, face, face ];
  10050. faceIndex.set( fill, faceIndexSize * vertices * face );
  10051. }
  10052. const planes = new BufferGeometry();
  10053. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10054. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10055. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10056. lodPlanes.push( planes );
  10057. if ( lod > LOD_MIN ) {
  10058. lod --;
  10059. }
  10060. }
  10061. return { lodPlanes, sizeLods, sigmas };
  10062. }
  10063. function _createRenderTarget( width, height, params ) {
  10064. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10065. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10066. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10067. cubeUVRenderTarget.scissorTest = true;
  10068. return cubeUVRenderTarget;
  10069. }
  10070. function _setViewport( target, x, y, width, height ) {
  10071. target.viewport.set( x, y, width, height );
  10072. target.scissor.set( x, y, width, height );
  10073. }
  10074. function _getBlurShader( lodMax, width, height ) {
  10075. const weights = new Float32Array( MAX_SAMPLES );
  10076. const poleAxis = new Vector3( 0, 1, 0 );
  10077. const shaderMaterial = new ShaderMaterial( {
  10078. name: 'SphericalGaussianBlur',
  10079. defines: {
  10080. 'n': MAX_SAMPLES,
  10081. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10082. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10083. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10084. },
  10085. uniforms: {
  10086. 'envMap': { value: null },
  10087. 'samples': { value: 1 },
  10088. 'weights': { value: weights },
  10089. 'latitudinal': { value: false },
  10090. 'dTheta': { value: 0 },
  10091. 'mipInt': { value: 0 },
  10092. 'poleAxis': { value: poleAxis }
  10093. },
  10094. vertexShader: _getCommonVertexShader(),
  10095. fragmentShader: /* glsl */`
  10096. precision mediump float;
  10097. precision mediump int;
  10098. varying vec3 vOutputDirection;
  10099. uniform sampler2D envMap;
  10100. uniform int samples;
  10101. uniform float weights[ n ];
  10102. uniform bool latitudinal;
  10103. uniform float dTheta;
  10104. uniform float mipInt;
  10105. uniform vec3 poleAxis;
  10106. #define ENVMAP_TYPE_CUBE_UV
  10107. #include <cube_uv_reflection_fragment>
  10108. vec3 getSample( float theta, vec3 axis ) {
  10109. float cosTheta = cos( theta );
  10110. // Rodrigues' axis-angle rotation
  10111. vec3 sampleDirection = vOutputDirection * cosTheta
  10112. + cross( axis, vOutputDirection ) * sin( theta )
  10113. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10114. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10115. }
  10116. void main() {
  10117. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10118. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10119. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10120. }
  10121. axis = normalize( axis );
  10122. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10123. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10124. for ( int i = 1; i < n; i++ ) {
  10125. if ( i >= samples ) {
  10126. break;
  10127. }
  10128. float theta = dTheta * float( i );
  10129. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10130. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10131. }
  10132. }
  10133. `,
  10134. blending: NoBlending,
  10135. depthTest: false,
  10136. depthWrite: false
  10137. } );
  10138. return shaderMaterial;
  10139. }
  10140. function _getEquirectMaterial() {
  10141. return new ShaderMaterial( {
  10142. name: 'EquirectangularToCubeUV',
  10143. uniforms: {
  10144. 'envMap': { value: null }
  10145. },
  10146. vertexShader: _getCommonVertexShader(),
  10147. fragmentShader: /* glsl */`
  10148. precision mediump float;
  10149. precision mediump int;
  10150. varying vec3 vOutputDirection;
  10151. uniform sampler2D envMap;
  10152. #include <common>
  10153. void main() {
  10154. vec3 outputDirection = normalize( vOutputDirection );
  10155. vec2 uv = equirectUv( outputDirection );
  10156. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10157. }
  10158. `,
  10159. blending: NoBlending,
  10160. depthTest: false,
  10161. depthWrite: false
  10162. } );
  10163. }
  10164. function _getCubemapMaterial() {
  10165. return new ShaderMaterial( {
  10166. name: 'CubemapToCubeUV',
  10167. uniforms: {
  10168. 'envMap': { value: null },
  10169. 'flipEnvMap': { value: - 1 }
  10170. },
  10171. vertexShader: _getCommonVertexShader(),
  10172. fragmentShader: /* glsl */`
  10173. precision mediump float;
  10174. precision mediump int;
  10175. uniform float flipEnvMap;
  10176. varying vec3 vOutputDirection;
  10177. uniform samplerCube envMap;
  10178. void main() {
  10179. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10180. }
  10181. `,
  10182. blending: NoBlending,
  10183. depthTest: false,
  10184. depthWrite: false
  10185. } );
  10186. }
  10187. function _getCommonVertexShader() {
  10188. return /* glsl */`
  10189. precision mediump float;
  10190. precision mediump int;
  10191. attribute float faceIndex;
  10192. varying vec3 vOutputDirection;
  10193. // RH coordinate system; PMREM face-indexing convention
  10194. vec3 getDirection( vec2 uv, float face ) {
  10195. uv = 2.0 * uv - 1.0;
  10196. vec3 direction = vec3( uv, 1.0 );
  10197. if ( face == 0.0 ) {
  10198. direction = direction.zyx; // ( 1, v, u ) pos x
  10199. } else if ( face == 1.0 ) {
  10200. direction = direction.xzy;
  10201. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10202. } else if ( face == 2.0 ) {
  10203. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10204. } else if ( face == 3.0 ) {
  10205. direction = direction.zyx;
  10206. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10207. } else if ( face == 4.0 ) {
  10208. direction = direction.xzy;
  10209. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10210. } else if ( face == 5.0 ) {
  10211. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10212. }
  10213. return direction;
  10214. }
  10215. void main() {
  10216. vOutputDirection = getDirection( uv, faceIndex );
  10217. gl_Position = vec4( position, 1.0 );
  10218. }
  10219. `;
  10220. }
  10221. function WebGLCubeUVMaps( renderer ) {
  10222. let cubeUVmaps = new WeakMap();
  10223. let pmremGenerator = null;
  10224. function get( texture ) {
  10225. if ( texture && texture.isTexture ) {
  10226. const mapping = texture.mapping;
  10227. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10228. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10229. // equirect/cube map to cubeUV conversion
  10230. if ( isEquirectMap || isCubeMap ) {
  10231. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10232. texture.needsPMREMUpdate = false;
  10233. let renderTarget = cubeUVmaps.get( texture );
  10234. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10235. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10236. cubeUVmaps.set( texture, renderTarget );
  10237. return renderTarget.texture;
  10238. } else {
  10239. if ( cubeUVmaps.has( texture ) ) {
  10240. return cubeUVmaps.get( texture ).texture;
  10241. } else {
  10242. const image = texture.image;
  10243. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10244. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10245. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10246. cubeUVmaps.set( texture, renderTarget );
  10247. texture.addEventListener( 'dispose', onTextureDispose );
  10248. return renderTarget.texture;
  10249. } else {
  10250. // image not yet ready. try the conversion next frame
  10251. return null;
  10252. }
  10253. }
  10254. }
  10255. }
  10256. }
  10257. return texture;
  10258. }
  10259. function isCubeTextureComplete( image ) {
  10260. let count = 0;
  10261. const length = 6;
  10262. for ( let i = 0; i < length; i ++ ) {
  10263. if ( image[ i ] !== undefined ) count ++;
  10264. }
  10265. return count === length;
  10266. }
  10267. function onTextureDispose( event ) {
  10268. const texture = event.target;
  10269. texture.removeEventListener( 'dispose', onTextureDispose );
  10270. const cubemapUV = cubeUVmaps.get( texture );
  10271. if ( cubemapUV !== undefined ) {
  10272. cubeUVmaps.delete( texture );
  10273. cubemapUV.dispose();
  10274. }
  10275. }
  10276. function dispose() {
  10277. cubeUVmaps = new WeakMap();
  10278. if ( pmremGenerator !== null ) {
  10279. pmremGenerator.dispose();
  10280. pmremGenerator = null;
  10281. }
  10282. }
  10283. return {
  10284. get: get,
  10285. dispose: dispose
  10286. };
  10287. }
  10288. function WebGLExtensions( gl ) {
  10289. const extensions = {};
  10290. function getExtension( name ) {
  10291. if ( extensions[ name ] !== undefined ) {
  10292. return extensions[ name ];
  10293. }
  10294. let extension;
  10295. switch ( name ) {
  10296. case 'WEBGL_depth_texture':
  10297. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10298. break;
  10299. case 'EXT_texture_filter_anisotropic':
  10300. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10301. break;
  10302. case 'WEBGL_compressed_texture_s3tc':
  10303. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10304. break;
  10305. case 'WEBGL_compressed_texture_pvrtc':
  10306. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10307. break;
  10308. default:
  10309. extension = gl.getExtension( name );
  10310. }
  10311. extensions[ name ] = extension;
  10312. return extension;
  10313. }
  10314. return {
  10315. has: function ( name ) {
  10316. return getExtension( name ) !== null;
  10317. },
  10318. init: function ( capabilities ) {
  10319. if ( capabilities.isWebGL2 ) {
  10320. getExtension( 'EXT_color_buffer_float' );
  10321. } else {
  10322. getExtension( 'WEBGL_depth_texture' );
  10323. getExtension( 'OES_texture_float' );
  10324. getExtension( 'OES_texture_half_float' );
  10325. getExtension( 'OES_texture_half_float_linear' );
  10326. getExtension( 'OES_standard_derivatives' );
  10327. getExtension( 'OES_element_index_uint' );
  10328. getExtension( 'OES_vertex_array_object' );
  10329. getExtension( 'ANGLE_instanced_arrays' );
  10330. }
  10331. getExtension( 'OES_texture_float_linear' );
  10332. getExtension( 'EXT_color_buffer_half_float' );
  10333. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10334. },
  10335. get: function ( name ) {
  10336. const extension = getExtension( name );
  10337. if ( extension === null ) {
  10338. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10339. }
  10340. return extension;
  10341. }
  10342. };
  10343. }
  10344. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10345. const geometries = {};
  10346. const wireframeAttributes = new WeakMap();
  10347. function onGeometryDispose( event ) {
  10348. const geometry = event.target;
  10349. if ( geometry.index !== null ) {
  10350. attributes.remove( geometry.index );
  10351. }
  10352. for ( const name in geometry.attributes ) {
  10353. attributes.remove( geometry.attributes[ name ] );
  10354. }
  10355. for ( const name in geometry.morphAttributes ) {
  10356. const array = geometry.morphAttributes[ name ];
  10357. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10358. attributes.remove( array[ i ] );
  10359. }
  10360. }
  10361. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10362. delete geometries[ geometry.id ];
  10363. const attribute = wireframeAttributes.get( geometry );
  10364. if ( attribute ) {
  10365. attributes.remove( attribute );
  10366. wireframeAttributes.delete( geometry );
  10367. }
  10368. bindingStates.releaseStatesOfGeometry( geometry );
  10369. if ( geometry.isInstancedBufferGeometry === true ) {
  10370. delete geometry._maxInstanceCount;
  10371. }
  10372. //
  10373. info.memory.geometries --;
  10374. }
  10375. function get( object, geometry ) {
  10376. if ( geometries[ geometry.id ] === true ) return geometry;
  10377. geometry.addEventListener( 'dispose', onGeometryDispose );
  10378. geometries[ geometry.id ] = true;
  10379. info.memory.geometries ++;
  10380. return geometry;
  10381. }
  10382. function update( geometry ) {
  10383. const geometryAttributes = geometry.attributes;
  10384. // Updating index buffer in VAO now. See WebGLBindingStates.
  10385. for ( const name in geometryAttributes ) {
  10386. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10387. }
  10388. // morph targets
  10389. const morphAttributes = geometry.morphAttributes;
  10390. for ( const name in morphAttributes ) {
  10391. const array = morphAttributes[ name ];
  10392. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10393. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10394. }
  10395. }
  10396. }
  10397. function updateWireframeAttribute( geometry ) {
  10398. const indices = [];
  10399. const geometryIndex = geometry.index;
  10400. const geometryPosition = geometry.attributes.position;
  10401. let version = 0;
  10402. if ( geometryIndex !== null ) {
  10403. const array = geometryIndex.array;
  10404. version = geometryIndex.version;
  10405. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10406. const a = array[ i + 0 ];
  10407. const b = array[ i + 1 ];
  10408. const c = array[ i + 2 ];
  10409. indices.push( a, b, b, c, c, a );
  10410. }
  10411. } else if ( geometryPosition !== undefined ) {
  10412. const array = geometryPosition.array;
  10413. version = geometryPosition.version;
  10414. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10415. const a = i + 0;
  10416. const b = i + 1;
  10417. const c = i + 2;
  10418. indices.push( a, b, b, c, c, a );
  10419. }
  10420. } else {
  10421. return;
  10422. }
  10423. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10424. attribute.version = version;
  10425. // Updating index buffer in VAO now. See WebGLBindingStates
  10426. //
  10427. const previousAttribute = wireframeAttributes.get( geometry );
  10428. if ( previousAttribute ) attributes.remove( previousAttribute );
  10429. //
  10430. wireframeAttributes.set( geometry, attribute );
  10431. }
  10432. function getWireframeAttribute( geometry ) {
  10433. const currentAttribute = wireframeAttributes.get( geometry );
  10434. if ( currentAttribute ) {
  10435. const geometryIndex = geometry.index;
  10436. if ( geometryIndex !== null ) {
  10437. // if the attribute is obsolete, create a new one
  10438. if ( currentAttribute.version < geometryIndex.version ) {
  10439. updateWireframeAttribute( geometry );
  10440. }
  10441. }
  10442. } else {
  10443. updateWireframeAttribute( geometry );
  10444. }
  10445. return wireframeAttributes.get( geometry );
  10446. }
  10447. return {
  10448. get: get,
  10449. update: update,
  10450. getWireframeAttribute: getWireframeAttribute
  10451. };
  10452. }
  10453. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10454. const isWebGL2 = capabilities.isWebGL2;
  10455. let mode;
  10456. function setMode( value ) {
  10457. mode = value;
  10458. }
  10459. let type, bytesPerElement;
  10460. function setIndex( value ) {
  10461. type = value.type;
  10462. bytesPerElement = value.bytesPerElement;
  10463. }
  10464. function render( start, count ) {
  10465. gl.drawElements( mode, count, type, start * bytesPerElement );
  10466. info.update( count, mode, 1 );
  10467. }
  10468. function renderInstances( start, count, primcount ) {
  10469. if ( primcount === 0 ) return;
  10470. let extension, methodName;
  10471. if ( isWebGL2 ) {
  10472. extension = gl;
  10473. methodName = 'drawElementsInstanced';
  10474. } else {
  10475. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10476. methodName = 'drawElementsInstancedANGLE';
  10477. if ( extension === null ) {
  10478. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10479. return;
  10480. }
  10481. }
  10482. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10483. info.update( count, mode, primcount );
  10484. }
  10485. //
  10486. this.setMode = setMode;
  10487. this.setIndex = setIndex;
  10488. this.render = render;
  10489. this.renderInstances = renderInstances;
  10490. }
  10491. function WebGLInfo( gl ) {
  10492. const memory = {
  10493. geometries: 0,
  10494. textures: 0
  10495. };
  10496. const render = {
  10497. frame: 0,
  10498. calls: 0,
  10499. triangles: 0,
  10500. points: 0,
  10501. lines: 0
  10502. };
  10503. function update( count, mode, instanceCount ) {
  10504. render.calls ++;
  10505. switch ( mode ) {
  10506. case gl.TRIANGLES:
  10507. render.triangles += instanceCount * ( count / 3 );
  10508. break;
  10509. case gl.LINES:
  10510. render.lines += instanceCount * ( count / 2 );
  10511. break;
  10512. case gl.LINE_STRIP:
  10513. render.lines += instanceCount * ( count - 1 );
  10514. break;
  10515. case gl.LINE_LOOP:
  10516. render.lines += instanceCount * count;
  10517. break;
  10518. case gl.POINTS:
  10519. render.points += instanceCount * count;
  10520. break;
  10521. default:
  10522. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10523. break;
  10524. }
  10525. }
  10526. function reset() {
  10527. render.calls = 0;
  10528. render.triangles = 0;
  10529. render.points = 0;
  10530. render.lines = 0;
  10531. }
  10532. return {
  10533. memory: memory,
  10534. render: render,
  10535. programs: null,
  10536. autoReset: true,
  10537. reset: reset,
  10538. update: update
  10539. };
  10540. }
  10541. function numericalSort( a, b ) {
  10542. return a[ 0 ] - b[ 0 ];
  10543. }
  10544. function absNumericalSort( a, b ) {
  10545. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10546. }
  10547. function WebGLMorphtargets( gl, capabilities, textures ) {
  10548. const influencesList = {};
  10549. const morphInfluences = new Float32Array( 8 );
  10550. const morphTextures = new WeakMap();
  10551. const morph = new Vector4();
  10552. const workInfluences = [];
  10553. for ( let i = 0; i < 8; i ++ ) {
  10554. workInfluences[ i ] = [ i, 0 ];
  10555. }
  10556. function update( object, geometry, program ) {
  10557. const objectInfluences = object.morphTargetInfluences;
  10558. if ( capabilities.isWebGL2 === true ) {
  10559. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10560. // into an array of data textures. Each layer represents a single morph target.
  10561. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10562. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10563. let entry = morphTextures.get( geometry );
  10564. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10565. if ( entry !== undefined ) entry.texture.dispose();
  10566. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10567. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10568. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10569. const morphTargets = geometry.morphAttributes.position || [];
  10570. const morphNormals = geometry.morphAttributes.normal || [];
  10571. const morphColors = geometry.morphAttributes.color || [];
  10572. let vertexDataCount = 0;
  10573. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10574. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10575. if ( hasMorphColors === true ) vertexDataCount = 3;
  10576. let width = geometry.attributes.position.count * vertexDataCount;
  10577. let height = 1;
  10578. if ( width > capabilities.maxTextureSize ) {
  10579. height = Math.ceil( width / capabilities.maxTextureSize );
  10580. width = capabilities.maxTextureSize;
  10581. }
  10582. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10583. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10584. texture.type = FloatType;
  10585. texture.needsUpdate = true;
  10586. // fill buffer
  10587. const vertexDataStride = vertexDataCount * 4;
  10588. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10589. const morphTarget = morphTargets[ i ];
  10590. const morphNormal = morphNormals[ i ];
  10591. const morphColor = morphColors[ i ];
  10592. const offset = width * height * 4 * i;
  10593. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10594. const stride = j * vertexDataStride;
  10595. if ( hasMorphPosition === true ) {
  10596. morph.fromBufferAttribute( morphTarget, j );
  10597. buffer[ offset + stride + 0 ] = morph.x;
  10598. buffer[ offset + stride + 1 ] = morph.y;
  10599. buffer[ offset + stride + 2 ] = morph.z;
  10600. buffer[ offset + stride + 3 ] = 0;
  10601. }
  10602. if ( hasMorphNormals === true ) {
  10603. morph.fromBufferAttribute( morphNormal, j );
  10604. buffer[ offset + stride + 4 ] = morph.x;
  10605. buffer[ offset + stride + 5 ] = morph.y;
  10606. buffer[ offset + stride + 6 ] = morph.z;
  10607. buffer[ offset + stride + 7 ] = 0;
  10608. }
  10609. if ( hasMorphColors === true ) {
  10610. morph.fromBufferAttribute( morphColor, j );
  10611. buffer[ offset + stride + 8 ] = morph.x;
  10612. buffer[ offset + stride + 9 ] = morph.y;
  10613. buffer[ offset + stride + 10 ] = morph.z;
  10614. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10615. }
  10616. }
  10617. }
  10618. entry = {
  10619. count: morphTargetsCount,
  10620. texture: texture,
  10621. size: new Vector2( width, height )
  10622. };
  10623. morphTextures.set( geometry, entry );
  10624. function disposeTexture() {
  10625. texture.dispose();
  10626. morphTextures.delete( geometry );
  10627. geometry.removeEventListener( 'dispose', disposeTexture );
  10628. }
  10629. geometry.addEventListener( 'dispose', disposeTexture );
  10630. }
  10631. //
  10632. let morphInfluencesSum = 0;
  10633. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10634. morphInfluencesSum += objectInfluences[ i ];
  10635. }
  10636. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10637. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10638. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10639. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10640. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10641. } else {
  10642. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10643. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10644. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10645. let influences = influencesList[ geometry.id ];
  10646. if ( influences === undefined || influences.length !== length ) {
  10647. // initialise list
  10648. influences = [];
  10649. for ( let i = 0; i < length; i ++ ) {
  10650. influences[ i ] = [ i, 0 ];
  10651. }
  10652. influencesList[ geometry.id ] = influences;
  10653. }
  10654. // Collect influences
  10655. for ( let i = 0; i < length; i ++ ) {
  10656. const influence = influences[ i ];
  10657. influence[ 0 ] = i;
  10658. influence[ 1 ] = objectInfluences[ i ];
  10659. }
  10660. influences.sort( absNumericalSort );
  10661. for ( let i = 0; i < 8; i ++ ) {
  10662. if ( i < length && influences[ i ][ 1 ] ) {
  10663. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10664. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10665. } else {
  10666. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10667. workInfluences[ i ][ 1 ] = 0;
  10668. }
  10669. }
  10670. workInfluences.sort( numericalSort );
  10671. const morphTargets = geometry.morphAttributes.position;
  10672. const morphNormals = geometry.morphAttributes.normal;
  10673. let morphInfluencesSum = 0;
  10674. for ( let i = 0; i < 8; i ++ ) {
  10675. const influence = workInfluences[ i ];
  10676. const index = influence[ 0 ];
  10677. const value = influence[ 1 ];
  10678. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10679. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10680. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10681. }
  10682. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10683. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10684. }
  10685. morphInfluences[ i ] = value;
  10686. morphInfluencesSum += value;
  10687. } else {
  10688. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10689. geometry.deleteAttribute( 'morphTarget' + i );
  10690. }
  10691. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10692. geometry.deleteAttribute( 'morphNormal' + i );
  10693. }
  10694. morphInfluences[ i ] = 0;
  10695. }
  10696. }
  10697. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10698. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10699. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10700. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10701. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10702. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10703. }
  10704. }
  10705. return {
  10706. update: update
  10707. };
  10708. }
  10709. function WebGLObjects( gl, geometries, attributes, info ) {
  10710. let updateMap = new WeakMap();
  10711. function update( object ) {
  10712. const frame = info.render.frame;
  10713. const geometry = object.geometry;
  10714. const buffergeometry = geometries.get( object, geometry );
  10715. // Update once per frame
  10716. if ( updateMap.get( buffergeometry ) !== frame ) {
  10717. geometries.update( buffergeometry );
  10718. updateMap.set( buffergeometry, frame );
  10719. }
  10720. if ( object.isInstancedMesh ) {
  10721. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10722. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10723. }
  10724. if ( updateMap.get( object ) !== frame ) {
  10725. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10726. if ( object.instanceColor !== null ) {
  10727. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10728. }
  10729. updateMap.set( object, frame );
  10730. }
  10731. }
  10732. if ( object.isSkinnedMesh ) {
  10733. const skeleton = object.skeleton;
  10734. if ( updateMap.get( skeleton ) !== frame ) {
  10735. skeleton.update();
  10736. updateMap.set( skeleton, frame );
  10737. }
  10738. }
  10739. return buffergeometry;
  10740. }
  10741. function dispose() {
  10742. updateMap = new WeakMap();
  10743. }
  10744. function onInstancedMeshDispose( event ) {
  10745. const instancedMesh = event.target;
  10746. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10747. attributes.remove( instancedMesh.instanceMatrix );
  10748. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10749. }
  10750. return {
  10751. update: update,
  10752. dispose: dispose
  10753. };
  10754. }
  10755. /**
  10756. * Uniforms of a program.
  10757. * Those form a tree structure with a special top-level container for the root,
  10758. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10759. *
  10760. *
  10761. * Properties of inner nodes including the top-level container:
  10762. *
  10763. * .seq - array of nested uniforms
  10764. * .map - nested uniforms by name
  10765. *
  10766. *
  10767. * Methods of all nodes except the top-level container:
  10768. *
  10769. * .setValue( gl, value, [textures] )
  10770. *
  10771. * uploads a uniform value(s)
  10772. * the 'textures' parameter is needed for sampler uniforms
  10773. *
  10774. *
  10775. * Static methods of the top-level container (textures factorizations):
  10776. *
  10777. * .upload( gl, seq, values, textures )
  10778. *
  10779. * sets uniforms in 'seq' to 'values[id].value'
  10780. *
  10781. * .seqWithValue( seq, values ) : filteredSeq
  10782. *
  10783. * filters 'seq' entries with corresponding entry in values
  10784. *
  10785. *
  10786. * Methods of the top-level container (textures factorizations):
  10787. *
  10788. * .setValue( gl, name, value, textures )
  10789. *
  10790. * sets uniform with name 'name' to 'value'
  10791. *
  10792. * .setOptional( gl, obj, prop )
  10793. *
  10794. * like .set for an optional property of the object
  10795. *
  10796. */
  10797. const emptyTexture = /*@__PURE__*/ new Texture();
  10798. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10799. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10800. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10801. // --- Utilities ---
  10802. // Array Caches (provide typed arrays for temporary by size)
  10803. const arrayCacheF32 = [];
  10804. const arrayCacheI32 = [];
  10805. // Float32Array caches used for uploading Matrix uniforms
  10806. const mat4array = new Float32Array( 16 );
  10807. const mat3array = new Float32Array( 9 );
  10808. const mat2array = new Float32Array( 4 );
  10809. // Flattening for arrays of vectors and matrices
  10810. function flatten( array, nBlocks, blockSize ) {
  10811. const firstElem = array[ 0 ];
  10812. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10813. // unoptimized: ! isNaN( firstElem )
  10814. // see http://jacksondunstan.com/articles/983
  10815. const n = nBlocks * blockSize;
  10816. let r = arrayCacheF32[ n ];
  10817. if ( r === undefined ) {
  10818. r = new Float32Array( n );
  10819. arrayCacheF32[ n ] = r;
  10820. }
  10821. if ( nBlocks !== 0 ) {
  10822. firstElem.toArray( r, 0 );
  10823. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10824. offset += blockSize;
  10825. array[ i ].toArray( r, offset );
  10826. }
  10827. }
  10828. return r;
  10829. }
  10830. function arraysEqual( a, b ) {
  10831. if ( a.length !== b.length ) return false;
  10832. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10833. if ( a[ i ] !== b[ i ] ) return false;
  10834. }
  10835. return true;
  10836. }
  10837. function copyArray( a, b ) {
  10838. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10839. a[ i ] = b[ i ];
  10840. }
  10841. }
  10842. // Texture unit allocation
  10843. function allocTexUnits( textures, n ) {
  10844. let r = arrayCacheI32[ n ];
  10845. if ( r === undefined ) {
  10846. r = new Int32Array( n );
  10847. arrayCacheI32[ n ] = r;
  10848. }
  10849. for ( let i = 0; i !== n; ++ i ) {
  10850. r[ i ] = textures.allocateTextureUnit();
  10851. }
  10852. return r;
  10853. }
  10854. // --- Setters ---
  10855. // Note: Defining these methods externally, because they come in a bunch
  10856. // and this way their names minify.
  10857. // Single scalar
  10858. function setValueV1f( gl, v ) {
  10859. const cache = this.cache;
  10860. if ( cache[ 0 ] === v ) return;
  10861. gl.uniform1f( this.addr, v );
  10862. cache[ 0 ] = v;
  10863. }
  10864. // Single float vector (from flat array or THREE.VectorN)
  10865. function setValueV2f( gl, v ) {
  10866. const cache = this.cache;
  10867. if ( v.x !== undefined ) {
  10868. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10869. gl.uniform2f( this.addr, v.x, v.y );
  10870. cache[ 0 ] = v.x;
  10871. cache[ 1 ] = v.y;
  10872. }
  10873. } else {
  10874. if ( arraysEqual( cache, v ) ) return;
  10875. gl.uniform2fv( this.addr, v );
  10876. copyArray( cache, v );
  10877. }
  10878. }
  10879. function setValueV3f( gl, v ) {
  10880. const cache = this.cache;
  10881. if ( v.x !== undefined ) {
  10882. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10883. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10884. cache[ 0 ] = v.x;
  10885. cache[ 1 ] = v.y;
  10886. cache[ 2 ] = v.z;
  10887. }
  10888. } else if ( v.r !== undefined ) {
  10889. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10890. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10891. cache[ 0 ] = v.r;
  10892. cache[ 1 ] = v.g;
  10893. cache[ 2 ] = v.b;
  10894. }
  10895. } else {
  10896. if ( arraysEqual( cache, v ) ) return;
  10897. gl.uniform3fv( this.addr, v );
  10898. copyArray( cache, v );
  10899. }
  10900. }
  10901. function setValueV4f( gl, v ) {
  10902. const cache = this.cache;
  10903. if ( v.x !== undefined ) {
  10904. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10905. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10906. cache[ 0 ] = v.x;
  10907. cache[ 1 ] = v.y;
  10908. cache[ 2 ] = v.z;
  10909. cache[ 3 ] = v.w;
  10910. }
  10911. } else {
  10912. if ( arraysEqual( cache, v ) ) return;
  10913. gl.uniform4fv( this.addr, v );
  10914. copyArray( cache, v );
  10915. }
  10916. }
  10917. // Single matrix (from flat array or THREE.MatrixN)
  10918. function setValueM2( gl, v ) {
  10919. const cache = this.cache;
  10920. const elements = v.elements;
  10921. if ( elements === undefined ) {
  10922. if ( arraysEqual( cache, v ) ) return;
  10923. gl.uniformMatrix2fv( this.addr, false, v );
  10924. copyArray( cache, v );
  10925. } else {
  10926. if ( arraysEqual( cache, elements ) ) return;
  10927. mat2array.set( elements );
  10928. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10929. copyArray( cache, elements );
  10930. }
  10931. }
  10932. function setValueM3( gl, v ) {
  10933. const cache = this.cache;
  10934. const elements = v.elements;
  10935. if ( elements === undefined ) {
  10936. if ( arraysEqual( cache, v ) ) return;
  10937. gl.uniformMatrix3fv( this.addr, false, v );
  10938. copyArray( cache, v );
  10939. } else {
  10940. if ( arraysEqual( cache, elements ) ) return;
  10941. mat3array.set( elements );
  10942. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10943. copyArray( cache, elements );
  10944. }
  10945. }
  10946. function setValueM4( gl, v ) {
  10947. const cache = this.cache;
  10948. const elements = v.elements;
  10949. if ( elements === undefined ) {
  10950. if ( arraysEqual( cache, v ) ) return;
  10951. gl.uniformMatrix4fv( this.addr, false, v );
  10952. copyArray( cache, v );
  10953. } else {
  10954. if ( arraysEqual( cache, elements ) ) return;
  10955. mat4array.set( elements );
  10956. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10957. copyArray( cache, elements );
  10958. }
  10959. }
  10960. // Single integer / boolean
  10961. function setValueV1i( gl, v ) {
  10962. const cache = this.cache;
  10963. if ( cache[ 0 ] === v ) return;
  10964. gl.uniform1i( this.addr, v );
  10965. cache[ 0 ] = v;
  10966. }
  10967. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10968. function setValueV2i( gl, v ) {
  10969. const cache = this.cache;
  10970. if ( v.x !== undefined ) {
  10971. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10972. gl.uniform2i( this.addr, v.x, v.y );
  10973. cache[ 0 ] = v.x;
  10974. cache[ 1 ] = v.y;
  10975. }
  10976. } else {
  10977. if ( arraysEqual( cache, v ) ) return;
  10978. gl.uniform2iv( this.addr, v );
  10979. copyArray( cache, v );
  10980. }
  10981. }
  10982. function setValueV3i( gl, v ) {
  10983. const cache = this.cache;
  10984. if ( v.x !== undefined ) {
  10985. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10986. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10987. cache[ 0 ] = v.x;
  10988. cache[ 1 ] = v.y;
  10989. cache[ 2 ] = v.z;
  10990. }
  10991. } else {
  10992. if ( arraysEqual( cache, v ) ) return;
  10993. gl.uniform3iv( this.addr, v );
  10994. copyArray( cache, v );
  10995. }
  10996. }
  10997. function setValueV4i( gl, v ) {
  10998. const cache = this.cache;
  10999. if ( v.x !== undefined ) {
  11000. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11001. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11002. cache[ 0 ] = v.x;
  11003. cache[ 1 ] = v.y;
  11004. cache[ 2 ] = v.z;
  11005. cache[ 3 ] = v.w;
  11006. }
  11007. } else {
  11008. if ( arraysEqual( cache, v ) ) return;
  11009. gl.uniform4iv( this.addr, v );
  11010. copyArray( cache, v );
  11011. }
  11012. }
  11013. // Single unsigned integer
  11014. function setValueV1ui( gl, v ) {
  11015. const cache = this.cache;
  11016. if ( cache[ 0 ] === v ) return;
  11017. gl.uniform1ui( this.addr, v );
  11018. cache[ 0 ] = v;
  11019. }
  11020. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11021. function setValueV2ui( gl, v ) {
  11022. const cache = this.cache;
  11023. if ( v.x !== undefined ) {
  11024. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11025. gl.uniform2ui( this.addr, v.x, v.y );
  11026. cache[ 0 ] = v.x;
  11027. cache[ 1 ] = v.y;
  11028. }
  11029. } else {
  11030. if ( arraysEqual( cache, v ) ) return;
  11031. gl.uniform2uiv( this.addr, v );
  11032. copyArray( cache, v );
  11033. }
  11034. }
  11035. function setValueV3ui( gl, v ) {
  11036. const cache = this.cache;
  11037. if ( v.x !== undefined ) {
  11038. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11039. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11040. cache[ 0 ] = v.x;
  11041. cache[ 1 ] = v.y;
  11042. cache[ 2 ] = v.z;
  11043. }
  11044. } else {
  11045. if ( arraysEqual( cache, v ) ) return;
  11046. gl.uniform3uiv( this.addr, v );
  11047. copyArray( cache, v );
  11048. }
  11049. }
  11050. function setValueV4ui( gl, v ) {
  11051. const cache = this.cache;
  11052. if ( v.x !== undefined ) {
  11053. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11054. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11055. cache[ 0 ] = v.x;
  11056. cache[ 1 ] = v.y;
  11057. cache[ 2 ] = v.z;
  11058. cache[ 3 ] = v.w;
  11059. }
  11060. } else {
  11061. if ( arraysEqual( cache, v ) ) return;
  11062. gl.uniform4uiv( this.addr, v );
  11063. copyArray( cache, v );
  11064. }
  11065. }
  11066. // Single texture (2D / Cube)
  11067. function setValueT1( gl, v, textures ) {
  11068. const cache = this.cache;
  11069. const unit = textures.allocateTextureUnit();
  11070. if ( cache[ 0 ] !== unit ) {
  11071. gl.uniform1i( this.addr, unit );
  11072. cache[ 0 ] = unit;
  11073. }
  11074. textures.setTexture2D( v || emptyTexture, unit );
  11075. }
  11076. function setValueT3D1( gl, v, textures ) {
  11077. const cache = this.cache;
  11078. const unit = textures.allocateTextureUnit();
  11079. if ( cache[ 0 ] !== unit ) {
  11080. gl.uniform1i( this.addr, unit );
  11081. cache[ 0 ] = unit;
  11082. }
  11083. textures.setTexture3D( v || empty3dTexture, unit );
  11084. }
  11085. function setValueT6( gl, v, textures ) {
  11086. const cache = this.cache;
  11087. const unit = textures.allocateTextureUnit();
  11088. if ( cache[ 0 ] !== unit ) {
  11089. gl.uniform1i( this.addr, unit );
  11090. cache[ 0 ] = unit;
  11091. }
  11092. textures.setTextureCube( v || emptyCubeTexture, unit );
  11093. }
  11094. function setValueT2DArray1( gl, v, textures ) {
  11095. const cache = this.cache;
  11096. const unit = textures.allocateTextureUnit();
  11097. if ( cache[ 0 ] !== unit ) {
  11098. gl.uniform1i( this.addr, unit );
  11099. cache[ 0 ] = unit;
  11100. }
  11101. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11102. }
  11103. // Helper to pick the right setter for the singular case
  11104. function getSingularSetter( type ) {
  11105. switch ( type ) {
  11106. case 0x1406: return setValueV1f; // FLOAT
  11107. case 0x8b50: return setValueV2f; // _VEC2
  11108. case 0x8b51: return setValueV3f; // _VEC3
  11109. case 0x8b52: return setValueV4f; // _VEC4
  11110. case 0x8b5a: return setValueM2; // _MAT2
  11111. case 0x8b5b: return setValueM3; // _MAT3
  11112. case 0x8b5c: return setValueM4; // _MAT4
  11113. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11114. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11115. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11116. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11117. case 0x1405: return setValueV1ui; // UINT
  11118. case 0x8dc6: return setValueV2ui; // _VEC2
  11119. case 0x8dc7: return setValueV3ui; // _VEC3
  11120. case 0x8dc8: return setValueV4ui; // _VEC4
  11121. case 0x8b5e: // SAMPLER_2D
  11122. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11123. case 0x8dca: // INT_SAMPLER_2D
  11124. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11125. case 0x8b62: // SAMPLER_2D_SHADOW
  11126. return setValueT1;
  11127. case 0x8b5f: // SAMPLER_3D
  11128. case 0x8dcb: // INT_SAMPLER_3D
  11129. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11130. return setValueT3D1;
  11131. case 0x8b60: // SAMPLER_CUBE
  11132. case 0x8dcc: // INT_SAMPLER_CUBE
  11133. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11134. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11135. return setValueT6;
  11136. case 0x8dc1: // SAMPLER_2D_ARRAY
  11137. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11138. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11139. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11140. return setValueT2DArray1;
  11141. }
  11142. }
  11143. // Array of scalars
  11144. function setValueV1fArray( gl, v ) {
  11145. gl.uniform1fv( this.addr, v );
  11146. }
  11147. // Array of vectors (from flat array or array of THREE.VectorN)
  11148. function setValueV2fArray( gl, v ) {
  11149. const data = flatten( v, this.size, 2 );
  11150. gl.uniform2fv( this.addr, data );
  11151. }
  11152. function setValueV3fArray( gl, v ) {
  11153. const data = flatten( v, this.size, 3 );
  11154. gl.uniform3fv( this.addr, data );
  11155. }
  11156. function setValueV4fArray( gl, v ) {
  11157. const data = flatten( v, this.size, 4 );
  11158. gl.uniform4fv( this.addr, data );
  11159. }
  11160. // Array of matrices (from flat array or array of THREE.MatrixN)
  11161. function setValueM2Array( gl, v ) {
  11162. const data = flatten( v, this.size, 4 );
  11163. gl.uniformMatrix2fv( this.addr, false, data );
  11164. }
  11165. function setValueM3Array( gl, v ) {
  11166. const data = flatten( v, this.size, 9 );
  11167. gl.uniformMatrix3fv( this.addr, false, data );
  11168. }
  11169. function setValueM4Array( gl, v ) {
  11170. const data = flatten( v, this.size, 16 );
  11171. gl.uniformMatrix4fv( this.addr, false, data );
  11172. }
  11173. // Array of integer / boolean
  11174. function setValueV1iArray( gl, v ) {
  11175. gl.uniform1iv( this.addr, v );
  11176. }
  11177. // Array of integer / boolean vectors (from flat array)
  11178. function setValueV2iArray( gl, v ) {
  11179. gl.uniform2iv( this.addr, v );
  11180. }
  11181. function setValueV3iArray( gl, v ) {
  11182. gl.uniform3iv( this.addr, v );
  11183. }
  11184. function setValueV4iArray( gl, v ) {
  11185. gl.uniform4iv( this.addr, v );
  11186. }
  11187. // Array of unsigned integer
  11188. function setValueV1uiArray( gl, v ) {
  11189. gl.uniform1uiv( this.addr, v );
  11190. }
  11191. // Array of unsigned integer vectors (from flat array)
  11192. function setValueV2uiArray( gl, v ) {
  11193. gl.uniform2uiv( this.addr, v );
  11194. }
  11195. function setValueV3uiArray( gl, v ) {
  11196. gl.uniform3uiv( this.addr, v );
  11197. }
  11198. function setValueV4uiArray( gl, v ) {
  11199. gl.uniform4uiv( this.addr, v );
  11200. }
  11201. // Array of textures (2D / 3D / Cube / 2DArray)
  11202. function setValueT1Array( gl, v, textures ) {
  11203. const cache = this.cache;
  11204. const n = v.length;
  11205. const units = allocTexUnits( textures, n );
  11206. if ( ! arraysEqual( cache, units ) ) {
  11207. gl.uniform1iv( this.addr, units );
  11208. copyArray( cache, units );
  11209. }
  11210. for ( let i = 0; i !== n; ++ i ) {
  11211. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11212. }
  11213. }
  11214. function setValueT3DArray( gl, v, textures ) {
  11215. const cache = this.cache;
  11216. const n = v.length;
  11217. const units = allocTexUnits( textures, n );
  11218. if ( ! arraysEqual( cache, units ) ) {
  11219. gl.uniform1iv( this.addr, units );
  11220. copyArray( cache, units );
  11221. }
  11222. for ( let i = 0; i !== n; ++ i ) {
  11223. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11224. }
  11225. }
  11226. function setValueT6Array( gl, v, textures ) {
  11227. const cache = this.cache;
  11228. const n = v.length;
  11229. const units = allocTexUnits( textures, n );
  11230. if ( ! arraysEqual( cache, units ) ) {
  11231. gl.uniform1iv( this.addr, units );
  11232. copyArray( cache, units );
  11233. }
  11234. for ( let i = 0; i !== n; ++ i ) {
  11235. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11236. }
  11237. }
  11238. function setValueT2DArrayArray( gl, v, textures ) {
  11239. const cache = this.cache;
  11240. const n = v.length;
  11241. const units = allocTexUnits( textures, n );
  11242. if ( ! arraysEqual( cache, units ) ) {
  11243. gl.uniform1iv( this.addr, units );
  11244. copyArray( cache, units );
  11245. }
  11246. for ( let i = 0; i !== n; ++ i ) {
  11247. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11248. }
  11249. }
  11250. // Helper to pick the right setter for a pure (bottom-level) array
  11251. function getPureArraySetter( type ) {
  11252. switch ( type ) {
  11253. case 0x1406: return setValueV1fArray; // FLOAT
  11254. case 0x8b50: return setValueV2fArray; // _VEC2
  11255. case 0x8b51: return setValueV3fArray; // _VEC3
  11256. case 0x8b52: return setValueV4fArray; // _VEC4
  11257. case 0x8b5a: return setValueM2Array; // _MAT2
  11258. case 0x8b5b: return setValueM3Array; // _MAT3
  11259. case 0x8b5c: return setValueM4Array; // _MAT4
  11260. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11261. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11262. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11263. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11264. case 0x1405: return setValueV1uiArray; // UINT
  11265. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11266. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11267. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11268. case 0x8b5e: // SAMPLER_2D
  11269. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11270. case 0x8dca: // INT_SAMPLER_2D
  11271. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11272. case 0x8b62: // SAMPLER_2D_SHADOW
  11273. return setValueT1Array;
  11274. case 0x8b5f: // SAMPLER_3D
  11275. case 0x8dcb: // INT_SAMPLER_3D
  11276. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11277. return setValueT3DArray;
  11278. case 0x8b60: // SAMPLER_CUBE
  11279. case 0x8dcc: // INT_SAMPLER_CUBE
  11280. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11281. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11282. return setValueT6Array;
  11283. case 0x8dc1: // SAMPLER_2D_ARRAY
  11284. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11285. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11286. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11287. return setValueT2DArrayArray;
  11288. }
  11289. }
  11290. // --- Uniform Classes ---
  11291. class SingleUniform {
  11292. constructor( id, activeInfo, addr ) {
  11293. this.id = id;
  11294. this.addr = addr;
  11295. this.cache = [];
  11296. this.setValue = getSingularSetter( activeInfo.type );
  11297. // this.path = activeInfo.name; // DEBUG
  11298. }
  11299. }
  11300. class PureArrayUniform {
  11301. constructor( id, activeInfo, addr ) {
  11302. this.id = id;
  11303. this.addr = addr;
  11304. this.cache = [];
  11305. this.size = activeInfo.size;
  11306. this.setValue = getPureArraySetter( activeInfo.type );
  11307. // this.path = activeInfo.name; // DEBUG
  11308. }
  11309. }
  11310. class StructuredUniform {
  11311. constructor( id ) {
  11312. this.id = id;
  11313. this.seq = [];
  11314. this.map = {};
  11315. }
  11316. setValue( gl, value, textures ) {
  11317. const seq = this.seq;
  11318. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11319. const u = seq[ i ];
  11320. u.setValue( gl, value[ u.id ], textures );
  11321. }
  11322. }
  11323. }
  11324. // --- Top-level ---
  11325. // Parser - builds up the property tree from the path strings
  11326. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11327. // extracts
  11328. // - the identifier (member name or array index)
  11329. // - followed by an optional right bracket (found when array index)
  11330. // - followed by an optional left bracket or dot (type of subscript)
  11331. //
  11332. // Note: These portions can be read in a non-overlapping fashion and
  11333. // allow straightforward parsing of the hierarchy that WebGL encodes
  11334. // in the uniform names.
  11335. function addUniform( container, uniformObject ) {
  11336. container.seq.push( uniformObject );
  11337. container.map[ uniformObject.id ] = uniformObject;
  11338. }
  11339. function parseUniform( activeInfo, addr, container ) {
  11340. const path = activeInfo.name,
  11341. pathLength = path.length;
  11342. // reset RegExp object, because of the early exit of a previous run
  11343. RePathPart.lastIndex = 0;
  11344. while ( true ) {
  11345. const match = RePathPart.exec( path ),
  11346. matchEnd = RePathPart.lastIndex;
  11347. let id = match[ 1 ];
  11348. const idIsIndex = match[ 2 ] === ']',
  11349. subscript = match[ 3 ];
  11350. if ( idIsIndex ) id = id | 0; // convert to integer
  11351. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11352. // bare name or "pure" bottom-level array "[0]" suffix
  11353. addUniform( container, subscript === undefined ?
  11354. new SingleUniform( id, activeInfo, addr ) :
  11355. new PureArrayUniform( id, activeInfo, addr ) );
  11356. break;
  11357. } else {
  11358. // step into inner node / create it in case it doesn't exist
  11359. const map = container.map;
  11360. let next = map[ id ];
  11361. if ( next === undefined ) {
  11362. next = new StructuredUniform( id );
  11363. addUniform( container, next );
  11364. }
  11365. container = next;
  11366. }
  11367. }
  11368. }
  11369. // Root Container
  11370. class WebGLUniforms {
  11371. constructor( gl, program ) {
  11372. this.seq = [];
  11373. this.map = {};
  11374. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11375. for ( let i = 0; i < n; ++ i ) {
  11376. const info = gl.getActiveUniform( program, i ),
  11377. addr = gl.getUniformLocation( program, info.name );
  11378. parseUniform( info, addr, this );
  11379. }
  11380. }
  11381. setValue( gl, name, value, textures ) {
  11382. const u = this.map[ name ];
  11383. if ( u !== undefined ) u.setValue( gl, value, textures );
  11384. }
  11385. setOptional( gl, object, name ) {
  11386. const v = object[ name ];
  11387. if ( v !== undefined ) this.setValue( gl, name, v );
  11388. }
  11389. static upload( gl, seq, values, textures ) {
  11390. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11391. const u = seq[ i ],
  11392. v = values[ u.id ];
  11393. if ( v.needsUpdate !== false ) {
  11394. // note: always updating when .needsUpdate is undefined
  11395. u.setValue( gl, v.value, textures );
  11396. }
  11397. }
  11398. }
  11399. static seqWithValue( seq, values ) {
  11400. const r = [];
  11401. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11402. const u = seq[ i ];
  11403. if ( u.id in values ) r.push( u );
  11404. }
  11405. return r;
  11406. }
  11407. }
  11408. function WebGLShader( gl, type, string ) {
  11409. const shader = gl.createShader( type );
  11410. gl.shaderSource( shader, string );
  11411. gl.compileShader( shader );
  11412. return shader;
  11413. }
  11414. let programIdCount = 0;
  11415. function handleSource( string, errorLine ) {
  11416. const lines = string.split( '\n' );
  11417. const lines2 = [];
  11418. const from = Math.max( errorLine - 6, 0 );
  11419. const to = Math.min( errorLine + 6, lines.length );
  11420. for ( let i = from; i < to; i ++ ) {
  11421. const line = i + 1;
  11422. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11423. }
  11424. return lines2.join( '\n' );
  11425. }
  11426. function getEncodingComponents( colorSpace ) {
  11427. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11428. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11429. let gamutMapping;
  11430. if ( workingPrimaries === encodingPrimaries ) {
  11431. gamutMapping = '';
  11432. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11433. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11434. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11435. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11436. }
  11437. switch ( colorSpace ) {
  11438. case LinearSRGBColorSpace:
  11439. case LinearDisplayP3ColorSpace:
  11440. return [ gamutMapping, 'LinearTransferOETF' ];
  11441. case SRGBColorSpace:
  11442. case DisplayP3ColorSpace:
  11443. return [ gamutMapping, 'sRGBTransferOETF' ];
  11444. default:
  11445. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11446. return [ gamutMapping, 'LinearTransferOETF' ];
  11447. }
  11448. }
  11449. function getShaderErrors( gl, shader, type ) {
  11450. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11451. const errors = gl.getShaderInfoLog( shader ).trim();
  11452. if ( status && errors === '' ) return '';
  11453. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11454. if ( errorMatches ) {
  11455. // --enable-privileged-webgl-extension
  11456. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11457. const errorLine = parseInt( errorMatches[ 1 ] );
  11458. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11459. } else {
  11460. return errors;
  11461. }
  11462. }
  11463. function getTexelEncodingFunction( functionName, colorSpace ) {
  11464. const components = getEncodingComponents( colorSpace );
  11465. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11466. }
  11467. function getToneMappingFunction( functionName, toneMapping ) {
  11468. let toneMappingName;
  11469. switch ( toneMapping ) {
  11470. case LinearToneMapping:
  11471. toneMappingName = 'Linear';
  11472. break;
  11473. case ReinhardToneMapping:
  11474. toneMappingName = 'Reinhard';
  11475. break;
  11476. case CineonToneMapping:
  11477. toneMappingName = 'OptimizedCineon';
  11478. break;
  11479. case ACESFilmicToneMapping:
  11480. toneMappingName = 'ACESFilmic';
  11481. break;
  11482. case CustomToneMapping:
  11483. toneMappingName = 'Custom';
  11484. break;
  11485. default:
  11486. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11487. toneMappingName = 'Linear';
  11488. }
  11489. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11490. }
  11491. function generateExtensions( parameters ) {
  11492. const chunks = [
  11493. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11494. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11495. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11496. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11497. ];
  11498. return chunks.filter( filterEmptyLine ).join( '\n' );
  11499. }
  11500. function generateDefines( defines ) {
  11501. const chunks = [];
  11502. for ( const name in defines ) {
  11503. const value = defines[ name ];
  11504. if ( value === false ) continue;
  11505. chunks.push( '#define ' + name + ' ' + value );
  11506. }
  11507. return chunks.join( '\n' );
  11508. }
  11509. function fetchAttributeLocations( gl, program ) {
  11510. const attributes = {};
  11511. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11512. for ( let i = 0; i < n; i ++ ) {
  11513. const info = gl.getActiveAttrib( program, i );
  11514. const name = info.name;
  11515. let locationSize = 1;
  11516. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11517. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11518. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11519. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11520. attributes[ name ] = {
  11521. type: info.type,
  11522. location: gl.getAttribLocation( program, name ),
  11523. locationSize: locationSize
  11524. };
  11525. }
  11526. return attributes;
  11527. }
  11528. function filterEmptyLine( string ) {
  11529. return string !== '';
  11530. }
  11531. function replaceLightNums( string, parameters ) {
  11532. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11533. return string
  11534. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11535. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11536. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11537. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11538. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11539. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11540. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11541. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11542. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11543. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11544. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11545. }
  11546. function replaceClippingPlaneNums( string, parameters ) {
  11547. return string
  11548. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11549. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11550. }
  11551. // Resolve Includes
  11552. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11553. function resolveIncludes( string ) {
  11554. return string.replace( includePattern, includeReplacer );
  11555. }
  11556. const shaderChunkMap = new Map( [
  11557. [ 'encodings_fragment', 'colorspace_fragment' ], // @deprecated, r154
  11558. [ 'encodings_pars_fragment', 'colorspace_pars_fragment' ], // @deprecated, r154
  11559. [ 'output_fragment', 'opaque_fragment' ], // @deprecated, r154
  11560. ] );
  11561. function includeReplacer( match, include ) {
  11562. let string = ShaderChunk[ include ];
  11563. if ( string === undefined ) {
  11564. const newInclude = shaderChunkMap.get( include );
  11565. if ( newInclude !== undefined ) {
  11566. string = ShaderChunk[ newInclude ];
  11567. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11568. } else {
  11569. throw new Error( 'Can not resolve #include <' + include + '>' );
  11570. }
  11571. }
  11572. return resolveIncludes( string );
  11573. }
  11574. // Unroll Loops
  11575. 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;
  11576. function unrollLoops( string ) {
  11577. return string.replace( unrollLoopPattern, loopReplacer );
  11578. }
  11579. function loopReplacer( match, start, end, snippet ) {
  11580. let string = '';
  11581. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11582. string += snippet
  11583. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11584. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11585. }
  11586. return string;
  11587. }
  11588. //
  11589. function generatePrecision( parameters ) {
  11590. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11591. if ( parameters.precision === 'highp' ) {
  11592. precisionstring += '\n#define HIGH_PRECISION';
  11593. } else if ( parameters.precision === 'mediump' ) {
  11594. precisionstring += '\n#define MEDIUM_PRECISION';
  11595. } else if ( parameters.precision === 'lowp' ) {
  11596. precisionstring += '\n#define LOW_PRECISION';
  11597. }
  11598. return precisionstring;
  11599. }
  11600. function generateShadowMapTypeDefine( parameters ) {
  11601. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11602. if ( parameters.shadowMapType === PCFShadowMap ) {
  11603. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11604. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11605. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11606. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11607. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11608. }
  11609. return shadowMapTypeDefine;
  11610. }
  11611. function generateEnvMapTypeDefine( parameters ) {
  11612. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11613. if ( parameters.envMap ) {
  11614. switch ( parameters.envMapMode ) {
  11615. case CubeReflectionMapping:
  11616. case CubeRefractionMapping:
  11617. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11618. break;
  11619. case CubeUVReflectionMapping:
  11620. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11621. break;
  11622. }
  11623. }
  11624. return envMapTypeDefine;
  11625. }
  11626. function generateEnvMapModeDefine( parameters ) {
  11627. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11628. if ( parameters.envMap ) {
  11629. switch ( parameters.envMapMode ) {
  11630. case CubeRefractionMapping:
  11631. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11632. break;
  11633. }
  11634. }
  11635. return envMapModeDefine;
  11636. }
  11637. function generateEnvMapBlendingDefine( parameters ) {
  11638. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11639. if ( parameters.envMap ) {
  11640. switch ( parameters.combine ) {
  11641. case MultiplyOperation:
  11642. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11643. break;
  11644. case MixOperation:
  11645. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11646. break;
  11647. case AddOperation:
  11648. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11649. break;
  11650. }
  11651. }
  11652. return envMapBlendingDefine;
  11653. }
  11654. function generateCubeUVSize( parameters ) {
  11655. const imageHeight = parameters.envMapCubeUVHeight;
  11656. if ( imageHeight === null ) return null;
  11657. const maxMip = Math.log2( imageHeight ) - 2;
  11658. const texelHeight = 1.0 / imageHeight;
  11659. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11660. return { texelWidth, texelHeight, maxMip };
  11661. }
  11662. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11663. // TODO Send this event to Three.js DevTools
  11664. // console.log( 'WebGLProgram', cacheKey );
  11665. const gl = renderer.getContext();
  11666. const defines = parameters.defines;
  11667. let vertexShader = parameters.vertexShader;
  11668. let fragmentShader = parameters.fragmentShader;
  11669. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11670. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11671. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11672. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11673. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11674. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11675. const customDefines = generateDefines( defines );
  11676. const program = gl.createProgram();
  11677. let prefixVertex, prefixFragment;
  11678. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11679. if ( parameters.isRawShaderMaterial ) {
  11680. prefixVertex = [
  11681. '#define SHADER_TYPE ' + parameters.shaderType,
  11682. '#define SHADER_NAME ' + parameters.shaderName,
  11683. customDefines
  11684. ].filter( filterEmptyLine ).join( '\n' );
  11685. if ( prefixVertex.length > 0 ) {
  11686. prefixVertex += '\n';
  11687. }
  11688. prefixFragment = [
  11689. customExtensions,
  11690. '#define SHADER_TYPE ' + parameters.shaderType,
  11691. '#define SHADER_NAME ' + parameters.shaderName,
  11692. customDefines
  11693. ].filter( filterEmptyLine ).join( '\n' );
  11694. if ( prefixFragment.length > 0 ) {
  11695. prefixFragment += '\n';
  11696. }
  11697. } else {
  11698. prefixVertex = [
  11699. generatePrecision( parameters ),
  11700. '#define SHADER_TYPE ' + parameters.shaderType,
  11701. '#define SHADER_NAME ' + parameters.shaderName,
  11702. customDefines,
  11703. parameters.instancing ? '#define USE_INSTANCING' : '',
  11704. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11705. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11706. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11707. parameters.map ? '#define USE_MAP' : '',
  11708. parameters.envMap ? '#define USE_ENVMAP' : '',
  11709. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11710. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11711. parameters.aoMap ? '#define USE_AOMAP' : '',
  11712. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11713. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11714. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11715. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11716. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11717. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11718. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11719. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11720. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11721. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11722. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11723. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11724. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11725. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11726. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11727. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11728. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11729. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11730. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11731. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11732. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11733. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11734. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11735. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11736. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11737. //
  11738. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11739. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11740. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11741. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11742. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11743. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11744. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11745. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11746. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11747. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11748. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11749. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11750. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11751. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11752. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11753. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11754. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11755. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11756. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11757. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11758. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11759. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11760. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11761. //
  11762. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11763. parameters.vertexColors ? '#define USE_COLOR' : '',
  11764. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11765. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11766. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11767. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11768. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11769. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11770. parameters.skinning ? '#define USE_SKINNING' : '',
  11771. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11772. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11773. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11774. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11775. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11776. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11777. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11778. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11779. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11780. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11781. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11782. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11783. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11784. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11785. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11786. 'uniform mat4 modelMatrix;',
  11787. 'uniform mat4 modelViewMatrix;',
  11788. 'uniform mat4 projectionMatrix;',
  11789. 'uniform mat4 viewMatrix;',
  11790. 'uniform mat3 normalMatrix;',
  11791. 'uniform vec3 cameraPosition;',
  11792. 'uniform bool isOrthographic;',
  11793. '#ifdef USE_INSTANCING',
  11794. ' attribute mat4 instanceMatrix;',
  11795. '#endif',
  11796. '#ifdef USE_INSTANCING_COLOR',
  11797. ' attribute vec3 instanceColor;',
  11798. '#endif',
  11799. 'attribute vec3 position;',
  11800. 'attribute vec3 normal;',
  11801. 'attribute vec2 uv;',
  11802. '#ifdef USE_UV1',
  11803. ' attribute vec2 uv1;',
  11804. '#endif',
  11805. '#ifdef USE_UV2',
  11806. ' attribute vec2 uv2;',
  11807. '#endif',
  11808. '#ifdef USE_UV3',
  11809. ' attribute vec2 uv3;',
  11810. '#endif',
  11811. '#ifdef USE_TANGENT',
  11812. ' attribute vec4 tangent;',
  11813. '#endif',
  11814. '#if defined( USE_COLOR_ALPHA )',
  11815. ' attribute vec4 color;',
  11816. '#elif defined( USE_COLOR )',
  11817. ' attribute vec3 color;',
  11818. '#endif',
  11819. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11820. ' attribute vec3 morphTarget0;',
  11821. ' attribute vec3 morphTarget1;',
  11822. ' attribute vec3 morphTarget2;',
  11823. ' attribute vec3 morphTarget3;',
  11824. ' #ifdef USE_MORPHNORMALS',
  11825. ' attribute vec3 morphNormal0;',
  11826. ' attribute vec3 morphNormal1;',
  11827. ' attribute vec3 morphNormal2;',
  11828. ' attribute vec3 morphNormal3;',
  11829. ' #else',
  11830. ' attribute vec3 morphTarget4;',
  11831. ' attribute vec3 morphTarget5;',
  11832. ' attribute vec3 morphTarget6;',
  11833. ' attribute vec3 morphTarget7;',
  11834. ' #endif',
  11835. '#endif',
  11836. '#ifdef USE_SKINNING',
  11837. ' attribute vec4 skinIndex;',
  11838. ' attribute vec4 skinWeight;',
  11839. '#endif',
  11840. '\n'
  11841. ].filter( filterEmptyLine ).join( '\n' );
  11842. prefixFragment = [
  11843. customExtensions,
  11844. generatePrecision( parameters ),
  11845. '#define SHADER_TYPE ' + parameters.shaderType,
  11846. '#define SHADER_NAME ' + parameters.shaderName,
  11847. customDefines,
  11848. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11849. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11850. parameters.map ? '#define USE_MAP' : '',
  11851. parameters.matcap ? '#define USE_MATCAP' : '',
  11852. parameters.envMap ? '#define USE_ENVMAP' : '',
  11853. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11854. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11855. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11856. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11857. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11858. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11859. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11860. parameters.aoMap ? '#define USE_AOMAP' : '',
  11861. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11862. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11863. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11864. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11865. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11866. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11867. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11868. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11869. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11870. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11871. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11872. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11873. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11874. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11875. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11876. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11877. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11878. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11879. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11880. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11881. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11882. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11883. parameters.sheen ? '#define USE_SHEEN' : '',
  11884. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11885. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11886. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11887. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11888. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11889. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11890. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11891. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11892. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11893. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11894. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11895. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11896. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11897. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11898. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11899. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11900. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11901. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11902. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11903. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11904. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11905. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11906. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11907. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11908. 'uniform mat4 viewMatrix;',
  11909. 'uniform vec3 cameraPosition;',
  11910. 'uniform bool isOrthographic;',
  11911. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11912. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11913. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11914. parameters.dithering ? '#define DITHERING' : '',
  11915. parameters.opaque ? '#define OPAQUE' : '',
  11916. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11917. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  11918. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11919. '\n'
  11920. ].filter( filterEmptyLine ).join( '\n' );
  11921. }
  11922. vertexShader = resolveIncludes( vertexShader );
  11923. vertexShader = replaceLightNums( vertexShader, parameters );
  11924. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11925. fragmentShader = resolveIncludes( fragmentShader );
  11926. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11927. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11928. vertexShader = unrollLoops( vertexShader );
  11929. fragmentShader = unrollLoops( fragmentShader );
  11930. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11931. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11932. versionString = '#version 300 es\n';
  11933. prefixVertex = [
  11934. 'precision mediump sampler2DArray;',
  11935. '#define attribute in',
  11936. '#define varying out',
  11937. '#define texture2D texture'
  11938. ].join( '\n' ) + '\n' + prefixVertex;
  11939. prefixFragment = [
  11940. '#define varying in',
  11941. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11942. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11943. '#define gl_FragDepthEXT gl_FragDepth',
  11944. '#define texture2D texture',
  11945. '#define textureCube texture',
  11946. '#define texture2DProj textureProj',
  11947. '#define texture2DLodEXT textureLod',
  11948. '#define texture2DProjLodEXT textureProjLod',
  11949. '#define textureCubeLodEXT textureLod',
  11950. '#define texture2DGradEXT textureGrad',
  11951. '#define texture2DProjGradEXT textureProjGrad',
  11952. '#define textureCubeGradEXT textureGrad'
  11953. ].join( '\n' ) + '\n' + prefixFragment;
  11954. }
  11955. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11956. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11957. // console.log( '*VERTEX*', vertexGlsl );
  11958. // console.log( '*FRAGMENT*', fragmentGlsl );
  11959. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11960. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11961. gl.attachShader( program, glVertexShader );
  11962. gl.attachShader( program, glFragmentShader );
  11963. // Force a particular attribute to index 0.
  11964. if ( parameters.index0AttributeName !== undefined ) {
  11965. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11966. } else if ( parameters.morphTargets === true ) {
  11967. // programs with morphTargets displace position out of attribute 0
  11968. gl.bindAttribLocation( program, 0, 'position' );
  11969. }
  11970. gl.linkProgram( program );
  11971. // check for link errors
  11972. if ( renderer.debug.checkShaderErrors ) {
  11973. const programLog = gl.getProgramInfoLog( program ).trim();
  11974. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11975. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11976. let runnable = true;
  11977. let haveDiagnostics = true;
  11978. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11979. runnable = false;
  11980. if ( typeof renderer.debug.onShaderError === 'function' ) {
  11981. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  11982. } else {
  11983. // default error reporting
  11984. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11985. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11986. console.error(
  11987. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11988. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11989. 'Program Info Log: ' + programLog + '\n' +
  11990. vertexErrors + '\n' +
  11991. fragmentErrors
  11992. );
  11993. }
  11994. } else if ( programLog !== '' ) {
  11995. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11996. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11997. haveDiagnostics = false;
  11998. }
  11999. if ( haveDiagnostics ) {
  12000. this.diagnostics = {
  12001. runnable: runnable,
  12002. programLog: programLog,
  12003. vertexShader: {
  12004. log: vertexLog,
  12005. prefix: prefixVertex
  12006. },
  12007. fragmentShader: {
  12008. log: fragmentLog,
  12009. prefix: prefixFragment
  12010. }
  12011. };
  12012. }
  12013. }
  12014. // Clean up
  12015. // Crashes in iOS9 and iOS10. #18402
  12016. // gl.detachShader( program, glVertexShader );
  12017. // gl.detachShader( program, glFragmentShader );
  12018. gl.deleteShader( glVertexShader );
  12019. gl.deleteShader( glFragmentShader );
  12020. // set up caching for uniform locations
  12021. let cachedUniforms;
  12022. this.getUniforms = function () {
  12023. if ( cachedUniforms === undefined ) {
  12024. cachedUniforms = new WebGLUniforms( gl, program );
  12025. }
  12026. return cachedUniforms;
  12027. };
  12028. // set up caching for attribute locations
  12029. let cachedAttributes;
  12030. this.getAttributes = function () {
  12031. if ( cachedAttributes === undefined ) {
  12032. cachedAttributes = fetchAttributeLocations( gl, program );
  12033. }
  12034. return cachedAttributes;
  12035. };
  12036. // free resource
  12037. this.destroy = function () {
  12038. bindingStates.releaseStatesOfProgram( this );
  12039. gl.deleteProgram( program );
  12040. this.program = undefined;
  12041. };
  12042. //
  12043. this.type = parameters.shaderType;
  12044. this.name = parameters.shaderName;
  12045. this.id = programIdCount ++;
  12046. this.cacheKey = cacheKey;
  12047. this.usedTimes = 1;
  12048. this.program = program;
  12049. this.vertexShader = glVertexShader;
  12050. this.fragmentShader = glFragmentShader;
  12051. return this;
  12052. }
  12053. let _id$1 = 0;
  12054. class WebGLShaderCache {
  12055. constructor() {
  12056. this.shaderCache = new Map();
  12057. this.materialCache = new Map();
  12058. }
  12059. update( material ) {
  12060. const vertexShader = material.vertexShader;
  12061. const fragmentShader = material.fragmentShader;
  12062. const vertexShaderStage = this._getShaderStage( vertexShader );
  12063. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12064. const materialShaders = this._getShaderCacheForMaterial( material );
  12065. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12066. materialShaders.add( vertexShaderStage );
  12067. vertexShaderStage.usedTimes ++;
  12068. }
  12069. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12070. materialShaders.add( fragmentShaderStage );
  12071. fragmentShaderStage.usedTimes ++;
  12072. }
  12073. return this;
  12074. }
  12075. remove( material ) {
  12076. const materialShaders = this.materialCache.get( material );
  12077. for ( const shaderStage of materialShaders ) {
  12078. shaderStage.usedTimes --;
  12079. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12080. }
  12081. this.materialCache.delete( material );
  12082. return this;
  12083. }
  12084. getVertexShaderID( material ) {
  12085. return this._getShaderStage( material.vertexShader ).id;
  12086. }
  12087. getFragmentShaderID( material ) {
  12088. return this._getShaderStage( material.fragmentShader ).id;
  12089. }
  12090. dispose() {
  12091. this.shaderCache.clear();
  12092. this.materialCache.clear();
  12093. }
  12094. _getShaderCacheForMaterial( material ) {
  12095. const cache = this.materialCache;
  12096. let set = cache.get( material );
  12097. if ( set === undefined ) {
  12098. set = new Set();
  12099. cache.set( material, set );
  12100. }
  12101. return set;
  12102. }
  12103. _getShaderStage( code ) {
  12104. const cache = this.shaderCache;
  12105. let stage = cache.get( code );
  12106. if ( stage === undefined ) {
  12107. stage = new WebGLShaderStage( code );
  12108. cache.set( code, stage );
  12109. }
  12110. return stage;
  12111. }
  12112. }
  12113. class WebGLShaderStage {
  12114. constructor( code ) {
  12115. this.id = _id$1 ++;
  12116. this.code = code;
  12117. this.usedTimes = 0;
  12118. }
  12119. }
  12120. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12121. const _programLayers = new Layers();
  12122. const _customShaders = new WebGLShaderCache();
  12123. const programs = [];
  12124. const IS_WEBGL2 = capabilities.isWebGL2;
  12125. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12126. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12127. let precision = capabilities.precision;
  12128. const shaderIDs = {
  12129. MeshDepthMaterial: 'depth',
  12130. MeshDistanceMaterial: 'distanceRGBA',
  12131. MeshNormalMaterial: 'normal',
  12132. MeshBasicMaterial: 'basic',
  12133. MeshLambertMaterial: 'lambert',
  12134. MeshPhongMaterial: 'phong',
  12135. MeshToonMaterial: 'toon',
  12136. MeshStandardMaterial: 'physical',
  12137. MeshPhysicalMaterial: 'physical',
  12138. MeshMatcapMaterial: 'matcap',
  12139. LineBasicMaterial: 'basic',
  12140. LineDashedMaterial: 'dashed',
  12141. PointsMaterial: 'points',
  12142. ShadowMaterial: 'shadow',
  12143. SpriteMaterial: 'sprite'
  12144. };
  12145. function getChannel( value ) {
  12146. if ( value === 0 ) return 'uv';
  12147. return `uv${ value }`;
  12148. }
  12149. function getParameters( material, lights, shadows, scene, object ) {
  12150. const fog = scene.fog;
  12151. const geometry = object.geometry;
  12152. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12153. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12154. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12155. const shaderID = shaderIDs[ material.type ];
  12156. // heuristics to create shader parameters according to lights in the scene
  12157. // (not to blow over maxLights budget)
  12158. if ( material.precision !== null ) {
  12159. precision = capabilities.getMaxPrecision( material.precision );
  12160. if ( precision !== material.precision ) {
  12161. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12162. }
  12163. }
  12164. //
  12165. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12166. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12167. let morphTextureStride = 0;
  12168. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12169. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12170. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12171. //
  12172. let vertexShader, fragmentShader;
  12173. let customVertexShaderID, customFragmentShaderID;
  12174. if ( shaderID ) {
  12175. const shader = ShaderLib[ shaderID ];
  12176. vertexShader = shader.vertexShader;
  12177. fragmentShader = shader.fragmentShader;
  12178. } else {
  12179. vertexShader = material.vertexShader;
  12180. fragmentShader = material.fragmentShader;
  12181. _customShaders.update( material );
  12182. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12183. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12184. }
  12185. const currentRenderTarget = renderer.getRenderTarget();
  12186. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12187. const HAS_MAP = !! material.map;
  12188. const HAS_MATCAP = !! material.matcap;
  12189. const HAS_ENVMAP = !! envMap;
  12190. const HAS_AOMAP = !! material.aoMap;
  12191. const HAS_LIGHTMAP = !! material.lightMap;
  12192. const HAS_BUMPMAP = !! material.bumpMap;
  12193. const HAS_NORMALMAP = !! material.normalMap;
  12194. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12195. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12196. const HAS_METALNESSMAP = !! material.metalnessMap;
  12197. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12198. const HAS_ANISOTROPY = material.anisotropy > 0;
  12199. const HAS_CLEARCOAT = material.clearcoat > 0;
  12200. const HAS_IRIDESCENCE = material.iridescence > 0;
  12201. const HAS_SHEEN = material.sheen > 0;
  12202. const HAS_TRANSMISSION = material.transmission > 0;
  12203. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12204. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12205. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12206. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12207. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12208. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12209. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12210. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12211. const HAS_SPECULARMAP = !! material.specularMap;
  12212. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12213. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12214. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12215. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12216. const HAS_GRADIENTMAP = !! material.gradientMap;
  12217. const HAS_ALPHAMAP = !! material.alphaMap;
  12218. const HAS_ALPHATEST = material.alphaTest > 0;
  12219. const HAS_ALPHAHASH = !! material.alphaHash;
  12220. const HAS_EXTENSIONS = !! material.extensions;
  12221. const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1;
  12222. const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;
  12223. const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3;
  12224. let toneMapping = NoToneMapping;
  12225. if ( material.toneMapped ) {
  12226. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12227. toneMapping = renderer.toneMapping;
  12228. }
  12229. }
  12230. const parameters = {
  12231. isWebGL2: IS_WEBGL2,
  12232. shaderID: shaderID,
  12233. shaderType: material.type,
  12234. shaderName: material.name,
  12235. vertexShader: vertexShader,
  12236. fragmentShader: fragmentShader,
  12237. defines: material.defines,
  12238. customVertexShaderID: customVertexShaderID,
  12239. customFragmentShaderID: customFragmentShaderID,
  12240. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12241. glslVersion: material.glslVersion,
  12242. precision: precision,
  12243. instancing: IS_INSTANCEDMESH,
  12244. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12245. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12246. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12247. map: HAS_MAP,
  12248. matcap: HAS_MATCAP,
  12249. envMap: HAS_ENVMAP,
  12250. envMapMode: HAS_ENVMAP && envMap.mapping,
  12251. envMapCubeUVHeight: envMapCubeUVHeight,
  12252. aoMap: HAS_AOMAP,
  12253. lightMap: HAS_LIGHTMAP,
  12254. bumpMap: HAS_BUMPMAP,
  12255. normalMap: HAS_NORMALMAP,
  12256. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12257. emissiveMap: HAS_EMISSIVEMAP,
  12258. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12259. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12260. metalnessMap: HAS_METALNESSMAP,
  12261. roughnessMap: HAS_ROUGHNESSMAP,
  12262. anisotropy: HAS_ANISOTROPY,
  12263. anisotropyMap: HAS_ANISOTROPYMAP,
  12264. clearcoat: HAS_CLEARCOAT,
  12265. clearcoatMap: HAS_CLEARCOATMAP,
  12266. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12267. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12268. iridescence: HAS_IRIDESCENCE,
  12269. iridescenceMap: HAS_IRIDESCENCEMAP,
  12270. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12271. sheen: HAS_SHEEN,
  12272. sheenColorMap: HAS_SHEEN_COLORMAP,
  12273. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12274. specularMap: HAS_SPECULARMAP,
  12275. specularColorMap: HAS_SPECULAR_COLORMAP,
  12276. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12277. transmission: HAS_TRANSMISSION,
  12278. transmissionMap: HAS_TRANSMISSIONMAP,
  12279. thicknessMap: HAS_THICKNESSMAP,
  12280. gradientMap: HAS_GRADIENTMAP,
  12281. opaque: material.transparent === false && material.blending === NormalBlending,
  12282. alphaMap: HAS_ALPHAMAP,
  12283. alphaTest: HAS_ALPHATEST,
  12284. alphaHash: HAS_ALPHAHASH,
  12285. combine: material.combine,
  12286. //
  12287. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12288. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12289. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12290. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12291. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12292. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12293. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12294. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12295. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12296. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12297. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12298. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12299. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12300. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12301. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12302. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12303. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12304. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12305. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12306. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12307. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12308. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12309. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12310. //
  12311. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12312. vertexColors: material.vertexColors,
  12313. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12314. vertexUv1s: HAS_ATTRIBUTE_UV1,
  12315. vertexUv2s: HAS_ATTRIBUTE_UV2,
  12316. vertexUv3s: HAS_ATTRIBUTE_UV3,
  12317. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12318. fog: !! fog,
  12319. useFog: material.fog === true,
  12320. fogExp2: ( fog && fog.isFogExp2 ),
  12321. flatShading: material.flatShading === true,
  12322. sizeAttenuation: material.sizeAttenuation === true,
  12323. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12324. skinning: object.isSkinnedMesh === true,
  12325. morphTargets: geometry.morphAttributes.position !== undefined,
  12326. morphNormals: geometry.morphAttributes.normal !== undefined,
  12327. morphColors: geometry.morphAttributes.color !== undefined,
  12328. morphTargetsCount: morphTargetsCount,
  12329. morphTextureStride: morphTextureStride,
  12330. numDirLights: lights.directional.length,
  12331. numPointLights: lights.point.length,
  12332. numSpotLights: lights.spot.length,
  12333. numSpotLightMaps: lights.spotLightMap.length,
  12334. numRectAreaLights: lights.rectArea.length,
  12335. numHemiLights: lights.hemi.length,
  12336. numDirLightShadows: lights.directionalShadowMap.length,
  12337. numPointLightShadows: lights.pointShadowMap.length,
  12338. numSpotLightShadows: lights.spotShadowMap.length,
  12339. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12340. numLightProbes: lights.numLightProbes,
  12341. numClippingPlanes: clipping.numPlanes,
  12342. numClipIntersection: clipping.numIntersection,
  12343. dithering: material.dithering,
  12344. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12345. shadowMapType: renderer.shadowMap.type,
  12346. toneMapping: toneMapping,
  12347. useLegacyLights: renderer._useLegacyLights,
  12348. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12349. premultipliedAlpha: material.premultipliedAlpha,
  12350. doubleSided: material.side === DoubleSide,
  12351. flipSided: material.side === BackSide,
  12352. useDepthPacking: material.depthPacking >= 0,
  12353. depthPacking: material.depthPacking || 0,
  12354. index0AttributeName: material.index0AttributeName,
  12355. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12356. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12357. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12358. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12359. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12360. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12361. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12362. customProgramCacheKey: material.customProgramCacheKey()
  12363. };
  12364. return parameters;
  12365. }
  12366. function getProgramCacheKey( parameters ) {
  12367. const array = [];
  12368. if ( parameters.shaderID ) {
  12369. array.push( parameters.shaderID );
  12370. } else {
  12371. array.push( parameters.customVertexShaderID );
  12372. array.push( parameters.customFragmentShaderID );
  12373. }
  12374. if ( parameters.defines !== undefined ) {
  12375. for ( const name in parameters.defines ) {
  12376. array.push( name );
  12377. array.push( parameters.defines[ name ] );
  12378. }
  12379. }
  12380. if ( parameters.isRawShaderMaterial === false ) {
  12381. getProgramCacheKeyParameters( array, parameters );
  12382. getProgramCacheKeyBooleans( array, parameters );
  12383. array.push( renderer.outputColorSpace );
  12384. }
  12385. array.push( parameters.customProgramCacheKey );
  12386. return array.join();
  12387. }
  12388. function getProgramCacheKeyParameters( array, parameters ) {
  12389. array.push( parameters.precision );
  12390. array.push( parameters.outputColorSpace );
  12391. array.push( parameters.envMapMode );
  12392. array.push( parameters.envMapCubeUVHeight );
  12393. array.push( parameters.mapUv );
  12394. array.push( parameters.alphaMapUv );
  12395. array.push( parameters.lightMapUv );
  12396. array.push( parameters.aoMapUv );
  12397. array.push( parameters.bumpMapUv );
  12398. array.push( parameters.normalMapUv );
  12399. array.push( parameters.displacementMapUv );
  12400. array.push( parameters.emissiveMapUv );
  12401. array.push( parameters.metalnessMapUv );
  12402. array.push( parameters.roughnessMapUv );
  12403. array.push( parameters.anisotropyMapUv );
  12404. array.push( parameters.clearcoatMapUv );
  12405. array.push( parameters.clearcoatNormalMapUv );
  12406. array.push( parameters.clearcoatRoughnessMapUv );
  12407. array.push( parameters.iridescenceMapUv );
  12408. array.push( parameters.iridescenceThicknessMapUv );
  12409. array.push( parameters.sheenColorMapUv );
  12410. array.push( parameters.sheenRoughnessMapUv );
  12411. array.push( parameters.specularMapUv );
  12412. array.push( parameters.specularColorMapUv );
  12413. array.push( parameters.specularIntensityMapUv );
  12414. array.push( parameters.transmissionMapUv );
  12415. array.push( parameters.thicknessMapUv );
  12416. array.push( parameters.combine );
  12417. array.push( parameters.fogExp2 );
  12418. array.push( parameters.sizeAttenuation );
  12419. array.push( parameters.morphTargetsCount );
  12420. array.push( parameters.morphAttributeCount );
  12421. array.push( parameters.numDirLights );
  12422. array.push( parameters.numPointLights );
  12423. array.push( parameters.numSpotLights );
  12424. array.push( parameters.numSpotLightMaps );
  12425. array.push( parameters.numHemiLights );
  12426. array.push( parameters.numRectAreaLights );
  12427. array.push( parameters.numDirLightShadows );
  12428. array.push( parameters.numPointLightShadows );
  12429. array.push( parameters.numSpotLightShadows );
  12430. array.push( parameters.numSpotLightShadowsWithMaps );
  12431. array.push( parameters.numLightProbes );
  12432. array.push( parameters.shadowMapType );
  12433. array.push( parameters.toneMapping );
  12434. array.push( parameters.numClippingPlanes );
  12435. array.push( parameters.numClipIntersection );
  12436. array.push( parameters.depthPacking );
  12437. }
  12438. function getProgramCacheKeyBooleans( array, parameters ) {
  12439. _programLayers.disableAll();
  12440. if ( parameters.isWebGL2 )
  12441. _programLayers.enable( 0 );
  12442. if ( parameters.supportsVertexTextures )
  12443. _programLayers.enable( 1 );
  12444. if ( parameters.instancing )
  12445. _programLayers.enable( 2 );
  12446. if ( parameters.instancingColor )
  12447. _programLayers.enable( 3 );
  12448. if ( parameters.matcap )
  12449. _programLayers.enable( 4 );
  12450. if ( parameters.envMap )
  12451. _programLayers.enable( 5 );
  12452. if ( parameters.normalMapObjectSpace )
  12453. _programLayers.enable( 6 );
  12454. if ( parameters.normalMapTangentSpace )
  12455. _programLayers.enable( 7 );
  12456. if ( parameters.clearcoat )
  12457. _programLayers.enable( 8 );
  12458. if ( parameters.iridescence )
  12459. _programLayers.enable( 9 );
  12460. if ( parameters.alphaTest )
  12461. _programLayers.enable( 10 );
  12462. if ( parameters.vertexColors )
  12463. _programLayers.enable( 11 );
  12464. if ( parameters.vertexAlphas )
  12465. _programLayers.enable( 12 );
  12466. if ( parameters.vertexUv1s )
  12467. _programLayers.enable( 13 );
  12468. if ( parameters.vertexUv2s )
  12469. _programLayers.enable( 14 );
  12470. if ( parameters.vertexUv3s )
  12471. _programLayers.enable( 15 );
  12472. if ( parameters.vertexTangents )
  12473. _programLayers.enable( 16 );
  12474. if ( parameters.anisotropy )
  12475. _programLayers.enable( 17 );
  12476. array.push( _programLayers.mask );
  12477. _programLayers.disableAll();
  12478. if ( parameters.fog )
  12479. _programLayers.enable( 0 );
  12480. if ( parameters.useFog )
  12481. _programLayers.enable( 1 );
  12482. if ( parameters.flatShading )
  12483. _programLayers.enable( 2 );
  12484. if ( parameters.logarithmicDepthBuffer )
  12485. _programLayers.enable( 3 );
  12486. if ( parameters.skinning )
  12487. _programLayers.enable( 4 );
  12488. if ( parameters.morphTargets )
  12489. _programLayers.enable( 5 );
  12490. if ( parameters.morphNormals )
  12491. _programLayers.enable( 6 );
  12492. if ( parameters.morphColors )
  12493. _programLayers.enable( 7 );
  12494. if ( parameters.premultipliedAlpha )
  12495. _programLayers.enable( 8 );
  12496. if ( parameters.shadowMapEnabled )
  12497. _programLayers.enable( 9 );
  12498. if ( parameters.useLegacyLights )
  12499. _programLayers.enable( 10 );
  12500. if ( parameters.doubleSided )
  12501. _programLayers.enable( 11 );
  12502. if ( parameters.flipSided )
  12503. _programLayers.enable( 12 );
  12504. if ( parameters.useDepthPacking )
  12505. _programLayers.enable( 13 );
  12506. if ( parameters.dithering )
  12507. _programLayers.enable( 14 );
  12508. if ( parameters.transmission )
  12509. _programLayers.enable( 15 );
  12510. if ( parameters.sheen )
  12511. _programLayers.enable( 16 );
  12512. if ( parameters.opaque )
  12513. _programLayers.enable( 17 );
  12514. if ( parameters.pointsUvs )
  12515. _programLayers.enable( 18 );
  12516. if ( parameters.decodeVideoTexture )
  12517. _programLayers.enable( 19 );
  12518. array.push( _programLayers.mask );
  12519. }
  12520. function getUniforms( material ) {
  12521. const shaderID = shaderIDs[ material.type ];
  12522. let uniforms;
  12523. if ( shaderID ) {
  12524. const shader = ShaderLib[ shaderID ];
  12525. uniforms = UniformsUtils.clone( shader.uniforms );
  12526. } else {
  12527. uniforms = material.uniforms;
  12528. }
  12529. return uniforms;
  12530. }
  12531. function acquireProgram( parameters, cacheKey ) {
  12532. let program;
  12533. // Check if code has been already compiled
  12534. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12535. const preexistingProgram = programs[ p ];
  12536. if ( preexistingProgram.cacheKey === cacheKey ) {
  12537. program = preexistingProgram;
  12538. ++ program.usedTimes;
  12539. break;
  12540. }
  12541. }
  12542. if ( program === undefined ) {
  12543. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12544. programs.push( program );
  12545. }
  12546. return program;
  12547. }
  12548. function releaseProgram( program ) {
  12549. if ( -- program.usedTimes === 0 ) {
  12550. // Remove from unordered set
  12551. const i = programs.indexOf( program );
  12552. programs[ i ] = programs[ programs.length - 1 ];
  12553. programs.pop();
  12554. // Free WebGL resources
  12555. program.destroy();
  12556. }
  12557. }
  12558. function releaseShaderCache( material ) {
  12559. _customShaders.remove( material );
  12560. }
  12561. function dispose() {
  12562. _customShaders.dispose();
  12563. }
  12564. return {
  12565. getParameters: getParameters,
  12566. getProgramCacheKey: getProgramCacheKey,
  12567. getUniforms: getUniforms,
  12568. acquireProgram: acquireProgram,
  12569. releaseProgram: releaseProgram,
  12570. releaseShaderCache: releaseShaderCache,
  12571. // Exposed for resource monitoring & error feedback via renderer.info:
  12572. programs: programs,
  12573. dispose: dispose
  12574. };
  12575. }
  12576. function WebGLProperties() {
  12577. let properties = new WeakMap();
  12578. function get( object ) {
  12579. let map = properties.get( object );
  12580. if ( map === undefined ) {
  12581. map = {};
  12582. properties.set( object, map );
  12583. }
  12584. return map;
  12585. }
  12586. function remove( object ) {
  12587. properties.delete( object );
  12588. }
  12589. function update( object, key, value ) {
  12590. properties.get( object )[ key ] = value;
  12591. }
  12592. function dispose() {
  12593. properties = new WeakMap();
  12594. }
  12595. return {
  12596. get: get,
  12597. remove: remove,
  12598. update: update,
  12599. dispose: dispose
  12600. };
  12601. }
  12602. function painterSortStable( a, b ) {
  12603. if ( a.groupOrder !== b.groupOrder ) {
  12604. return a.groupOrder - b.groupOrder;
  12605. } else if ( a.renderOrder !== b.renderOrder ) {
  12606. return a.renderOrder - b.renderOrder;
  12607. } else if ( a.material.id !== b.material.id ) {
  12608. return a.material.id - b.material.id;
  12609. } else if ( a.z !== b.z ) {
  12610. return a.z - b.z;
  12611. } else {
  12612. return a.id - b.id;
  12613. }
  12614. }
  12615. function reversePainterSortStable( a, b ) {
  12616. if ( a.groupOrder !== b.groupOrder ) {
  12617. return a.groupOrder - b.groupOrder;
  12618. } else if ( a.renderOrder !== b.renderOrder ) {
  12619. return a.renderOrder - b.renderOrder;
  12620. } else if ( a.z !== b.z ) {
  12621. return b.z - a.z;
  12622. } else {
  12623. return a.id - b.id;
  12624. }
  12625. }
  12626. function WebGLRenderList() {
  12627. const renderItems = [];
  12628. let renderItemsIndex = 0;
  12629. const opaque = [];
  12630. const transmissive = [];
  12631. const transparent = [];
  12632. function init() {
  12633. renderItemsIndex = 0;
  12634. opaque.length = 0;
  12635. transmissive.length = 0;
  12636. transparent.length = 0;
  12637. }
  12638. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12639. let renderItem = renderItems[ renderItemsIndex ];
  12640. if ( renderItem === undefined ) {
  12641. renderItem = {
  12642. id: object.id,
  12643. object: object,
  12644. geometry: geometry,
  12645. material: material,
  12646. groupOrder: groupOrder,
  12647. renderOrder: object.renderOrder,
  12648. z: z,
  12649. group: group
  12650. };
  12651. renderItems[ renderItemsIndex ] = renderItem;
  12652. } else {
  12653. renderItem.id = object.id;
  12654. renderItem.object = object;
  12655. renderItem.geometry = geometry;
  12656. renderItem.material = material;
  12657. renderItem.groupOrder = groupOrder;
  12658. renderItem.renderOrder = object.renderOrder;
  12659. renderItem.z = z;
  12660. renderItem.group = group;
  12661. }
  12662. renderItemsIndex ++;
  12663. return renderItem;
  12664. }
  12665. function push( object, geometry, material, groupOrder, z, group ) {
  12666. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12667. if ( material.transmission > 0.0 ) {
  12668. transmissive.push( renderItem );
  12669. } else if ( material.transparent === true ) {
  12670. transparent.push( renderItem );
  12671. } else {
  12672. opaque.push( renderItem );
  12673. }
  12674. }
  12675. function unshift( object, geometry, material, groupOrder, z, group ) {
  12676. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12677. if ( material.transmission > 0.0 ) {
  12678. transmissive.unshift( renderItem );
  12679. } else if ( material.transparent === true ) {
  12680. transparent.unshift( renderItem );
  12681. } else {
  12682. opaque.unshift( renderItem );
  12683. }
  12684. }
  12685. function sort( customOpaqueSort, customTransparentSort ) {
  12686. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12687. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12688. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12689. }
  12690. function finish() {
  12691. // Clear references from inactive renderItems in the list
  12692. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12693. const renderItem = renderItems[ i ];
  12694. if ( renderItem.id === null ) break;
  12695. renderItem.id = null;
  12696. renderItem.object = null;
  12697. renderItem.geometry = null;
  12698. renderItem.material = null;
  12699. renderItem.group = null;
  12700. }
  12701. }
  12702. return {
  12703. opaque: opaque,
  12704. transmissive: transmissive,
  12705. transparent: transparent,
  12706. init: init,
  12707. push: push,
  12708. unshift: unshift,
  12709. finish: finish,
  12710. sort: sort
  12711. };
  12712. }
  12713. function WebGLRenderLists() {
  12714. let lists = new WeakMap();
  12715. function get( scene, renderCallDepth ) {
  12716. const listArray = lists.get( scene );
  12717. let list;
  12718. if ( listArray === undefined ) {
  12719. list = new WebGLRenderList();
  12720. lists.set( scene, [ list ] );
  12721. } else {
  12722. if ( renderCallDepth >= listArray.length ) {
  12723. list = new WebGLRenderList();
  12724. listArray.push( list );
  12725. } else {
  12726. list = listArray[ renderCallDepth ];
  12727. }
  12728. }
  12729. return list;
  12730. }
  12731. function dispose() {
  12732. lists = new WeakMap();
  12733. }
  12734. return {
  12735. get: get,
  12736. dispose: dispose
  12737. };
  12738. }
  12739. function UniformsCache() {
  12740. const lights = {};
  12741. return {
  12742. get: function ( light ) {
  12743. if ( lights[ light.id ] !== undefined ) {
  12744. return lights[ light.id ];
  12745. }
  12746. let uniforms;
  12747. switch ( light.type ) {
  12748. case 'DirectionalLight':
  12749. uniforms = {
  12750. direction: new Vector3(),
  12751. color: new Color()
  12752. };
  12753. break;
  12754. case 'SpotLight':
  12755. uniforms = {
  12756. position: new Vector3(),
  12757. direction: new Vector3(),
  12758. color: new Color(),
  12759. distance: 0,
  12760. coneCos: 0,
  12761. penumbraCos: 0,
  12762. decay: 0
  12763. };
  12764. break;
  12765. case 'PointLight':
  12766. uniforms = {
  12767. position: new Vector3(),
  12768. color: new Color(),
  12769. distance: 0,
  12770. decay: 0
  12771. };
  12772. break;
  12773. case 'HemisphereLight':
  12774. uniforms = {
  12775. direction: new Vector3(),
  12776. skyColor: new Color(),
  12777. groundColor: new Color()
  12778. };
  12779. break;
  12780. case 'RectAreaLight':
  12781. uniforms = {
  12782. color: new Color(),
  12783. position: new Vector3(),
  12784. halfWidth: new Vector3(),
  12785. halfHeight: new Vector3()
  12786. };
  12787. break;
  12788. }
  12789. lights[ light.id ] = uniforms;
  12790. return uniforms;
  12791. }
  12792. };
  12793. }
  12794. function ShadowUniformsCache() {
  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. shadowBias: 0,
  12806. shadowNormalBias: 0,
  12807. shadowRadius: 1,
  12808. shadowMapSize: new Vector2()
  12809. };
  12810. break;
  12811. case 'SpotLight':
  12812. uniforms = {
  12813. shadowBias: 0,
  12814. shadowNormalBias: 0,
  12815. shadowRadius: 1,
  12816. shadowMapSize: new Vector2()
  12817. };
  12818. break;
  12819. case 'PointLight':
  12820. uniforms = {
  12821. shadowBias: 0,
  12822. shadowNormalBias: 0,
  12823. shadowRadius: 1,
  12824. shadowMapSize: new Vector2(),
  12825. shadowCameraNear: 1,
  12826. shadowCameraFar: 1000
  12827. };
  12828. break;
  12829. // TODO (abelnation): set RectAreaLight shadow uniforms
  12830. }
  12831. lights[ light.id ] = uniforms;
  12832. return uniforms;
  12833. }
  12834. };
  12835. }
  12836. let nextVersion = 0;
  12837. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12838. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12839. }
  12840. function WebGLLights( extensions, capabilities ) {
  12841. const cache = new UniformsCache();
  12842. const shadowCache = ShadowUniformsCache();
  12843. const state = {
  12844. version: 0,
  12845. hash: {
  12846. directionalLength: - 1,
  12847. pointLength: - 1,
  12848. spotLength: - 1,
  12849. rectAreaLength: - 1,
  12850. hemiLength: - 1,
  12851. numDirectionalShadows: - 1,
  12852. numPointShadows: - 1,
  12853. numSpotShadows: - 1,
  12854. numSpotMaps: - 1,
  12855. numLightProbes: - 1
  12856. },
  12857. ambient: [ 0, 0, 0 ],
  12858. probe: [],
  12859. directional: [],
  12860. directionalShadow: [],
  12861. directionalShadowMap: [],
  12862. directionalShadowMatrix: [],
  12863. spot: [],
  12864. spotLightMap: [],
  12865. spotShadow: [],
  12866. spotShadowMap: [],
  12867. spotLightMatrix: [],
  12868. rectArea: [],
  12869. rectAreaLTC1: null,
  12870. rectAreaLTC2: null,
  12871. point: [],
  12872. pointShadow: [],
  12873. pointShadowMap: [],
  12874. pointShadowMatrix: [],
  12875. hemi: [],
  12876. numSpotLightShadowsWithMaps: 0,
  12877. numLightProbes: 0
  12878. };
  12879. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12880. const vector3 = new Vector3();
  12881. const matrix4 = new Matrix4();
  12882. const matrix42 = new Matrix4();
  12883. function setup( lights, useLegacyLights ) {
  12884. let r = 0, g = 0, b = 0;
  12885. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12886. let directionalLength = 0;
  12887. let pointLength = 0;
  12888. let spotLength = 0;
  12889. let rectAreaLength = 0;
  12890. let hemiLength = 0;
  12891. let numDirectionalShadows = 0;
  12892. let numPointShadows = 0;
  12893. let numSpotShadows = 0;
  12894. let numSpotMaps = 0;
  12895. let numSpotShadowsWithMaps = 0;
  12896. let numLightProbes = 0;
  12897. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12898. lights.sort( shadowCastingAndTexturingLightsFirst );
  12899. // artist-friendly light intensity scaling factor
  12900. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12901. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12902. const light = lights[ i ];
  12903. const color = light.color;
  12904. const intensity = light.intensity;
  12905. const distance = light.distance;
  12906. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12907. if ( light.isAmbientLight ) {
  12908. r += color.r * intensity * scaleFactor;
  12909. g += color.g * intensity * scaleFactor;
  12910. b += color.b * intensity * scaleFactor;
  12911. } else if ( light.isLightProbe ) {
  12912. for ( let j = 0; j < 9; j ++ ) {
  12913. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12914. }
  12915. numLightProbes ++;
  12916. } else if ( light.isDirectionalLight ) {
  12917. const uniforms = cache.get( light );
  12918. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12919. if ( light.castShadow ) {
  12920. const shadow = light.shadow;
  12921. const shadowUniforms = shadowCache.get( light );
  12922. shadowUniforms.shadowBias = shadow.bias;
  12923. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12924. shadowUniforms.shadowRadius = shadow.radius;
  12925. shadowUniforms.shadowMapSize = shadow.mapSize;
  12926. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12927. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12928. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12929. numDirectionalShadows ++;
  12930. }
  12931. state.directional[ directionalLength ] = uniforms;
  12932. directionalLength ++;
  12933. } else if ( light.isSpotLight ) {
  12934. const uniforms = cache.get( light );
  12935. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12936. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12937. uniforms.distance = distance;
  12938. uniforms.coneCos = Math.cos( light.angle );
  12939. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12940. uniforms.decay = light.decay;
  12941. state.spot[ spotLength ] = uniforms;
  12942. const shadow = light.shadow;
  12943. if ( light.map ) {
  12944. state.spotLightMap[ numSpotMaps ] = light.map;
  12945. numSpotMaps ++;
  12946. // make sure the lightMatrix is up to date
  12947. // TODO : do it if required only
  12948. shadow.updateMatrices( light );
  12949. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12950. }
  12951. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12952. if ( light.castShadow ) {
  12953. const shadowUniforms = shadowCache.get( light );
  12954. shadowUniforms.shadowBias = shadow.bias;
  12955. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12956. shadowUniforms.shadowRadius = shadow.radius;
  12957. shadowUniforms.shadowMapSize = shadow.mapSize;
  12958. state.spotShadow[ spotLength ] = shadowUniforms;
  12959. state.spotShadowMap[ spotLength ] = shadowMap;
  12960. numSpotShadows ++;
  12961. }
  12962. spotLength ++;
  12963. } else if ( light.isRectAreaLight ) {
  12964. const uniforms = cache.get( light );
  12965. uniforms.color.copy( color ).multiplyScalar( intensity );
  12966. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12967. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12968. state.rectArea[ rectAreaLength ] = uniforms;
  12969. rectAreaLength ++;
  12970. } else if ( light.isPointLight ) {
  12971. const uniforms = cache.get( light );
  12972. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12973. uniforms.distance = light.distance;
  12974. uniforms.decay = light.decay;
  12975. if ( light.castShadow ) {
  12976. const shadow = light.shadow;
  12977. const shadowUniforms = shadowCache.get( light );
  12978. shadowUniforms.shadowBias = shadow.bias;
  12979. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12980. shadowUniforms.shadowRadius = shadow.radius;
  12981. shadowUniforms.shadowMapSize = shadow.mapSize;
  12982. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12983. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12984. state.pointShadow[ pointLength ] = shadowUniforms;
  12985. state.pointShadowMap[ pointLength ] = shadowMap;
  12986. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12987. numPointShadows ++;
  12988. }
  12989. state.point[ pointLength ] = uniforms;
  12990. pointLength ++;
  12991. } else if ( light.isHemisphereLight ) {
  12992. const uniforms = cache.get( light );
  12993. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12994. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12995. state.hemi[ hemiLength ] = uniforms;
  12996. hemiLength ++;
  12997. }
  12998. }
  12999. if ( rectAreaLength > 0 ) {
  13000. if ( capabilities.isWebGL2 ) {
  13001. // WebGL 2
  13002. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13003. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13004. } else {
  13005. // WebGL 1
  13006. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13007. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13008. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13009. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  13010. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13011. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13012. } else {
  13013. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  13014. }
  13015. }
  13016. }
  13017. state.ambient[ 0 ] = r;
  13018. state.ambient[ 1 ] = g;
  13019. state.ambient[ 2 ] = b;
  13020. const hash = state.hash;
  13021. if ( hash.directionalLength !== directionalLength ||
  13022. hash.pointLength !== pointLength ||
  13023. hash.spotLength !== spotLength ||
  13024. hash.rectAreaLength !== rectAreaLength ||
  13025. hash.hemiLength !== hemiLength ||
  13026. hash.numDirectionalShadows !== numDirectionalShadows ||
  13027. hash.numPointShadows !== numPointShadows ||
  13028. hash.numSpotShadows !== numSpotShadows ||
  13029. hash.numSpotMaps !== numSpotMaps ||
  13030. hash.numLightProbes !== numLightProbes ) {
  13031. state.directional.length = directionalLength;
  13032. state.spot.length = spotLength;
  13033. state.rectArea.length = rectAreaLength;
  13034. state.point.length = pointLength;
  13035. state.hemi.length = hemiLength;
  13036. state.directionalShadow.length = numDirectionalShadows;
  13037. state.directionalShadowMap.length = numDirectionalShadows;
  13038. state.pointShadow.length = numPointShadows;
  13039. state.pointShadowMap.length = numPointShadows;
  13040. state.spotShadow.length = numSpotShadows;
  13041. state.spotShadowMap.length = numSpotShadows;
  13042. state.directionalShadowMatrix.length = numDirectionalShadows;
  13043. state.pointShadowMatrix.length = numPointShadows;
  13044. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13045. state.spotLightMap.length = numSpotMaps;
  13046. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13047. state.numLightProbes = numLightProbes;
  13048. hash.directionalLength = directionalLength;
  13049. hash.pointLength = pointLength;
  13050. hash.spotLength = spotLength;
  13051. hash.rectAreaLength = rectAreaLength;
  13052. hash.hemiLength = hemiLength;
  13053. hash.numDirectionalShadows = numDirectionalShadows;
  13054. hash.numPointShadows = numPointShadows;
  13055. hash.numSpotShadows = numSpotShadows;
  13056. hash.numSpotMaps = numSpotMaps;
  13057. hash.numLightProbes = numLightProbes;
  13058. state.version = nextVersion ++;
  13059. }
  13060. }
  13061. function setupView( lights, camera ) {
  13062. let directionalLength = 0;
  13063. let pointLength = 0;
  13064. let spotLength = 0;
  13065. let rectAreaLength = 0;
  13066. let hemiLength = 0;
  13067. const viewMatrix = camera.matrixWorldInverse;
  13068. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13069. const light = lights[ i ];
  13070. if ( light.isDirectionalLight ) {
  13071. const uniforms = state.directional[ directionalLength ];
  13072. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13073. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13074. uniforms.direction.sub( vector3 );
  13075. uniforms.direction.transformDirection( viewMatrix );
  13076. directionalLength ++;
  13077. } else if ( light.isSpotLight ) {
  13078. const uniforms = state.spot[ spotLength ];
  13079. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13080. uniforms.position.applyMatrix4( viewMatrix );
  13081. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13082. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13083. uniforms.direction.sub( vector3 );
  13084. uniforms.direction.transformDirection( viewMatrix );
  13085. spotLength ++;
  13086. } else if ( light.isRectAreaLight ) {
  13087. const uniforms = state.rectArea[ rectAreaLength ];
  13088. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13089. uniforms.position.applyMatrix4( viewMatrix );
  13090. // extract local rotation of light to derive width/height half vectors
  13091. matrix42.identity();
  13092. matrix4.copy( light.matrixWorld );
  13093. matrix4.premultiply( viewMatrix );
  13094. matrix42.extractRotation( matrix4 );
  13095. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13096. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13097. uniforms.halfWidth.applyMatrix4( matrix42 );
  13098. uniforms.halfHeight.applyMatrix4( matrix42 );
  13099. rectAreaLength ++;
  13100. } else if ( light.isPointLight ) {
  13101. const uniforms = state.point[ pointLength ];
  13102. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13103. uniforms.position.applyMatrix4( viewMatrix );
  13104. pointLength ++;
  13105. } else if ( light.isHemisphereLight ) {
  13106. const uniforms = state.hemi[ hemiLength ];
  13107. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13108. uniforms.direction.transformDirection( viewMatrix );
  13109. hemiLength ++;
  13110. }
  13111. }
  13112. }
  13113. return {
  13114. setup: setup,
  13115. setupView: setupView,
  13116. state: state
  13117. };
  13118. }
  13119. function WebGLRenderState( extensions, capabilities ) {
  13120. const lights = new WebGLLights( extensions, capabilities );
  13121. const lightsArray = [];
  13122. const shadowsArray = [];
  13123. function init() {
  13124. lightsArray.length = 0;
  13125. shadowsArray.length = 0;
  13126. }
  13127. function pushLight( light ) {
  13128. lightsArray.push( light );
  13129. }
  13130. function pushShadow( shadowLight ) {
  13131. shadowsArray.push( shadowLight );
  13132. }
  13133. function setupLights( useLegacyLights ) {
  13134. lights.setup( lightsArray, useLegacyLights );
  13135. }
  13136. function setupLightsView( camera ) {
  13137. lights.setupView( lightsArray, camera );
  13138. }
  13139. const state = {
  13140. lightsArray: lightsArray,
  13141. shadowsArray: shadowsArray,
  13142. lights: lights
  13143. };
  13144. return {
  13145. init: init,
  13146. state: state,
  13147. setupLights: setupLights,
  13148. setupLightsView: setupLightsView,
  13149. pushLight: pushLight,
  13150. pushShadow: pushShadow
  13151. };
  13152. }
  13153. function WebGLRenderStates( extensions, capabilities ) {
  13154. let renderStates = new WeakMap();
  13155. function get( scene, renderCallDepth = 0 ) {
  13156. const renderStateArray = renderStates.get( scene );
  13157. let renderState;
  13158. if ( renderStateArray === undefined ) {
  13159. renderState = new WebGLRenderState( extensions, capabilities );
  13160. renderStates.set( scene, [ renderState ] );
  13161. } else {
  13162. if ( renderCallDepth >= renderStateArray.length ) {
  13163. renderState = new WebGLRenderState( extensions, capabilities );
  13164. renderStateArray.push( renderState );
  13165. } else {
  13166. renderState = renderStateArray[ renderCallDepth ];
  13167. }
  13168. }
  13169. return renderState;
  13170. }
  13171. function dispose() {
  13172. renderStates = new WeakMap();
  13173. }
  13174. return {
  13175. get: get,
  13176. dispose: dispose
  13177. };
  13178. }
  13179. class MeshDepthMaterial extends Material {
  13180. constructor( parameters ) {
  13181. super();
  13182. this.isMeshDepthMaterial = true;
  13183. this.type = 'MeshDepthMaterial';
  13184. this.depthPacking = BasicDepthPacking;
  13185. this.map = null;
  13186. this.alphaMap = null;
  13187. this.displacementMap = null;
  13188. this.displacementScale = 1;
  13189. this.displacementBias = 0;
  13190. this.wireframe = false;
  13191. this.wireframeLinewidth = 1;
  13192. this.setValues( parameters );
  13193. }
  13194. copy( source ) {
  13195. super.copy( source );
  13196. this.depthPacking = source.depthPacking;
  13197. this.map = source.map;
  13198. this.alphaMap = source.alphaMap;
  13199. this.displacementMap = source.displacementMap;
  13200. this.displacementScale = source.displacementScale;
  13201. this.displacementBias = source.displacementBias;
  13202. this.wireframe = source.wireframe;
  13203. this.wireframeLinewidth = source.wireframeLinewidth;
  13204. return this;
  13205. }
  13206. }
  13207. class MeshDistanceMaterial extends Material {
  13208. constructor( parameters ) {
  13209. super();
  13210. this.isMeshDistanceMaterial = true;
  13211. this.type = 'MeshDistanceMaterial';
  13212. this.map = null;
  13213. this.alphaMap = null;
  13214. this.displacementMap = null;
  13215. this.displacementScale = 1;
  13216. this.displacementBias = 0;
  13217. this.setValues( parameters );
  13218. }
  13219. copy( source ) {
  13220. super.copy( source );
  13221. this.map = source.map;
  13222. this.alphaMap = source.alphaMap;
  13223. this.displacementMap = source.displacementMap;
  13224. this.displacementScale = source.displacementScale;
  13225. this.displacementBias = source.displacementBias;
  13226. return this;
  13227. }
  13228. }
  13229. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13230. 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}";
  13231. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13232. let _frustum = new Frustum();
  13233. const _shadowMapSize = new Vector2(),
  13234. _viewportSize = new Vector2(),
  13235. _viewport = new Vector4(),
  13236. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13237. _distanceMaterial = new MeshDistanceMaterial(),
  13238. _materialCache = {},
  13239. _maxTextureSize = _capabilities.maxTextureSize;
  13240. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13241. const shadowMaterialVertical = new ShaderMaterial( {
  13242. defines: {
  13243. VSM_SAMPLES: 8
  13244. },
  13245. uniforms: {
  13246. shadow_pass: { value: null },
  13247. resolution: { value: new Vector2() },
  13248. radius: { value: 4.0 }
  13249. },
  13250. vertexShader: vertex,
  13251. fragmentShader: fragment
  13252. } );
  13253. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13254. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13255. const fullScreenTri = new BufferGeometry();
  13256. fullScreenTri.setAttribute(
  13257. 'position',
  13258. new BufferAttribute(
  13259. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13260. 3
  13261. )
  13262. );
  13263. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13264. const scope = this;
  13265. this.enabled = false;
  13266. this.autoUpdate = true;
  13267. this.needsUpdate = false;
  13268. this.type = PCFShadowMap;
  13269. let _previousType = this.type;
  13270. this.render = function ( lights, scene, camera ) {
  13271. if ( scope.enabled === false ) return;
  13272. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13273. if ( lights.length === 0 ) return;
  13274. const currentRenderTarget = _renderer.getRenderTarget();
  13275. const activeCubeFace = _renderer.getActiveCubeFace();
  13276. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13277. const _state = _renderer.state;
  13278. // Set GL state for depth map.
  13279. _state.setBlending( NoBlending );
  13280. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13281. _state.buffers.depth.setTest( true );
  13282. _state.setScissorTest( false );
  13283. // check for shadow map type changes
  13284. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13285. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13286. // render depth map
  13287. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13288. const light = lights[ i ];
  13289. const shadow = light.shadow;
  13290. if ( shadow === undefined ) {
  13291. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13292. continue;
  13293. }
  13294. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13295. _shadowMapSize.copy( shadow.mapSize );
  13296. const shadowFrameExtents = shadow.getFrameExtents();
  13297. _shadowMapSize.multiply( shadowFrameExtents );
  13298. _viewportSize.copy( shadow.mapSize );
  13299. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13300. if ( _shadowMapSize.x > _maxTextureSize ) {
  13301. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13302. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13303. shadow.mapSize.x = _viewportSize.x;
  13304. }
  13305. if ( _shadowMapSize.y > _maxTextureSize ) {
  13306. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13307. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13308. shadow.mapSize.y = _viewportSize.y;
  13309. }
  13310. }
  13311. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13312. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13313. if ( shadow.map !== null ) {
  13314. shadow.map.dispose();
  13315. }
  13316. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13317. shadow.map.texture.name = light.name + '.shadowMap';
  13318. shadow.camera.updateProjectionMatrix();
  13319. }
  13320. _renderer.setRenderTarget( shadow.map );
  13321. _renderer.clear();
  13322. const viewportCount = shadow.getViewportCount();
  13323. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13324. const viewport = shadow.getViewport( vp );
  13325. _viewport.set(
  13326. _viewportSize.x * viewport.x,
  13327. _viewportSize.y * viewport.y,
  13328. _viewportSize.x * viewport.z,
  13329. _viewportSize.y * viewport.w
  13330. );
  13331. _state.viewport( _viewport );
  13332. shadow.updateMatrices( light, vp );
  13333. _frustum = shadow.getFrustum();
  13334. renderObject( scene, camera, shadow.camera, light, this.type );
  13335. }
  13336. // do blur pass for VSM
  13337. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13338. VSMPass( shadow, camera );
  13339. }
  13340. shadow.needsUpdate = false;
  13341. }
  13342. _previousType = this.type;
  13343. scope.needsUpdate = false;
  13344. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13345. };
  13346. function VSMPass( shadow, camera ) {
  13347. const geometry = _objects.update( fullScreenMesh );
  13348. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13349. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13350. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13351. shadowMaterialVertical.needsUpdate = true;
  13352. shadowMaterialHorizontal.needsUpdate = true;
  13353. }
  13354. if ( shadow.mapPass === null ) {
  13355. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13356. }
  13357. // vertical pass
  13358. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13359. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13360. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13361. _renderer.setRenderTarget( shadow.mapPass );
  13362. _renderer.clear();
  13363. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13364. // horizontal pass
  13365. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13366. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13367. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13368. _renderer.setRenderTarget( shadow.map );
  13369. _renderer.clear();
  13370. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13371. }
  13372. function getDepthMaterial( object, material, light, type ) {
  13373. let result = null;
  13374. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13375. if ( customMaterial !== undefined ) {
  13376. result = customMaterial;
  13377. } else {
  13378. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13379. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13380. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13381. ( material.alphaMap && material.alphaTest > 0 ) ||
  13382. ( material.map && material.alphaTest > 0 ) ) {
  13383. // in this case we need a unique material instance reflecting the
  13384. // appropriate state
  13385. const keyA = result.uuid, keyB = material.uuid;
  13386. let materialsForVariant = _materialCache[ keyA ];
  13387. if ( materialsForVariant === undefined ) {
  13388. materialsForVariant = {};
  13389. _materialCache[ keyA ] = materialsForVariant;
  13390. }
  13391. let cachedMaterial = materialsForVariant[ keyB ];
  13392. if ( cachedMaterial === undefined ) {
  13393. cachedMaterial = result.clone();
  13394. materialsForVariant[ keyB ] = cachedMaterial;
  13395. }
  13396. result = cachedMaterial;
  13397. }
  13398. }
  13399. result.visible = material.visible;
  13400. result.wireframe = material.wireframe;
  13401. if ( type === VSMShadowMap ) {
  13402. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13403. } else {
  13404. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13405. }
  13406. result.alphaMap = material.alphaMap;
  13407. result.alphaTest = material.alphaTest;
  13408. result.map = material.map;
  13409. result.clipShadows = material.clipShadows;
  13410. result.clippingPlanes = material.clippingPlanes;
  13411. result.clipIntersection = material.clipIntersection;
  13412. result.displacementMap = material.displacementMap;
  13413. result.displacementScale = material.displacementScale;
  13414. result.displacementBias = material.displacementBias;
  13415. result.wireframeLinewidth = material.wireframeLinewidth;
  13416. result.linewidth = material.linewidth;
  13417. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13418. const materialProperties = _renderer.properties.get( result );
  13419. materialProperties.light = light;
  13420. }
  13421. return result;
  13422. }
  13423. function renderObject( object, camera, shadowCamera, light, type ) {
  13424. if ( object.visible === false ) return;
  13425. const visible = object.layers.test( camera.layers );
  13426. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13427. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13428. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13429. const geometry = _objects.update( object );
  13430. const material = object.material;
  13431. if ( Array.isArray( material ) ) {
  13432. const groups = geometry.groups;
  13433. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13434. const group = groups[ k ];
  13435. const groupMaterial = material[ group.materialIndex ];
  13436. if ( groupMaterial && groupMaterial.visible ) {
  13437. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13438. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13439. }
  13440. }
  13441. } else if ( material.visible ) {
  13442. const depthMaterial = getDepthMaterial( object, material, light, type );
  13443. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13444. }
  13445. }
  13446. }
  13447. const children = object.children;
  13448. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13449. renderObject( children[ i ], camera, shadowCamera, light, type );
  13450. }
  13451. }
  13452. }
  13453. function WebGLState( gl, extensions, capabilities ) {
  13454. const isWebGL2 = capabilities.isWebGL2;
  13455. function ColorBuffer() {
  13456. let locked = false;
  13457. const color = new Vector4();
  13458. let currentColorMask = null;
  13459. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13460. return {
  13461. setMask: function ( colorMask ) {
  13462. if ( currentColorMask !== colorMask && ! locked ) {
  13463. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13464. currentColorMask = colorMask;
  13465. }
  13466. },
  13467. setLocked: function ( lock ) {
  13468. locked = lock;
  13469. },
  13470. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13471. if ( premultipliedAlpha === true ) {
  13472. r *= a; g *= a; b *= a;
  13473. }
  13474. color.set( r, g, b, a );
  13475. if ( currentColorClear.equals( color ) === false ) {
  13476. gl.clearColor( r, g, b, a );
  13477. currentColorClear.copy( color );
  13478. }
  13479. },
  13480. reset: function () {
  13481. locked = false;
  13482. currentColorMask = null;
  13483. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13484. }
  13485. };
  13486. }
  13487. function DepthBuffer() {
  13488. let locked = false;
  13489. let currentDepthMask = null;
  13490. let currentDepthFunc = null;
  13491. let currentDepthClear = null;
  13492. return {
  13493. setTest: function ( depthTest ) {
  13494. if ( depthTest ) {
  13495. enable( gl.DEPTH_TEST );
  13496. } else {
  13497. disable( gl.DEPTH_TEST );
  13498. }
  13499. },
  13500. setMask: function ( depthMask ) {
  13501. if ( currentDepthMask !== depthMask && ! locked ) {
  13502. gl.depthMask( depthMask );
  13503. currentDepthMask = depthMask;
  13504. }
  13505. },
  13506. setFunc: function ( depthFunc ) {
  13507. if ( currentDepthFunc !== depthFunc ) {
  13508. switch ( depthFunc ) {
  13509. case NeverDepth:
  13510. gl.depthFunc( gl.NEVER );
  13511. break;
  13512. case AlwaysDepth:
  13513. gl.depthFunc( gl.ALWAYS );
  13514. break;
  13515. case LessDepth:
  13516. gl.depthFunc( gl.LESS );
  13517. break;
  13518. case LessEqualDepth:
  13519. gl.depthFunc( gl.LEQUAL );
  13520. break;
  13521. case EqualDepth:
  13522. gl.depthFunc( gl.EQUAL );
  13523. break;
  13524. case GreaterEqualDepth:
  13525. gl.depthFunc( gl.GEQUAL );
  13526. break;
  13527. case GreaterDepth:
  13528. gl.depthFunc( gl.GREATER );
  13529. break;
  13530. case NotEqualDepth:
  13531. gl.depthFunc( gl.NOTEQUAL );
  13532. break;
  13533. default:
  13534. gl.depthFunc( gl.LEQUAL );
  13535. }
  13536. currentDepthFunc = depthFunc;
  13537. }
  13538. },
  13539. setLocked: function ( lock ) {
  13540. locked = lock;
  13541. },
  13542. setClear: function ( depth ) {
  13543. if ( currentDepthClear !== depth ) {
  13544. gl.clearDepth( depth );
  13545. currentDepthClear = depth;
  13546. }
  13547. },
  13548. reset: function () {
  13549. locked = false;
  13550. currentDepthMask = null;
  13551. currentDepthFunc = null;
  13552. currentDepthClear = null;
  13553. }
  13554. };
  13555. }
  13556. function StencilBuffer() {
  13557. let locked = false;
  13558. let currentStencilMask = null;
  13559. let currentStencilFunc = null;
  13560. let currentStencilRef = null;
  13561. let currentStencilFuncMask = null;
  13562. let currentStencilFail = null;
  13563. let currentStencilZFail = null;
  13564. let currentStencilZPass = null;
  13565. let currentStencilClear = null;
  13566. return {
  13567. setTest: function ( stencilTest ) {
  13568. if ( ! locked ) {
  13569. if ( stencilTest ) {
  13570. enable( gl.STENCIL_TEST );
  13571. } else {
  13572. disable( gl.STENCIL_TEST );
  13573. }
  13574. }
  13575. },
  13576. setMask: function ( stencilMask ) {
  13577. if ( currentStencilMask !== stencilMask && ! locked ) {
  13578. gl.stencilMask( stencilMask );
  13579. currentStencilMask = stencilMask;
  13580. }
  13581. },
  13582. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13583. if ( currentStencilFunc !== stencilFunc ||
  13584. currentStencilRef !== stencilRef ||
  13585. currentStencilFuncMask !== stencilMask ) {
  13586. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13587. currentStencilFunc = stencilFunc;
  13588. currentStencilRef = stencilRef;
  13589. currentStencilFuncMask = stencilMask;
  13590. }
  13591. },
  13592. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13593. if ( currentStencilFail !== stencilFail ||
  13594. currentStencilZFail !== stencilZFail ||
  13595. currentStencilZPass !== stencilZPass ) {
  13596. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13597. currentStencilFail = stencilFail;
  13598. currentStencilZFail = stencilZFail;
  13599. currentStencilZPass = stencilZPass;
  13600. }
  13601. },
  13602. setLocked: function ( lock ) {
  13603. locked = lock;
  13604. },
  13605. setClear: function ( stencil ) {
  13606. if ( currentStencilClear !== stencil ) {
  13607. gl.clearStencil( stencil );
  13608. currentStencilClear = stencil;
  13609. }
  13610. },
  13611. reset: function () {
  13612. locked = false;
  13613. currentStencilMask = null;
  13614. currentStencilFunc = null;
  13615. currentStencilRef = null;
  13616. currentStencilFuncMask = null;
  13617. currentStencilFail = null;
  13618. currentStencilZFail = null;
  13619. currentStencilZPass = null;
  13620. currentStencilClear = null;
  13621. }
  13622. };
  13623. }
  13624. //
  13625. const colorBuffer = new ColorBuffer();
  13626. const depthBuffer = new DepthBuffer();
  13627. const stencilBuffer = new StencilBuffer();
  13628. const uboBindings = new WeakMap();
  13629. const uboProgramMap = new WeakMap();
  13630. let enabledCapabilities = {};
  13631. let currentBoundFramebuffers = {};
  13632. let currentDrawbuffers = new WeakMap();
  13633. let defaultDrawbuffers = [];
  13634. let currentProgram = null;
  13635. let currentBlendingEnabled = false;
  13636. let currentBlending = null;
  13637. let currentBlendEquation = null;
  13638. let currentBlendSrc = null;
  13639. let currentBlendDst = null;
  13640. let currentBlendEquationAlpha = null;
  13641. let currentBlendSrcAlpha = null;
  13642. let currentBlendDstAlpha = null;
  13643. let currentPremultipledAlpha = false;
  13644. let currentFlipSided = null;
  13645. let currentCullFace = null;
  13646. let currentLineWidth = null;
  13647. let currentPolygonOffsetFactor = null;
  13648. let currentPolygonOffsetUnits = null;
  13649. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13650. let lineWidthAvailable = false;
  13651. let version = 0;
  13652. const glVersion = gl.getParameter( gl.VERSION );
  13653. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13654. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13655. lineWidthAvailable = ( version >= 1.0 );
  13656. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13657. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13658. lineWidthAvailable = ( version >= 2.0 );
  13659. }
  13660. let currentTextureSlot = null;
  13661. let currentBoundTextures = {};
  13662. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13663. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13664. const currentScissor = new Vector4().fromArray( scissorParam );
  13665. const currentViewport = new Vector4().fromArray( viewportParam );
  13666. function createTexture( type, target, count, dimensions ) {
  13667. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13668. const texture = gl.createTexture();
  13669. gl.bindTexture( type, texture );
  13670. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13671. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13672. for ( let i = 0; i < count; i ++ ) {
  13673. if ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) {
  13674. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13675. } else {
  13676. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13677. }
  13678. }
  13679. return texture;
  13680. }
  13681. const emptyTextures = {};
  13682. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13683. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13684. if ( isWebGL2 ) {
  13685. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13686. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13687. }
  13688. // init
  13689. colorBuffer.setClear( 0, 0, 0, 1 );
  13690. depthBuffer.setClear( 1 );
  13691. stencilBuffer.setClear( 0 );
  13692. enable( gl.DEPTH_TEST );
  13693. depthBuffer.setFunc( LessEqualDepth );
  13694. setFlipSided( false );
  13695. setCullFace( CullFaceBack );
  13696. enable( gl.CULL_FACE );
  13697. setBlending( NoBlending );
  13698. //
  13699. function enable( id ) {
  13700. if ( enabledCapabilities[ id ] !== true ) {
  13701. gl.enable( id );
  13702. enabledCapabilities[ id ] = true;
  13703. }
  13704. }
  13705. function disable( id ) {
  13706. if ( enabledCapabilities[ id ] !== false ) {
  13707. gl.disable( id );
  13708. enabledCapabilities[ id ] = false;
  13709. }
  13710. }
  13711. function bindFramebuffer( target, framebuffer ) {
  13712. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13713. gl.bindFramebuffer( target, framebuffer );
  13714. currentBoundFramebuffers[ target ] = framebuffer;
  13715. if ( isWebGL2 ) {
  13716. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13717. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13718. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13719. }
  13720. if ( target === gl.FRAMEBUFFER ) {
  13721. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13722. }
  13723. }
  13724. return true;
  13725. }
  13726. return false;
  13727. }
  13728. function drawBuffers( renderTarget, framebuffer ) {
  13729. let drawBuffers = defaultDrawbuffers;
  13730. let needsUpdate = false;
  13731. if ( renderTarget ) {
  13732. drawBuffers = currentDrawbuffers.get( framebuffer );
  13733. if ( drawBuffers === undefined ) {
  13734. drawBuffers = [];
  13735. currentDrawbuffers.set( framebuffer, drawBuffers );
  13736. }
  13737. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13738. const textures = renderTarget.texture;
  13739. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13740. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13741. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13742. }
  13743. drawBuffers.length = textures.length;
  13744. needsUpdate = true;
  13745. }
  13746. } else {
  13747. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13748. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13749. needsUpdate = true;
  13750. }
  13751. }
  13752. } else {
  13753. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13754. drawBuffers[ 0 ] = gl.BACK;
  13755. needsUpdate = true;
  13756. }
  13757. }
  13758. if ( needsUpdate ) {
  13759. if ( capabilities.isWebGL2 ) {
  13760. gl.drawBuffers( drawBuffers );
  13761. } else {
  13762. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13763. }
  13764. }
  13765. }
  13766. function useProgram( program ) {
  13767. if ( currentProgram !== program ) {
  13768. gl.useProgram( program );
  13769. currentProgram = program;
  13770. return true;
  13771. }
  13772. return false;
  13773. }
  13774. const equationToGL = {
  13775. [ AddEquation ]: gl.FUNC_ADD,
  13776. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13777. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13778. };
  13779. if ( isWebGL2 ) {
  13780. equationToGL[ MinEquation ] = gl.MIN;
  13781. equationToGL[ MaxEquation ] = gl.MAX;
  13782. } else {
  13783. const extension = extensions.get( 'EXT_blend_minmax' );
  13784. if ( extension !== null ) {
  13785. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13786. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13787. }
  13788. }
  13789. const factorToGL = {
  13790. [ ZeroFactor ]: gl.ZERO,
  13791. [ OneFactor ]: gl.ONE,
  13792. [ SrcColorFactor ]: gl.SRC_COLOR,
  13793. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13794. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13795. [ DstColorFactor ]: gl.DST_COLOR,
  13796. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13797. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13798. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13799. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13800. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13801. };
  13802. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13803. if ( blending === NoBlending ) {
  13804. if ( currentBlendingEnabled === true ) {
  13805. disable( gl.BLEND );
  13806. currentBlendingEnabled = false;
  13807. }
  13808. return;
  13809. }
  13810. if ( currentBlendingEnabled === false ) {
  13811. enable( gl.BLEND );
  13812. currentBlendingEnabled = true;
  13813. }
  13814. if ( blending !== CustomBlending ) {
  13815. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13816. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13817. gl.blendEquation( gl.FUNC_ADD );
  13818. currentBlendEquation = AddEquation;
  13819. currentBlendEquationAlpha = AddEquation;
  13820. }
  13821. if ( premultipliedAlpha ) {
  13822. switch ( blending ) {
  13823. case NormalBlending:
  13824. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13825. break;
  13826. case AdditiveBlending:
  13827. gl.blendFunc( gl.ONE, gl.ONE );
  13828. break;
  13829. case SubtractiveBlending:
  13830. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13831. break;
  13832. case MultiplyBlending:
  13833. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13834. break;
  13835. default:
  13836. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13837. break;
  13838. }
  13839. } else {
  13840. switch ( blending ) {
  13841. case NormalBlending:
  13842. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13843. break;
  13844. case AdditiveBlending:
  13845. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13846. break;
  13847. case SubtractiveBlending:
  13848. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13849. break;
  13850. case MultiplyBlending:
  13851. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13852. break;
  13853. default:
  13854. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13855. break;
  13856. }
  13857. }
  13858. currentBlendSrc = null;
  13859. currentBlendDst = null;
  13860. currentBlendSrcAlpha = null;
  13861. currentBlendDstAlpha = null;
  13862. currentBlending = blending;
  13863. currentPremultipledAlpha = premultipliedAlpha;
  13864. }
  13865. return;
  13866. }
  13867. // custom blending
  13868. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13869. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13870. blendDstAlpha = blendDstAlpha || blendDst;
  13871. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13872. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13873. currentBlendEquation = blendEquation;
  13874. currentBlendEquationAlpha = blendEquationAlpha;
  13875. }
  13876. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13877. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13878. currentBlendSrc = blendSrc;
  13879. currentBlendDst = blendDst;
  13880. currentBlendSrcAlpha = blendSrcAlpha;
  13881. currentBlendDstAlpha = blendDstAlpha;
  13882. }
  13883. currentBlending = blending;
  13884. currentPremultipledAlpha = false;
  13885. }
  13886. function setMaterial( material, frontFaceCW ) {
  13887. material.side === DoubleSide
  13888. ? disable( gl.CULL_FACE )
  13889. : enable( gl.CULL_FACE );
  13890. let flipSided = ( material.side === BackSide );
  13891. if ( frontFaceCW ) flipSided = ! flipSided;
  13892. setFlipSided( flipSided );
  13893. ( material.blending === NormalBlending && material.transparent === false )
  13894. ? setBlending( NoBlending )
  13895. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13896. depthBuffer.setFunc( material.depthFunc );
  13897. depthBuffer.setTest( material.depthTest );
  13898. depthBuffer.setMask( material.depthWrite );
  13899. colorBuffer.setMask( material.colorWrite );
  13900. const stencilWrite = material.stencilWrite;
  13901. stencilBuffer.setTest( stencilWrite );
  13902. if ( stencilWrite ) {
  13903. stencilBuffer.setMask( material.stencilWriteMask );
  13904. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13905. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13906. }
  13907. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13908. material.alphaToCoverage === true
  13909. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13910. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13911. }
  13912. //
  13913. function setFlipSided( flipSided ) {
  13914. if ( currentFlipSided !== flipSided ) {
  13915. if ( flipSided ) {
  13916. gl.frontFace( gl.CW );
  13917. } else {
  13918. gl.frontFace( gl.CCW );
  13919. }
  13920. currentFlipSided = flipSided;
  13921. }
  13922. }
  13923. function setCullFace( cullFace ) {
  13924. if ( cullFace !== CullFaceNone ) {
  13925. enable( gl.CULL_FACE );
  13926. if ( cullFace !== currentCullFace ) {
  13927. if ( cullFace === CullFaceBack ) {
  13928. gl.cullFace( gl.BACK );
  13929. } else if ( cullFace === CullFaceFront ) {
  13930. gl.cullFace( gl.FRONT );
  13931. } else {
  13932. gl.cullFace( gl.FRONT_AND_BACK );
  13933. }
  13934. }
  13935. } else {
  13936. disable( gl.CULL_FACE );
  13937. }
  13938. currentCullFace = cullFace;
  13939. }
  13940. function setLineWidth( width ) {
  13941. if ( width !== currentLineWidth ) {
  13942. if ( lineWidthAvailable ) gl.lineWidth( width );
  13943. currentLineWidth = width;
  13944. }
  13945. }
  13946. function setPolygonOffset( polygonOffset, factor, units ) {
  13947. if ( polygonOffset ) {
  13948. enable( gl.POLYGON_OFFSET_FILL );
  13949. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13950. gl.polygonOffset( factor, units );
  13951. currentPolygonOffsetFactor = factor;
  13952. currentPolygonOffsetUnits = units;
  13953. }
  13954. } else {
  13955. disable( gl.POLYGON_OFFSET_FILL );
  13956. }
  13957. }
  13958. function setScissorTest( scissorTest ) {
  13959. if ( scissorTest ) {
  13960. enable( gl.SCISSOR_TEST );
  13961. } else {
  13962. disable( gl.SCISSOR_TEST );
  13963. }
  13964. }
  13965. // texture
  13966. function activeTexture( webglSlot ) {
  13967. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13968. if ( currentTextureSlot !== webglSlot ) {
  13969. gl.activeTexture( webglSlot );
  13970. currentTextureSlot = webglSlot;
  13971. }
  13972. }
  13973. function bindTexture( webglType, webglTexture, webglSlot ) {
  13974. if ( webglSlot === undefined ) {
  13975. if ( currentTextureSlot === null ) {
  13976. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13977. } else {
  13978. webglSlot = currentTextureSlot;
  13979. }
  13980. }
  13981. let boundTexture = currentBoundTextures[ webglSlot ];
  13982. if ( boundTexture === undefined ) {
  13983. boundTexture = { type: undefined, texture: undefined };
  13984. currentBoundTextures[ webglSlot ] = boundTexture;
  13985. }
  13986. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13987. if ( currentTextureSlot !== webglSlot ) {
  13988. gl.activeTexture( webglSlot );
  13989. currentTextureSlot = webglSlot;
  13990. }
  13991. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13992. boundTexture.type = webglType;
  13993. boundTexture.texture = webglTexture;
  13994. }
  13995. }
  13996. function unbindTexture() {
  13997. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13998. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13999. gl.bindTexture( boundTexture.type, null );
  14000. boundTexture.type = undefined;
  14001. boundTexture.texture = undefined;
  14002. }
  14003. }
  14004. function compressedTexImage2D() {
  14005. try {
  14006. gl.compressedTexImage2D.apply( gl, arguments );
  14007. } catch ( error ) {
  14008. console.error( 'THREE.WebGLState:', error );
  14009. }
  14010. }
  14011. function compressedTexImage3D() {
  14012. try {
  14013. gl.compressedTexImage3D.apply( gl, arguments );
  14014. } catch ( error ) {
  14015. console.error( 'THREE.WebGLState:', error );
  14016. }
  14017. }
  14018. function texSubImage2D() {
  14019. try {
  14020. gl.texSubImage2D.apply( gl, arguments );
  14021. } catch ( error ) {
  14022. console.error( 'THREE.WebGLState:', error );
  14023. }
  14024. }
  14025. function texSubImage3D() {
  14026. try {
  14027. gl.texSubImage3D.apply( gl, arguments );
  14028. } catch ( error ) {
  14029. console.error( 'THREE.WebGLState:', error );
  14030. }
  14031. }
  14032. function compressedTexSubImage2D() {
  14033. try {
  14034. gl.compressedTexSubImage2D.apply( gl, arguments );
  14035. } catch ( error ) {
  14036. console.error( 'THREE.WebGLState:', error );
  14037. }
  14038. }
  14039. function compressedTexSubImage3D() {
  14040. try {
  14041. gl.compressedTexSubImage3D.apply( gl, arguments );
  14042. } catch ( error ) {
  14043. console.error( 'THREE.WebGLState:', error );
  14044. }
  14045. }
  14046. function texStorage2D() {
  14047. try {
  14048. gl.texStorage2D.apply( gl, arguments );
  14049. } catch ( error ) {
  14050. console.error( 'THREE.WebGLState:', error );
  14051. }
  14052. }
  14053. function texStorage3D() {
  14054. try {
  14055. gl.texStorage3D.apply( gl, arguments );
  14056. } catch ( error ) {
  14057. console.error( 'THREE.WebGLState:', error );
  14058. }
  14059. }
  14060. function texImage2D() {
  14061. try {
  14062. gl.texImage2D.apply( gl, arguments );
  14063. } catch ( error ) {
  14064. console.error( 'THREE.WebGLState:', error );
  14065. }
  14066. }
  14067. function texImage3D() {
  14068. try {
  14069. gl.texImage3D.apply( gl, arguments );
  14070. } catch ( error ) {
  14071. console.error( 'THREE.WebGLState:', error );
  14072. }
  14073. }
  14074. //
  14075. function scissor( scissor ) {
  14076. if ( currentScissor.equals( scissor ) === false ) {
  14077. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14078. currentScissor.copy( scissor );
  14079. }
  14080. }
  14081. function viewport( viewport ) {
  14082. if ( currentViewport.equals( viewport ) === false ) {
  14083. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14084. currentViewport.copy( viewport );
  14085. }
  14086. }
  14087. function updateUBOMapping( uniformsGroup, program ) {
  14088. let mapping = uboProgramMap.get( program );
  14089. if ( mapping === undefined ) {
  14090. mapping = new WeakMap();
  14091. uboProgramMap.set( program, mapping );
  14092. }
  14093. let blockIndex = mapping.get( uniformsGroup );
  14094. if ( blockIndex === undefined ) {
  14095. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14096. mapping.set( uniformsGroup, blockIndex );
  14097. }
  14098. }
  14099. function uniformBlockBinding( uniformsGroup, program ) {
  14100. const mapping = uboProgramMap.get( program );
  14101. const blockIndex = mapping.get( uniformsGroup );
  14102. if ( uboBindings.get( program ) !== blockIndex ) {
  14103. // bind shader specific block index to global block point
  14104. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14105. uboBindings.set( program, blockIndex );
  14106. }
  14107. }
  14108. //
  14109. function reset() {
  14110. // reset state
  14111. gl.disable( gl.BLEND );
  14112. gl.disable( gl.CULL_FACE );
  14113. gl.disable( gl.DEPTH_TEST );
  14114. gl.disable( gl.POLYGON_OFFSET_FILL );
  14115. gl.disable( gl.SCISSOR_TEST );
  14116. gl.disable( gl.STENCIL_TEST );
  14117. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14118. gl.blendEquation( gl.FUNC_ADD );
  14119. gl.blendFunc( gl.ONE, gl.ZERO );
  14120. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14121. gl.colorMask( true, true, true, true );
  14122. gl.clearColor( 0, 0, 0, 0 );
  14123. gl.depthMask( true );
  14124. gl.depthFunc( gl.LESS );
  14125. gl.clearDepth( 1 );
  14126. gl.stencilMask( 0xffffffff );
  14127. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14128. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14129. gl.clearStencil( 0 );
  14130. gl.cullFace( gl.BACK );
  14131. gl.frontFace( gl.CCW );
  14132. gl.polygonOffset( 0, 0 );
  14133. gl.activeTexture( gl.TEXTURE0 );
  14134. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14135. if ( isWebGL2 === true ) {
  14136. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14137. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14138. }
  14139. gl.useProgram( null );
  14140. gl.lineWidth( 1 );
  14141. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14142. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14143. // reset internals
  14144. enabledCapabilities = {};
  14145. currentTextureSlot = null;
  14146. currentBoundTextures = {};
  14147. currentBoundFramebuffers = {};
  14148. currentDrawbuffers = new WeakMap();
  14149. defaultDrawbuffers = [];
  14150. currentProgram = null;
  14151. currentBlendingEnabled = false;
  14152. currentBlending = null;
  14153. currentBlendEquation = null;
  14154. currentBlendSrc = null;
  14155. currentBlendDst = null;
  14156. currentBlendEquationAlpha = null;
  14157. currentBlendSrcAlpha = null;
  14158. currentBlendDstAlpha = null;
  14159. currentPremultipledAlpha = false;
  14160. currentFlipSided = null;
  14161. currentCullFace = null;
  14162. currentLineWidth = null;
  14163. currentPolygonOffsetFactor = null;
  14164. currentPolygonOffsetUnits = null;
  14165. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14166. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14167. colorBuffer.reset();
  14168. depthBuffer.reset();
  14169. stencilBuffer.reset();
  14170. }
  14171. return {
  14172. buffers: {
  14173. color: colorBuffer,
  14174. depth: depthBuffer,
  14175. stencil: stencilBuffer
  14176. },
  14177. enable: enable,
  14178. disable: disable,
  14179. bindFramebuffer: bindFramebuffer,
  14180. drawBuffers: drawBuffers,
  14181. useProgram: useProgram,
  14182. setBlending: setBlending,
  14183. setMaterial: setMaterial,
  14184. setFlipSided: setFlipSided,
  14185. setCullFace: setCullFace,
  14186. setLineWidth: setLineWidth,
  14187. setPolygonOffset: setPolygonOffset,
  14188. setScissorTest: setScissorTest,
  14189. activeTexture: activeTexture,
  14190. bindTexture: bindTexture,
  14191. unbindTexture: unbindTexture,
  14192. compressedTexImage2D: compressedTexImage2D,
  14193. compressedTexImage3D: compressedTexImage3D,
  14194. texImage2D: texImage2D,
  14195. texImage3D: texImage3D,
  14196. updateUBOMapping: updateUBOMapping,
  14197. uniformBlockBinding: uniformBlockBinding,
  14198. texStorage2D: texStorage2D,
  14199. texStorage3D: texStorage3D,
  14200. texSubImage2D: texSubImage2D,
  14201. texSubImage3D: texSubImage3D,
  14202. compressedTexSubImage2D: compressedTexSubImage2D,
  14203. compressedTexSubImage3D: compressedTexSubImage3D,
  14204. scissor: scissor,
  14205. viewport: viewport,
  14206. reset: reset
  14207. };
  14208. }
  14209. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14210. const isWebGL2 = capabilities.isWebGL2;
  14211. const maxTextures = capabilities.maxTextures;
  14212. const maxCubemapSize = capabilities.maxCubemapSize;
  14213. const maxTextureSize = capabilities.maxTextureSize;
  14214. const maxSamples = capabilities.maxSamples;
  14215. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14216. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14217. const _videoTextures = new WeakMap();
  14218. let _canvas;
  14219. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14220. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14221. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14222. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14223. let useOffscreenCanvas = false;
  14224. try {
  14225. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14226. // eslint-disable-next-line compat/compat
  14227. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14228. } catch ( err ) {
  14229. // Ignore any errors
  14230. }
  14231. function createCanvas( width, height ) {
  14232. // Use OffscreenCanvas when available. Specially needed in web workers
  14233. return useOffscreenCanvas ?
  14234. // eslint-disable-next-line compat/compat
  14235. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14236. }
  14237. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14238. let scale = 1;
  14239. // handle case if texture exceeds max size
  14240. if ( image.width > maxSize || image.height > maxSize ) {
  14241. scale = maxSize / Math.max( image.width, image.height );
  14242. }
  14243. // only perform resize if necessary
  14244. if ( scale < 1 || needsPowerOfTwo === true ) {
  14245. // only perform resize for certain image types
  14246. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14247. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14248. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14249. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14250. const width = floor( scale * image.width );
  14251. const height = floor( scale * image.height );
  14252. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14253. // cube textures can't reuse the same canvas
  14254. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14255. canvas.width = width;
  14256. canvas.height = height;
  14257. const context = canvas.getContext( '2d' );
  14258. context.drawImage( image, 0, 0, width, height );
  14259. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14260. return canvas;
  14261. } else {
  14262. if ( 'data' in image ) {
  14263. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14264. }
  14265. return image;
  14266. }
  14267. }
  14268. return image;
  14269. }
  14270. function isPowerOfTwo$1( image ) {
  14271. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14272. }
  14273. function textureNeedsPowerOfTwo( texture ) {
  14274. if ( isWebGL2 ) return false;
  14275. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14276. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14277. }
  14278. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14279. return texture.generateMipmaps && supportsMips &&
  14280. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14281. }
  14282. function generateMipmap( target ) {
  14283. _gl.generateMipmap( target );
  14284. }
  14285. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14286. if ( isWebGL2 === false ) return glFormat;
  14287. if ( internalFormatName !== null ) {
  14288. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14289. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14290. }
  14291. let internalFormat = glFormat;
  14292. if ( glFormat === _gl.RED ) {
  14293. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14294. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14295. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14296. }
  14297. if ( glFormat === _gl.RED_INTEGER ) {
  14298. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14299. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14300. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14301. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14302. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14303. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14304. }
  14305. if ( glFormat === _gl.RG ) {
  14306. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14307. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14308. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14309. }
  14310. if ( glFormat === _gl.RGBA ) {
  14311. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14312. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14313. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14314. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14315. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14316. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14317. }
  14318. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14319. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14320. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14321. extensions.get( 'EXT_color_buffer_float' );
  14322. }
  14323. return internalFormat;
  14324. }
  14325. function getMipLevels( texture, image, supportsMips ) {
  14326. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14327. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14328. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14329. // user-defined mipmaps
  14330. return texture.mipmaps.length;
  14331. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14332. return image.mipmaps.length;
  14333. } else {
  14334. // texture without mipmaps (only base level)
  14335. return 1;
  14336. }
  14337. }
  14338. // Fallback filters for non-power-of-2 textures
  14339. function filterFallback( f ) {
  14340. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14341. return _gl.NEAREST;
  14342. }
  14343. return _gl.LINEAR;
  14344. }
  14345. //
  14346. function onTextureDispose( event ) {
  14347. const texture = event.target;
  14348. texture.removeEventListener( 'dispose', onTextureDispose );
  14349. deallocateTexture( texture );
  14350. if ( texture.isVideoTexture ) {
  14351. _videoTextures.delete( texture );
  14352. }
  14353. }
  14354. function onRenderTargetDispose( event ) {
  14355. const renderTarget = event.target;
  14356. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14357. deallocateRenderTarget( renderTarget );
  14358. }
  14359. //
  14360. function deallocateTexture( texture ) {
  14361. const textureProperties = properties.get( texture );
  14362. if ( textureProperties.__webglInit === undefined ) return;
  14363. // check if it's necessary to remove the WebGLTexture object
  14364. const source = texture.source;
  14365. const webglTextures = _sources.get( source );
  14366. if ( webglTextures ) {
  14367. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14368. webglTexture.usedTimes --;
  14369. // the WebGLTexture object is not used anymore, remove it
  14370. if ( webglTexture.usedTimes === 0 ) {
  14371. deleteTexture( texture );
  14372. }
  14373. // remove the weak map entry if no WebGLTexture uses the source anymore
  14374. if ( Object.keys( webglTextures ).length === 0 ) {
  14375. _sources.delete( source );
  14376. }
  14377. }
  14378. properties.remove( texture );
  14379. }
  14380. function deleteTexture( texture ) {
  14381. const textureProperties = properties.get( texture );
  14382. _gl.deleteTexture( textureProperties.__webglTexture );
  14383. const source = texture.source;
  14384. const webglTextures = _sources.get( source );
  14385. delete webglTextures[ textureProperties.__cacheKey ];
  14386. info.memory.textures --;
  14387. }
  14388. function deallocateRenderTarget( renderTarget ) {
  14389. const texture = renderTarget.texture;
  14390. const renderTargetProperties = properties.get( renderTarget );
  14391. const textureProperties = properties.get( texture );
  14392. if ( textureProperties.__webglTexture !== undefined ) {
  14393. _gl.deleteTexture( textureProperties.__webglTexture );
  14394. info.memory.textures --;
  14395. }
  14396. if ( renderTarget.depthTexture ) {
  14397. renderTarget.depthTexture.dispose();
  14398. }
  14399. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14400. for ( let i = 0; i < 6; i ++ ) {
  14401. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14402. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14403. } else {
  14404. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14405. }
  14406. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14407. }
  14408. } else {
  14409. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14410. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14411. } else {
  14412. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14413. }
  14414. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14415. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14416. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14417. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14418. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14419. }
  14420. }
  14421. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14422. }
  14423. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14424. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14425. const attachmentProperties = properties.get( texture[ i ] );
  14426. if ( attachmentProperties.__webglTexture ) {
  14427. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14428. info.memory.textures --;
  14429. }
  14430. properties.remove( texture[ i ] );
  14431. }
  14432. }
  14433. properties.remove( texture );
  14434. properties.remove( renderTarget );
  14435. }
  14436. //
  14437. let textureUnits = 0;
  14438. function resetTextureUnits() {
  14439. textureUnits = 0;
  14440. }
  14441. function allocateTextureUnit() {
  14442. const textureUnit = textureUnits;
  14443. if ( textureUnit >= maxTextures ) {
  14444. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14445. }
  14446. textureUnits += 1;
  14447. return textureUnit;
  14448. }
  14449. function getTextureCacheKey( texture ) {
  14450. const array = [];
  14451. array.push( texture.wrapS );
  14452. array.push( texture.wrapT );
  14453. array.push( texture.wrapR || 0 );
  14454. array.push( texture.magFilter );
  14455. array.push( texture.minFilter );
  14456. array.push( texture.anisotropy );
  14457. array.push( texture.internalFormat );
  14458. array.push( texture.format );
  14459. array.push( texture.type );
  14460. array.push( texture.generateMipmaps );
  14461. array.push( texture.premultiplyAlpha );
  14462. array.push( texture.flipY );
  14463. array.push( texture.unpackAlignment );
  14464. array.push( texture.colorSpace );
  14465. return array.join();
  14466. }
  14467. //
  14468. function setTexture2D( texture, slot ) {
  14469. const textureProperties = properties.get( texture );
  14470. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14471. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14472. const image = texture.image;
  14473. if ( image === null ) {
  14474. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14475. } else if ( image.complete === false ) {
  14476. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14477. } else {
  14478. uploadTexture( textureProperties, texture, slot );
  14479. return;
  14480. }
  14481. }
  14482. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14483. }
  14484. function setTexture2DArray( texture, slot ) {
  14485. const textureProperties = properties.get( texture );
  14486. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14487. uploadTexture( textureProperties, texture, slot );
  14488. return;
  14489. }
  14490. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14491. }
  14492. function setTexture3D( texture, slot ) {
  14493. const textureProperties = properties.get( texture );
  14494. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14495. uploadTexture( textureProperties, texture, slot );
  14496. return;
  14497. }
  14498. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14499. }
  14500. function setTextureCube( texture, slot ) {
  14501. const textureProperties = properties.get( texture );
  14502. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14503. uploadCubeTexture( textureProperties, texture, slot );
  14504. return;
  14505. }
  14506. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14507. }
  14508. const wrappingToGL = {
  14509. [ RepeatWrapping ]: _gl.REPEAT,
  14510. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14511. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14512. };
  14513. const filterToGL = {
  14514. [ NearestFilter ]: _gl.NEAREST,
  14515. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14516. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14517. [ LinearFilter ]: _gl.LINEAR,
  14518. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14519. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14520. };
  14521. const compareToGL = {
  14522. [ NeverCompare ]: _gl.NEVER,
  14523. [ AlwaysCompare ]: _gl.ALWAYS,
  14524. [ LessCompare ]: _gl.LESS,
  14525. [ LessEqualCompare ]: _gl.LEQUAL,
  14526. [ EqualCompare ]: _gl.EQUAL,
  14527. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14528. [ GreaterCompare ]: _gl.GREATER,
  14529. [ NotEqualCompare ]: _gl.NOTEQUAL
  14530. };
  14531. function setTextureParameters( textureType, texture, supportsMips ) {
  14532. if ( supportsMips ) {
  14533. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14534. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14535. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14536. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14537. }
  14538. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14539. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14540. } else {
  14541. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14542. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14543. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14544. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  14545. }
  14546. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14547. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14548. }
  14549. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14550. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14551. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14552. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14553. }
  14554. }
  14555. if ( texture.compareFunction ) {
  14556. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14557. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14558. }
  14559. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14560. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14561. if ( texture.magFilter === NearestFilter ) return;
  14562. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14563. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14564. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14565. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14566. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14567. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14568. }
  14569. }
  14570. }
  14571. function initTexture( textureProperties, texture ) {
  14572. let forceUpload = false;
  14573. if ( textureProperties.__webglInit === undefined ) {
  14574. textureProperties.__webglInit = true;
  14575. texture.addEventListener( 'dispose', onTextureDispose );
  14576. }
  14577. // create Source <-> WebGLTextures mapping if necessary
  14578. const source = texture.source;
  14579. let webglTextures = _sources.get( source );
  14580. if ( webglTextures === undefined ) {
  14581. webglTextures = {};
  14582. _sources.set( source, webglTextures );
  14583. }
  14584. // check if there is already a WebGLTexture object for the given texture parameters
  14585. const textureCacheKey = getTextureCacheKey( texture );
  14586. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14587. // if not, create a new instance of WebGLTexture
  14588. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14589. // create new entry
  14590. webglTextures[ textureCacheKey ] = {
  14591. texture: _gl.createTexture(),
  14592. usedTimes: 0
  14593. };
  14594. info.memory.textures ++;
  14595. // when a new instance of WebGLTexture was created, a texture upload is required
  14596. // even if the image contents are identical
  14597. forceUpload = true;
  14598. }
  14599. webglTextures[ textureCacheKey ].usedTimes ++;
  14600. // every time the texture cache key changes, it's necessary to check if an instance of
  14601. // WebGLTexture can be deleted in order to avoid a memory leak.
  14602. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14603. if ( webglTexture !== undefined ) {
  14604. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14605. if ( webglTexture.usedTimes === 0 ) {
  14606. deleteTexture( texture );
  14607. }
  14608. }
  14609. // store references to cache key and WebGLTexture object
  14610. textureProperties.__cacheKey = textureCacheKey;
  14611. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14612. }
  14613. return forceUpload;
  14614. }
  14615. function uploadTexture( textureProperties, texture, slot ) {
  14616. let textureType = _gl.TEXTURE_2D;
  14617. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14618. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14619. const forceUpload = initTexture( textureProperties, texture );
  14620. const source = texture.source;
  14621. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14622. const sourceProperties = properties.get( source );
  14623. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14624. state.activeTexture( _gl.TEXTURE0 + slot );
  14625. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14626. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14627. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14628. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14629. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14630. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14631. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14632. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14633. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14634. image = verifyColorSpace( texture, image );
  14635. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14636. glFormat = utils.convert( texture.format, texture.colorSpace );
  14637. let glType = utils.convert( texture.type ),
  14638. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14639. setTextureParameters( textureType, texture, supportsMips );
  14640. let mipmap;
  14641. const mipmaps = texture.mipmaps;
  14642. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14643. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14644. const levels = getMipLevels( texture, image, supportsMips );
  14645. if ( texture.isDepthTexture ) {
  14646. // populate depth texture with dummy data
  14647. glInternalFormat = _gl.DEPTH_COMPONENT;
  14648. if ( isWebGL2 ) {
  14649. if ( texture.type === FloatType ) {
  14650. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14651. } else if ( texture.type === UnsignedIntType ) {
  14652. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14653. } else if ( texture.type === UnsignedInt248Type ) {
  14654. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14655. } else {
  14656. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14657. }
  14658. } else {
  14659. if ( texture.type === FloatType ) {
  14660. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14661. }
  14662. }
  14663. // validation checks for WebGL 1
  14664. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14665. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14666. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14667. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14668. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14669. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14670. texture.type = UnsignedIntType;
  14671. glType = utils.convert( texture.type );
  14672. }
  14673. }
  14674. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14675. // Depth stencil textures need the DEPTH_STENCIL internal format
  14676. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14677. glInternalFormat = _gl.DEPTH_STENCIL;
  14678. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14679. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14680. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14681. if ( texture.type !== UnsignedInt248Type ) {
  14682. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14683. texture.type = UnsignedInt248Type;
  14684. glType = utils.convert( texture.type );
  14685. }
  14686. }
  14687. //
  14688. if ( allocateMemory ) {
  14689. if ( useTexStorage ) {
  14690. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14691. } else {
  14692. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14693. }
  14694. }
  14695. } else if ( texture.isDataTexture ) {
  14696. // use manually created mipmaps if available
  14697. // if there are no manual mipmaps
  14698. // set 0 level mipmap and then use GL to generate other mipmap levels
  14699. if ( mipmaps.length > 0 && supportsMips ) {
  14700. if ( useTexStorage && allocateMemory ) {
  14701. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14702. }
  14703. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14704. mipmap = mipmaps[ i ];
  14705. if ( useTexStorage ) {
  14706. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14707. } else {
  14708. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14709. }
  14710. }
  14711. texture.generateMipmaps = false;
  14712. } else {
  14713. if ( useTexStorage ) {
  14714. if ( allocateMemory ) {
  14715. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14716. }
  14717. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14718. } else {
  14719. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14720. }
  14721. }
  14722. } else if ( texture.isCompressedTexture ) {
  14723. if ( texture.isCompressedArrayTexture ) {
  14724. if ( useTexStorage && allocateMemory ) {
  14725. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14726. }
  14727. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14728. mipmap = mipmaps[ i ];
  14729. if ( texture.format !== RGBAFormat ) {
  14730. if ( glFormat !== null ) {
  14731. if ( useTexStorage ) {
  14732. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14733. } else {
  14734. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14735. }
  14736. } else {
  14737. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14738. }
  14739. } else {
  14740. if ( useTexStorage ) {
  14741. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14742. } else {
  14743. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14744. }
  14745. }
  14746. }
  14747. } else {
  14748. if ( useTexStorage && allocateMemory ) {
  14749. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14750. }
  14751. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14752. mipmap = mipmaps[ i ];
  14753. if ( texture.format !== RGBAFormat ) {
  14754. if ( glFormat !== null ) {
  14755. if ( useTexStorage ) {
  14756. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14757. } else {
  14758. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14759. }
  14760. } else {
  14761. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14762. }
  14763. } else {
  14764. if ( useTexStorage ) {
  14765. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14766. } else {
  14767. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14768. }
  14769. }
  14770. }
  14771. }
  14772. } else if ( texture.isDataArrayTexture ) {
  14773. if ( useTexStorage ) {
  14774. if ( allocateMemory ) {
  14775. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14776. }
  14777. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14778. } else {
  14779. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14780. }
  14781. } else if ( texture.isData3DTexture ) {
  14782. if ( useTexStorage ) {
  14783. if ( allocateMemory ) {
  14784. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14785. }
  14786. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14787. } else {
  14788. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14789. }
  14790. } else if ( texture.isFramebufferTexture ) {
  14791. if ( allocateMemory ) {
  14792. if ( useTexStorage ) {
  14793. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14794. } else {
  14795. let width = image.width, height = image.height;
  14796. for ( let i = 0; i < levels; i ++ ) {
  14797. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14798. width >>= 1;
  14799. height >>= 1;
  14800. }
  14801. }
  14802. }
  14803. } else {
  14804. // regular Texture (image, video, canvas)
  14805. // use manually created mipmaps if available
  14806. // if there are no manual mipmaps
  14807. // set 0 level mipmap and then use GL to generate other mipmap levels
  14808. if ( mipmaps.length > 0 && supportsMips ) {
  14809. if ( useTexStorage && allocateMemory ) {
  14810. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14811. }
  14812. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14813. mipmap = mipmaps[ i ];
  14814. if ( useTexStorage ) {
  14815. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14816. } else {
  14817. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14818. }
  14819. }
  14820. texture.generateMipmaps = false;
  14821. } else {
  14822. if ( useTexStorage ) {
  14823. if ( allocateMemory ) {
  14824. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14825. }
  14826. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14827. } else {
  14828. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14829. }
  14830. }
  14831. }
  14832. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14833. generateMipmap( textureType );
  14834. }
  14835. sourceProperties.__version = source.version;
  14836. if ( texture.onUpdate ) texture.onUpdate( texture );
  14837. }
  14838. textureProperties.__version = texture.version;
  14839. }
  14840. function uploadCubeTexture( textureProperties, texture, slot ) {
  14841. if ( texture.image.length !== 6 ) return;
  14842. const forceUpload = initTexture( textureProperties, texture );
  14843. const source = texture.source;
  14844. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14845. const sourceProperties = properties.get( source );
  14846. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14847. state.activeTexture( _gl.TEXTURE0 + slot );
  14848. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14849. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14850. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14851. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14852. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14853. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14854. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14855. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14856. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14857. const cubeImage = [];
  14858. for ( let i = 0; i < 6; i ++ ) {
  14859. if ( ! isCompressed && ! isDataTexture ) {
  14860. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14861. } else {
  14862. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14863. }
  14864. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14865. }
  14866. const image = cubeImage[ 0 ],
  14867. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14868. glFormat = utils.convert( texture.format, texture.colorSpace ),
  14869. glType = utils.convert( texture.type ),
  14870. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14871. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14872. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14873. let levels = getMipLevels( texture, image, supportsMips );
  14874. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14875. let mipmaps;
  14876. if ( isCompressed ) {
  14877. if ( useTexStorage && allocateMemory ) {
  14878. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14879. }
  14880. for ( let i = 0; i < 6; i ++ ) {
  14881. mipmaps = cubeImage[ i ].mipmaps;
  14882. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14883. const mipmap = mipmaps[ j ];
  14884. if ( texture.format !== RGBAFormat ) {
  14885. if ( glFormat !== null ) {
  14886. if ( useTexStorage ) {
  14887. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14888. } else {
  14889. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14890. }
  14891. } else {
  14892. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14893. }
  14894. } else {
  14895. if ( useTexStorage ) {
  14896. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14897. } else {
  14898. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14899. }
  14900. }
  14901. }
  14902. }
  14903. } else {
  14904. mipmaps = texture.mipmaps;
  14905. if ( useTexStorage && allocateMemory ) {
  14906. // TODO: Uniformly handle mipmap definitions
  14907. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14908. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14909. if ( mipmaps.length > 0 ) levels ++;
  14910. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14911. }
  14912. for ( let i = 0; i < 6; i ++ ) {
  14913. if ( isDataTexture ) {
  14914. if ( useTexStorage ) {
  14915. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14916. } else {
  14917. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14918. }
  14919. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14920. const mipmap = mipmaps[ j ];
  14921. const mipmapImage = mipmap.image[ i ].image;
  14922. if ( useTexStorage ) {
  14923. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14924. } else {
  14925. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14926. }
  14927. }
  14928. } else {
  14929. if ( useTexStorage ) {
  14930. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14931. } else {
  14932. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14933. }
  14934. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14935. const mipmap = mipmaps[ j ];
  14936. if ( useTexStorage ) {
  14937. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14938. } else {
  14939. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14940. }
  14941. }
  14942. }
  14943. }
  14944. }
  14945. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14946. // We assume images for cube map have the same size.
  14947. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14948. }
  14949. sourceProperties.__version = source.version;
  14950. if ( texture.onUpdate ) texture.onUpdate( texture );
  14951. }
  14952. textureProperties.__version = texture.version;
  14953. }
  14954. // Render targets
  14955. // Setup storage for target texture and bind it to correct framebuffer
  14956. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  14957. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14958. const glType = utils.convert( texture.type );
  14959. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14960. const renderTargetProperties = properties.get( renderTarget );
  14961. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14962. const width = Math.max( 1, renderTarget.width >> level );
  14963. const height = Math.max( 1, renderTarget.height >> level );
  14964. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14965. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  14966. } else {
  14967. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  14968. }
  14969. }
  14970. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14971. if ( useMultisampledRTT( renderTarget ) ) {
  14972. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14973. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14974. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  14975. }
  14976. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14977. }
  14978. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14979. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14980. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14981. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14982. let glInternalFormat = ( isWebGL2 === true ) ? _gl.DEPTH_COMPONENT24 : _gl.DEPTH_COMPONENT16;
  14983. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14984. const depthTexture = renderTarget.depthTexture;
  14985. if ( depthTexture && depthTexture.isDepthTexture ) {
  14986. if ( depthTexture.type === FloatType ) {
  14987. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14988. } else if ( depthTexture.type === UnsignedIntType ) {
  14989. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14990. }
  14991. }
  14992. const samples = getRenderTargetSamples( renderTarget );
  14993. if ( useMultisampledRTT( renderTarget ) ) {
  14994. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14995. } else {
  14996. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14997. }
  14998. } else {
  14999. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15000. }
  15001. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15002. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15003. const samples = getRenderTargetSamples( renderTarget );
  15004. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15005. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15006. } else if ( useMultisampledRTT( renderTarget ) ) {
  15007. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15008. } else {
  15009. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15010. }
  15011. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15012. } else {
  15013. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  15014. for ( let i = 0; i < textures.length; i ++ ) {
  15015. const texture = textures[ i ];
  15016. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15017. const glType = utils.convert( texture.type );
  15018. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15019. const samples = getRenderTargetSamples( renderTarget );
  15020. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15021. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15022. } else if ( useMultisampledRTT( renderTarget ) ) {
  15023. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15024. } else {
  15025. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15026. }
  15027. }
  15028. }
  15029. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15030. }
  15031. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15032. function setupDepthTexture( framebuffer, renderTarget ) {
  15033. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15034. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15035. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15036. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15037. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15038. }
  15039. // upload an empty depth texture with framebuffer size
  15040. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15041. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15042. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15043. renderTarget.depthTexture.image.width = renderTarget.width;
  15044. renderTarget.depthTexture.image.height = renderTarget.height;
  15045. renderTarget.depthTexture.needsUpdate = true;
  15046. }
  15047. setTexture2D( renderTarget.depthTexture, 0 );
  15048. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15049. const samples = getRenderTargetSamples( renderTarget );
  15050. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15051. if ( useMultisampledRTT( renderTarget ) ) {
  15052. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15053. } else {
  15054. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15055. }
  15056. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15057. if ( useMultisampledRTT( renderTarget ) ) {
  15058. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15059. } else {
  15060. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15061. }
  15062. } else {
  15063. throw new Error( 'Unknown depthTexture format' );
  15064. }
  15065. }
  15066. // Setup GL resources for a non-texture depth buffer
  15067. function setupDepthRenderbuffer( renderTarget ) {
  15068. const renderTargetProperties = properties.get( renderTarget );
  15069. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15070. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15071. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15072. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15073. } else {
  15074. if ( isCube ) {
  15075. renderTargetProperties.__webglDepthbuffer = [];
  15076. for ( let i = 0; i < 6; i ++ ) {
  15077. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15078. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15079. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15080. }
  15081. } else {
  15082. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15083. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15084. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15085. }
  15086. }
  15087. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15088. }
  15089. // rebind framebuffer with external textures
  15090. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15091. const renderTargetProperties = properties.get( renderTarget );
  15092. if ( colorTexture !== undefined ) {
  15093. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15094. }
  15095. if ( depthTexture !== undefined ) {
  15096. setupDepthRenderbuffer( renderTarget );
  15097. }
  15098. }
  15099. // Set up GL resources for the render target
  15100. function setupRenderTarget( renderTarget ) {
  15101. const texture = renderTarget.texture;
  15102. const renderTargetProperties = properties.get( renderTarget );
  15103. const textureProperties = properties.get( texture );
  15104. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15105. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  15106. if ( textureProperties.__webglTexture === undefined ) {
  15107. textureProperties.__webglTexture = _gl.createTexture();
  15108. }
  15109. textureProperties.__version = texture.version;
  15110. info.memory.textures ++;
  15111. }
  15112. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15113. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15114. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15115. // Setup framebuffer
  15116. if ( isCube ) {
  15117. renderTargetProperties.__webglFramebuffer = [];
  15118. for ( let i = 0; i < 6; i ++ ) {
  15119. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15120. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15121. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15122. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15123. }
  15124. } else {
  15125. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15126. }
  15127. }
  15128. } else {
  15129. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15130. renderTargetProperties.__webglFramebuffer = [];
  15131. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15132. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15133. }
  15134. } else {
  15135. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15136. }
  15137. if ( isMultipleRenderTargets ) {
  15138. if ( capabilities.drawBuffers ) {
  15139. const textures = renderTarget.texture;
  15140. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15141. const attachmentProperties = properties.get( textures[ i ] );
  15142. if ( attachmentProperties.__webglTexture === undefined ) {
  15143. attachmentProperties.__webglTexture = _gl.createTexture();
  15144. info.memory.textures ++;
  15145. }
  15146. }
  15147. } else {
  15148. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  15149. }
  15150. }
  15151. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15152. const textures = isMultipleRenderTargets ? texture : [ texture ];
  15153. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15154. renderTargetProperties.__webglColorRenderbuffer = [];
  15155. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15156. for ( let i = 0; i < textures.length; i ++ ) {
  15157. const texture = textures[ i ];
  15158. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15159. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15160. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15161. const glType = utils.convert( texture.type );
  15162. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15163. const samples = getRenderTargetSamples( renderTarget );
  15164. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15165. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15166. }
  15167. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15168. if ( renderTarget.depthBuffer ) {
  15169. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15170. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15171. }
  15172. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15173. }
  15174. }
  15175. // Setup color buffer
  15176. if ( isCube ) {
  15177. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15178. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  15179. for ( let i = 0; i < 6; i ++ ) {
  15180. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15181. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15182. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15183. }
  15184. } else {
  15185. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15186. }
  15187. }
  15188. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15189. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15190. }
  15191. state.unbindTexture();
  15192. } else if ( isMultipleRenderTargets ) {
  15193. const textures = renderTarget.texture;
  15194. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15195. const attachment = textures[ i ];
  15196. const attachmentProperties = properties.get( attachment );
  15197. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15198. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  15199. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15200. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  15201. generateMipmap( _gl.TEXTURE_2D );
  15202. }
  15203. }
  15204. state.unbindTexture();
  15205. } else {
  15206. let glTextureType = _gl.TEXTURE_2D;
  15207. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15208. if ( isWebGL2 ) {
  15209. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15210. } else {
  15211. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  15212. }
  15213. }
  15214. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15215. setTextureParameters( glTextureType, texture, supportsMips );
  15216. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15217. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15218. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15219. }
  15220. } else {
  15221. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15222. }
  15223. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15224. generateMipmap( glTextureType );
  15225. }
  15226. state.unbindTexture();
  15227. }
  15228. // Setup depth and stencil buffers
  15229. if ( renderTarget.depthBuffer ) {
  15230. setupDepthRenderbuffer( renderTarget );
  15231. }
  15232. }
  15233. function updateRenderTargetMipmap( renderTarget ) {
  15234. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15235. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  15236. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15237. const texture = textures[ i ];
  15238. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15239. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15240. const webglTexture = properties.get( texture ).__webglTexture;
  15241. state.bindTexture( target, webglTexture );
  15242. generateMipmap( target );
  15243. state.unbindTexture();
  15244. }
  15245. }
  15246. }
  15247. function updateMultisampleRenderTarget( renderTarget ) {
  15248. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15249. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  15250. const width = renderTarget.width;
  15251. const height = renderTarget.height;
  15252. let mask = _gl.COLOR_BUFFER_BIT;
  15253. const invalidationArray = [];
  15254. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15255. const renderTargetProperties = properties.get( renderTarget );
  15256. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15257. // If MRT we need to remove FBO attachments
  15258. if ( isMultipleRenderTargets ) {
  15259. for ( let i = 0; i < textures.length; i ++ ) {
  15260. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15261. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15262. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15263. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15264. }
  15265. }
  15266. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15267. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15268. for ( let i = 0; i < textures.length; i ++ ) {
  15269. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  15270. if ( renderTarget.depthBuffer ) {
  15271. invalidationArray.push( depthStyle );
  15272. }
  15273. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  15274. if ( ignoreDepthValues === false ) {
  15275. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15276. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15277. }
  15278. if ( isMultipleRenderTargets ) {
  15279. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15280. }
  15281. if ( ignoreDepthValues === true ) {
  15282. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  15283. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15284. }
  15285. if ( isMultipleRenderTargets ) {
  15286. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15287. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15288. }
  15289. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15290. if ( supportsInvalidateFramebuffer ) {
  15291. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  15292. }
  15293. }
  15294. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15295. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15296. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15297. if ( isMultipleRenderTargets ) {
  15298. for ( let i = 0; i < textures.length; i ++ ) {
  15299. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15300. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15301. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15302. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15303. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15304. }
  15305. }
  15306. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15307. }
  15308. }
  15309. function getRenderTargetSamples( renderTarget ) {
  15310. return Math.min( maxSamples, renderTarget.samples );
  15311. }
  15312. function useMultisampledRTT( renderTarget ) {
  15313. const renderTargetProperties = properties.get( renderTarget );
  15314. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15315. }
  15316. function updateVideoTexture( texture ) {
  15317. const frame = info.render.frame;
  15318. // Check the last frame we updated the VideoTexture
  15319. if ( _videoTextures.get( texture ) !== frame ) {
  15320. _videoTextures.set( texture, frame );
  15321. texture.update();
  15322. }
  15323. }
  15324. function verifyColorSpace( texture, image ) {
  15325. const colorSpace = texture.colorSpace;
  15326. const format = texture.format;
  15327. const type = texture.type;
  15328. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  15329. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15330. // sRGB
  15331. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15332. if ( isWebGL2 === false ) {
  15333. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  15334. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  15335. texture.format = _SRGBAFormat;
  15336. // it's not possible to generate mips in WebGL 1 with this extension
  15337. texture.minFilter = LinearFilter;
  15338. texture.generateMipmaps = false;
  15339. } else {
  15340. // slow fallback (CPU decode)
  15341. image = ImageUtils.sRGBToLinear( image );
  15342. }
  15343. } else {
  15344. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15345. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15346. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15347. }
  15348. }
  15349. } else {
  15350. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15351. }
  15352. }
  15353. return image;
  15354. }
  15355. //
  15356. this.allocateTextureUnit = allocateTextureUnit;
  15357. this.resetTextureUnits = resetTextureUnits;
  15358. this.setTexture2D = setTexture2D;
  15359. this.setTexture2DArray = setTexture2DArray;
  15360. this.setTexture3D = setTexture3D;
  15361. this.setTextureCube = setTextureCube;
  15362. this.rebindTextures = rebindTextures;
  15363. this.setupRenderTarget = setupRenderTarget;
  15364. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15365. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15366. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15367. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15368. this.useMultisampledRTT = useMultisampledRTT;
  15369. }
  15370. function WebGLUtils( gl, extensions, capabilities ) {
  15371. const isWebGL2 = capabilities.isWebGL2;
  15372. function convert( p, colorSpace = NoColorSpace ) {
  15373. let extension;
  15374. const transfer = ColorManagement.getTransfer( colorSpace );
  15375. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15376. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15377. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15378. if ( p === ByteType ) return gl.BYTE;
  15379. if ( p === ShortType ) return gl.SHORT;
  15380. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15381. if ( p === IntType ) return gl.INT;
  15382. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15383. if ( p === FloatType ) return gl.FLOAT;
  15384. if ( p === HalfFloatType ) {
  15385. if ( isWebGL2 ) return gl.HALF_FLOAT;
  15386. extension = extensions.get( 'OES_texture_half_float' );
  15387. if ( extension !== null ) {
  15388. return extension.HALF_FLOAT_OES;
  15389. } else {
  15390. return null;
  15391. }
  15392. }
  15393. if ( p === AlphaFormat ) return gl.ALPHA;
  15394. if ( p === RGBAFormat ) return gl.RGBA;
  15395. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15396. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15397. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15398. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15399. // WebGL 1 sRGB fallback
  15400. if ( p === _SRGBAFormat ) {
  15401. extension = extensions.get( 'EXT_sRGB' );
  15402. if ( extension !== null ) {
  15403. return extension.SRGB_ALPHA_EXT;
  15404. } else {
  15405. return null;
  15406. }
  15407. }
  15408. // WebGL2 formats.
  15409. if ( p === RedFormat ) return gl.RED;
  15410. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15411. if ( p === RGFormat ) return gl.RG;
  15412. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15413. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15414. // S3TC
  15415. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15416. if ( transfer === SRGBTransfer ) {
  15417. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15418. if ( extension !== null ) {
  15419. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15420. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15421. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15422. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15423. } else {
  15424. return null;
  15425. }
  15426. } else {
  15427. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15428. if ( extension !== null ) {
  15429. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15430. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15431. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15432. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15433. } else {
  15434. return null;
  15435. }
  15436. }
  15437. }
  15438. // PVRTC
  15439. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15440. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15441. if ( extension !== null ) {
  15442. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15443. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15444. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15445. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15446. } else {
  15447. return null;
  15448. }
  15449. }
  15450. // ETC1
  15451. if ( p === RGB_ETC1_Format ) {
  15452. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15453. if ( extension !== null ) {
  15454. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15455. } else {
  15456. return null;
  15457. }
  15458. }
  15459. // ETC2
  15460. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15461. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15462. if ( extension !== null ) {
  15463. if ( p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15464. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15465. } else {
  15466. return null;
  15467. }
  15468. }
  15469. // ASTC
  15470. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15471. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15472. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15473. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15474. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15475. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15476. if ( extension !== null ) {
  15477. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15478. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15479. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15480. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15481. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15482. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15483. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15484. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15485. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15486. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15487. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15488. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15489. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15490. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15491. } else {
  15492. return null;
  15493. }
  15494. }
  15495. // BPTC
  15496. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15497. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15498. if ( extension !== null ) {
  15499. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15500. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15501. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15502. } else {
  15503. return null;
  15504. }
  15505. }
  15506. // RGTC
  15507. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15508. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15509. if ( extension !== null ) {
  15510. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15511. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15512. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15513. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15514. } else {
  15515. return null;
  15516. }
  15517. }
  15518. //
  15519. if ( p === UnsignedInt248Type ) {
  15520. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  15521. extension = extensions.get( 'WEBGL_depth_texture' );
  15522. if ( extension !== null ) {
  15523. return extension.UNSIGNED_INT_24_8_WEBGL;
  15524. } else {
  15525. return null;
  15526. }
  15527. }
  15528. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15529. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15530. }
  15531. return { convert: convert };
  15532. }
  15533. class ArrayCamera extends PerspectiveCamera {
  15534. constructor( array = [] ) {
  15535. super();
  15536. this.isArrayCamera = true;
  15537. this.cameras = array;
  15538. }
  15539. }
  15540. class Group extends Object3D {
  15541. constructor() {
  15542. super();
  15543. this.isGroup = true;
  15544. this.type = 'Group';
  15545. }
  15546. }
  15547. const _moveEvent = { type: 'move' };
  15548. class WebXRController {
  15549. constructor() {
  15550. this._targetRay = null;
  15551. this._grip = null;
  15552. this._hand = null;
  15553. }
  15554. getHandSpace() {
  15555. if ( this._hand === null ) {
  15556. this._hand = new Group();
  15557. this._hand.matrixAutoUpdate = false;
  15558. this._hand.visible = false;
  15559. this._hand.joints = {};
  15560. this._hand.inputState = { pinching: false };
  15561. }
  15562. return this._hand;
  15563. }
  15564. getTargetRaySpace() {
  15565. if ( this._targetRay === null ) {
  15566. this._targetRay = new Group();
  15567. this._targetRay.matrixAutoUpdate = false;
  15568. this._targetRay.visible = false;
  15569. this._targetRay.hasLinearVelocity = false;
  15570. this._targetRay.linearVelocity = new Vector3();
  15571. this._targetRay.hasAngularVelocity = false;
  15572. this._targetRay.angularVelocity = new Vector3();
  15573. }
  15574. return this._targetRay;
  15575. }
  15576. getGripSpace() {
  15577. if ( this._grip === null ) {
  15578. this._grip = new Group();
  15579. this._grip.matrixAutoUpdate = false;
  15580. this._grip.visible = false;
  15581. this._grip.hasLinearVelocity = false;
  15582. this._grip.linearVelocity = new Vector3();
  15583. this._grip.hasAngularVelocity = false;
  15584. this._grip.angularVelocity = new Vector3();
  15585. }
  15586. return this._grip;
  15587. }
  15588. dispatchEvent( event ) {
  15589. if ( this._targetRay !== null ) {
  15590. this._targetRay.dispatchEvent( event );
  15591. }
  15592. if ( this._grip !== null ) {
  15593. this._grip.dispatchEvent( event );
  15594. }
  15595. if ( this._hand !== null ) {
  15596. this._hand.dispatchEvent( event );
  15597. }
  15598. return this;
  15599. }
  15600. connect( inputSource ) {
  15601. if ( inputSource && inputSource.hand ) {
  15602. const hand = this._hand;
  15603. if ( hand ) {
  15604. for ( const inputjoint of inputSource.hand.values() ) {
  15605. // Initialize hand with joints when connected
  15606. this._getHandJoint( hand, inputjoint );
  15607. }
  15608. }
  15609. }
  15610. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15611. return this;
  15612. }
  15613. disconnect( inputSource ) {
  15614. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15615. if ( this._targetRay !== null ) {
  15616. this._targetRay.visible = false;
  15617. }
  15618. if ( this._grip !== null ) {
  15619. this._grip.visible = false;
  15620. }
  15621. if ( this._hand !== null ) {
  15622. this._hand.visible = false;
  15623. }
  15624. return this;
  15625. }
  15626. update( inputSource, frame, referenceSpace ) {
  15627. let inputPose = null;
  15628. let gripPose = null;
  15629. let handPose = null;
  15630. const targetRay = this._targetRay;
  15631. const grip = this._grip;
  15632. const hand = this._hand;
  15633. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15634. if ( hand && inputSource.hand ) {
  15635. handPose = true;
  15636. for ( const inputjoint of inputSource.hand.values() ) {
  15637. // Update the joints groups with the XRJoint poses
  15638. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15639. // The transform of this joint will be updated with the joint pose on each frame
  15640. const joint = this._getHandJoint( hand, inputjoint );
  15641. if ( jointPose !== null ) {
  15642. joint.matrix.fromArray( jointPose.transform.matrix );
  15643. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15644. joint.matrixWorldNeedsUpdate = true;
  15645. joint.jointRadius = jointPose.radius;
  15646. }
  15647. joint.visible = jointPose !== null;
  15648. }
  15649. // Custom events
  15650. // Check pinchz
  15651. const indexTip = hand.joints[ 'index-finger-tip' ];
  15652. const thumbTip = hand.joints[ 'thumb-tip' ];
  15653. const distance = indexTip.position.distanceTo( thumbTip.position );
  15654. const distanceToPinch = 0.02;
  15655. const threshold = 0.005;
  15656. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15657. hand.inputState.pinching = false;
  15658. this.dispatchEvent( {
  15659. type: 'pinchend',
  15660. handedness: inputSource.handedness,
  15661. target: this
  15662. } );
  15663. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15664. hand.inputState.pinching = true;
  15665. this.dispatchEvent( {
  15666. type: 'pinchstart',
  15667. handedness: inputSource.handedness,
  15668. target: this
  15669. } );
  15670. }
  15671. } else {
  15672. if ( grip !== null && inputSource.gripSpace ) {
  15673. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15674. if ( gripPose !== null ) {
  15675. grip.matrix.fromArray( gripPose.transform.matrix );
  15676. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15677. grip.matrixWorldNeedsUpdate = true;
  15678. if ( gripPose.linearVelocity ) {
  15679. grip.hasLinearVelocity = true;
  15680. grip.linearVelocity.copy( gripPose.linearVelocity );
  15681. } else {
  15682. grip.hasLinearVelocity = false;
  15683. }
  15684. if ( gripPose.angularVelocity ) {
  15685. grip.hasAngularVelocity = true;
  15686. grip.angularVelocity.copy( gripPose.angularVelocity );
  15687. } else {
  15688. grip.hasAngularVelocity = false;
  15689. }
  15690. }
  15691. }
  15692. }
  15693. if ( targetRay !== null ) {
  15694. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15695. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15696. if ( inputPose === null && gripPose !== null ) {
  15697. inputPose = gripPose;
  15698. }
  15699. if ( inputPose !== null ) {
  15700. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15701. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15702. targetRay.matrixWorldNeedsUpdate = true;
  15703. if ( inputPose.linearVelocity ) {
  15704. targetRay.hasLinearVelocity = true;
  15705. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15706. } else {
  15707. targetRay.hasLinearVelocity = false;
  15708. }
  15709. if ( inputPose.angularVelocity ) {
  15710. targetRay.hasAngularVelocity = true;
  15711. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15712. } else {
  15713. targetRay.hasAngularVelocity = false;
  15714. }
  15715. this.dispatchEvent( _moveEvent );
  15716. }
  15717. }
  15718. }
  15719. if ( targetRay !== null ) {
  15720. targetRay.visible = ( inputPose !== null );
  15721. }
  15722. if ( grip !== null ) {
  15723. grip.visible = ( gripPose !== null );
  15724. }
  15725. if ( hand !== null ) {
  15726. hand.visible = ( handPose !== null );
  15727. }
  15728. return this;
  15729. }
  15730. // private method
  15731. _getHandJoint( hand, inputjoint ) {
  15732. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15733. const joint = new Group();
  15734. joint.matrixAutoUpdate = false;
  15735. joint.visible = false;
  15736. hand.joints[ inputjoint.jointName ] = joint;
  15737. hand.add( joint );
  15738. }
  15739. return hand.joints[ inputjoint.jointName ];
  15740. }
  15741. }
  15742. class DepthTexture extends Texture {
  15743. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15744. format = format !== undefined ? format : DepthFormat;
  15745. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15746. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15747. }
  15748. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15749. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15750. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15751. this.isDepthTexture = true;
  15752. this.image = { width: width, height: height };
  15753. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15754. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15755. this.flipY = false;
  15756. this.generateMipmaps = false;
  15757. this.compareFunction = null;
  15758. }
  15759. copy( source ) {
  15760. super.copy( source );
  15761. this.compareFunction = source.compareFunction;
  15762. return this;
  15763. }
  15764. toJSON( meta ) {
  15765. const data = super.toJSON( meta );
  15766. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  15767. return data;
  15768. }
  15769. }
  15770. class WebXRManager extends EventDispatcher {
  15771. constructor( renderer, gl ) {
  15772. super();
  15773. const scope = this;
  15774. let session = null;
  15775. let framebufferScaleFactor = 1.0;
  15776. let referenceSpace = null;
  15777. let referenceSpaceType = 'local-floor';
  15778. // Set default foveation to maximum.
  15779. let foveation = 1.0;
  15780. let customReferenceSpace = null;
  15781. let pose = null;
  15782. let glBinding = null;
  15783. let glProjLayer = null;
  15784. let glBaseLayer = null;
  15785. let xrFrame = null;
  15786. const attributes = gl.getContextAttributes();
  15787. let initialRenderTarget = null;
  15788. let newRenderTarget = null;
  15789. const controllers = [];
  15790. const controllerInputSources = [];
  15791. //
  15792. const cameraL = new PerspectiveCamera();
  15793. cameraL.layers.enable( 1 );
  15794. cameraL.viewport = new Vector4();
  15795. const cameraR = new PerspectiveCamera();
  15796. cameraR.layers.enable( 2 );
  15797. cameraR.viewport = new Vector4();
  15798. const cameras = [ cameraL, cameraR ];
  15799. const cameraXR = new ArrayCamera();
  15800. cameraXR.layers.enable( 1 );
  15801. cameraXR.layers.enable( 2 );
  15802. let _currentDepthNear = null;
  15803. let _currentDepthFar = null;
  15804. //
  15805. this.cameraAutoUpdate = true;
  15806. this.enabled = false;
  15807. this.isPresenting = false;
  15808. this.getController = function ( index ) {
  15809. let controller = controllers[ index ];
  15810. if ( controller === undefined ) {
  15811. controller = new WebXRController();
  15812. controllers[ index ] = controller;
  15813. }
  15814. return controller.getTargetRaySpace();
  15815. };
  15816. this.getControllerGrip = function ( index ) {
  15817. let controller = controllers[ index ];
  15818. if ( controller === undefined ) {
  15819. controller = new WebXRController();
  15820. controllers[ index ] = controller;
  15821. }
  15822. return controller.getGripSpace();
  15823. };
  15824. this.getHand = function ( index ) {
  15825. let controller = controllers[ index ];
  15826. if ( controller === undefined ) {
  15827. controller = new WebXRController();
  15828. controllers[ index ] = controller;
  15829. }
  15830. return controller.getHandSpace();
  15831. };
  15832. //
  15833. function onSessionEvent( event ) {
  15834. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15835. if ( controllerIndex === - 1 ) {
  15836. return;
  15837. }
  15838. const controller = controllers[ controllerIndex ];
  15839. if ( controller !== undefined ) {
  15840. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  15841. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15842. }
  15843. }
  15844. function onSessionEnd() {
  15845. session.removeEventListener( 'select', onSessionEvent );
  15846. session.removeEventListener( 'selectstart', onSessionEvent );
  15847. session.removeEventListener( 'selectend', onSessionEvent );
  15848. session.removeEventListener( 'squeeze', onSessionEvent );
  15849. session.removeEventListener( 'squeezestart', onSessionEvent );
  15850. session.removeEventListener( 'squeezeend', onSessionEvent );
  15851. session.removeEventListener( 'end', onSessionEnd );
  15852. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15853. for ( let i = 0; i < controllers.length; i ++ ) {
  15854. const inputSource = controllerInputSources[ i ];
  15855. if ( inputSource === null ) continue;
  15856. controllerInputSources[ i ] = null;
  15857. controllers[ i ].disconnect( inputSource );
  15858. }
  15859. _currentDepthNear = null;
  15860. _currentDepthFar = null;
  15861. // restore framebuffer/rendering state
  15862. renderer.setRenderTarget( initialRenderTarget );
  15863. glBaseLayer = null;
  15864. glProjLayer = null;
  15865. glBinding = null;
  15866. session = null;
  15867. newRenderTarget = null;
  15868. //
  15869. animation.stop();
  15870. scope.isPresenting = false;
  15871. scope.dispatchEvent( { type: 'sessionend' } );
  15872. }
  15873. this.setFramebufferScaleFactor = function ( value ) {
  15874. framebufferScaleFactor = value;
  15875. if ( scope.isPresenting === true ) {
  15876. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15877. }
  15878. };
  15879. this.setReferenceSpaceType = function ( value ) {
  15880. referenceSpaceType = value;
  15881. if ( scope.isPresenting === true ) {
  15882. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15883. }
  15884. };
  15885. this.getReferenceSpace = function () {
  15886. return customReferenceSpace || referenceSpace;
  15887. };
  15888. this.setReferenceSpace = function ( space ) {
  15889. customReferenceSpace = space;
  15890. };
  15891. this.getBaseLayer = function () {
  15892. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15893. };
  15894. this.getBinding = function () {
  15895. return glBinding;
  15896. };
  15897. this.getFrame = function () {
  15898. return xrFrame;
  15899. };
  15900. this.getSession = function () {
  15901. return session;
  15902. };
  15903. this.setSession = async function ( value ) {
  15904. session = value;
  15905. if ( session !== null ) {
  15906. initialRenderTarget = renderer.getRenderTarget();
  15907. session.addEventListener( 'select', onSessionEvent );
  15908. session.addEventListener( 'selectstart', onSessionEvent );
  15909. session.addEventListener( 'selectend', onSessionEvent );
  15910. session.addEventListener( 'squeeze', onSessionEvent );
  15911. session.addEventListener( 'squeezestart', onSessionEvent );
  15912. session.addEventListener( 'squeezeend', onSessionEvent );
  15913. session.addEventListener( 'end', onSessionEnd );
  15914. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15915. if ( attributes.xrCompatible !== true ) {
  15916. await gl.makeXRCompatible();
  15917. }
  15918. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15919. const layerInit = {
  15920. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15921. alpha: true,
  15922. depth: attributes.depth,
  15923. stencil: attributes.stencil,
  15924. framebufferScaleFactor: framebufferScaleFactor
  15925. };
  15926. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15927. session.updateRenderState( { baseLayer: glBaseLayer } );
  15928. newRenderTarget = new WebGLRenderTarget(
  15929. glBaseLayer.framebufferWidth,
  15930. glBaseLayer.framebufferHeight,
  15931. {
  15932. format: RGBAFormat,
  15933. type: UnsignedByteType,
  15934. colorSpace: renderer.outputColorSpace,
  15935. stencilBuffer: attributes.stencil
  15936. }
  15937. );
  15938. } else {
  15939. let depthFormat = null;
  15940. let depthType = null;
  15941. let glDepthFormat = null;
  15942. if ( attributes.depth ) {
  15943. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15944. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15945. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15946. }
  15947. const projectionlayerInit = {
  15948. colorFormat: gl.RGBA8,
  15949. depthFormat: glDepthFormat,
  15950. scaleFactor: framebufferScaleFactor
  15951. };
  15952. glBinding = new XRWebGLBinding( session, gl );
  15953. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15954. session.updateRenderState( { layers: [ glProjLayer ] } );
  15955. newRenderTarget = new WebGLRenderTarget(
  15956. glProjLayer.textureWidth,
  15957. glProjLayer.textureHeight,
  15958. {
  15959. format: RGBAFormat,
  15960. type: UnsignedByteType,
  15961. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15962. stencilBuffer: attributes.stencil,
  15963. colorSpace: renderer.outputColorSpace,
  15964. samples: attributes.antialias ? 4 : 0
  15965. } );
  15966. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15967. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15968. }
  15969. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15970. this.setFoveation( foveation );
  15971. customReferenceSpace = null;
  15972. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15973. animation.setContext( session );
  15974. animation.start();
  15975. scope.isPresenting = true;
  15976. scope.dispatchEvent( { type: 'sessionstart' } );
  15977. }
  15978. };
  15979. this.getEnvironmentBlendMode = function () {
  15980. if ( session !== null ) {
  15981. return session.environmentBlendMode;
  15982. }
  15983. };
  15984. function onInputSourcesChange( event ) {
  15985. // Notify disconnected
  15986. for ( let i = 0; i < event.removed.length; i ++ ) {
  15987. const inputSource = event.removed[ i ];
  15988. const index = controllerInputSources.indexOf( inputSource );
  15989. if ( index >= 0 ) {
  15990. controllerInputSources[ index ] = null;
  15991. controllers[ index ].disconnect( inputSource );
  15992. }
  15993. }
  15994. // Notify connected
  15995. for ( let i = 0; i < event.added.length; i ++ ) {
  15996. const inputSource = event.added[ i ];
  15997. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15998. if ( controllerIndex === - 1 ) {
  15999. // Assign input source a controller that currently has no input source
  16000. for ( let i = 0; i < controllers.length; i ++ ) {
  16001. if ( i >= controllerInputSources.length ) {
  16002. controllerInputSources.push( inputSource );
  16003. controllerIndex = i;
  16004. break;
  16005. } else if ( controllerInputSources[ i ] === null ) {
  16006. controllerInputSources[ i ] = inputSource;
  16007. controllerIndex = i;
  16008. break;
  16009. }
  16010. }
  16011. // If all controllers do currently receive input we ignore new ones
  16012. if ( controllerIndex === - 1 ) break;
  16013. }
  16014. const controller = controllers[ controllerIndex ];
  16015. if ( controller ) {
  16016. controller.connect( inputSource );
  16017. }
  16018. }
  16019. }
  16020. //
  16021. const cameraLPos = new Vector3();
  16022. const cameraRPos = new Vector3();
  16023. /**
  16024. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16025. * the cameras' projection and world matrices have already been set.
  16026. * And that near and far planes are identical for both cameras.
  16027. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16028. */
  16029. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16030. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16031. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16032. const ipd = cameraLPos.distanceTo( cameraRPos );
  16033. const projL = cameraL.projectionMatrix.elements;
  16034. const projR = cameraR.projectionMatrix.elements;
  16035. // VR systems will have identical far and near planes, and
  16036. // most likely identical top and bottom frustum extents.
  16037. // Use the left camera for these values.
  16038. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16039. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16040. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16041. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16042. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16043. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16044. const left = near * leftFov;
  16045. const right = near * rightFov;
  16046. // Calculate the new camera's position offset from the
  16047. // left camera. xOffset should be roughly half `ipd`.
  16048. const zOffset = ipd / ( - leftFov + rightFov );
  16049. const xOffset = zOffset * - leftFov;
  16050. // TODO: Better way to apply this offset?
  16051. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16052. camera.translateX( xOffset );
  16053. camera.translateZ( zOffset );
  16054. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16055. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16056. // Find the union of the frustum values of the cameras and scale
  16057. // the values so that the near plane's position does not change in world space,
  16058. // although must now be relative to the new union camera.
  16059. const near2 = near + zOffset;
  16060. const far2 = far + zOffset;
  16061. const left2 = left - xOffset;
  16062. const right2 = right + ( ipd - xOffset );
  16063. const top2 = topFov * far / far2 * near2;
  16064. const bottom2 = bottomFov * far / far2 * near2;
  16065. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16066. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16067. }
  16068. function updateCamera( camera, parent ) {
  16069. if ( parent === null ) {
  16070. camera.matrixWorld.copy( camera.matrix );
  16071. } else {
  16072. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16073. }
  16074. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16075. }
  16076. this.updateCamera = function ( camera ) {
  16077. if ( session === null ) return;
  16078. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  16079. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  16080. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16081. // Note that the new renderState won't apply until the next frame. See #18320
  16082. session.updateRenderState( {
  16083. depthNear: cameraXR.near,
  16084. depthFar: cameraXR.far
  16085. } );
  16086. _currentDepthNear = cameraXR.near;
  16087. _currentDepthFar = cameraXR.far;
  16088. }
  16089. const parent = camera.parent;
  16090. const cameras = cameraXR.cameras;
  16091. updateCamera( cameraXR, parent );
  16092. for ( let i = 0; i < cameras.length; i ++ ) {
  16093. updateCamera( cameras[ i ], parent );
  16094. }
  16095. // update projection matrix for proper view frustum culling
  16096. if ( cameras.length === 2 ) {
  16097. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16098. } else {
  16099. // assume single camera setup (AR)
  16100. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16101. }
  16102. // update user camera and its children
  16103. updateUserCamera( camera, cameraXR, parent );
  16104. };
  16105. function updateUserCamera( camera, cameraXR, parent ) {
  16106. if ( parent === null ) {
  16107. camera.matrix.copy( cameraXR.matrixWorld );
  16108. } else {
  16109. camera.matrix.copy( parent.matrixWorld );
  16110. camera.matrix.invert();
  16111. camera.matrix.multiply( cameraXR.matrixWorld );
  16112. }
  16113. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16114. camera.updateMatrixWorld( true );
  16115. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16116. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16117. if ( camera.isPerspectiveCamera ) {
  16118. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16119. camera.zoom = 1;
  16120. }
  16121. }
  16122. this.getCamera = function () {
  16123. return cameraXR;
  16124. };
  16125. this.getFoveation = function () {
  16126. if ( glProjLayer === null && glBaseLayer === null ) {
  16127. return undefined;
  16128. }
  16129. return foveation;
  16130. };
  16131. this.setFoveation = function ( value ) {
  16132. // 0 = no foveation = full resolution
  16133. // 1 = maximum foveation = the edges render at lower resolution
  16134. foveation = value;
  16135. if ( glProjLayer !== null ) {
  16136. glProjLayer.fixedFoveation = value;
  16137. }
  16138. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16139. glBaseLayer.fixedFoveation = value;
  16140. }
  16141. };
  16142. // Animation Loop
  16143. let onAnimationFrameCallback = null;
  16144. function onAnimationFrame( time, frame ) {
  16145. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16146. xrFrame = frame;
  16147. if ( pose !== null ) {
  16148. const views = pose.views;
  16149. if ( glBaseLayer !== null ) {
  16150. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16151. renderer.setRenderTarget( newRenderTarget );
  16152. }
  16153. let cameraXRNeedsUpdate = false;
  16154. // check if it's necessary to rebuild cameraXR's camera list
  16155. if ( views.length !== cameraXR.cameras.length ) {
  16156. cameraXR.cameras.length = 0;
  16157. cameraXRNeedsUpdate = true;
  16158. }
  16159. for ( let i = 0; i < views.length; i ++ ) {
  16160. const view = views[ i ];
  16161. let viewport = null;
  16162. if ( glBaseLayer !== null ) {
  16163. viewport = glBaseLayer.getViewport( view );
  16164. } else {
  16165. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16166. viewport = glSubImage.viewport;
  16167. // For side-by-side projection, we only produce a single texture for both eyes.
  16168. if ( i === 0 ) {
  16169. renderer.setRenderTargetTextures(
  16170. newRenderTarget,
  16171. glSubImage.colorTexture,
  16172. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16173. renderer.setRenderTarget( newRenderTarget );
  16174. }
  16175. }
  16176. let camera = cameras[ i ];
  16177. if ( camera === undefined ) {
  16178. camera = new PerspectiveCamera();
  16179. camera.layers.enable( i );
  16180. camera.viewport = new Vector4();
  16181. cameras[ i ] = camera;
  16182. }
  16183. camera.matrix.fromArray( view.transform.matrix );
  16184. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16185. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16186. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16187. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16188. if ( i === 0 ) {
  16189. cameraXR.matrix.copy( camera.matrix );
  16190. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16191. }
  16192. if ( cameraXRNeedsUpdate === true ) {
  16193. cameraXR.cameras.push( camera );
  16194. }
  16195. }
  16196. }
  16197. //
  16198. for ( let i = 0; i < controllers.length; i ++ ) {
  16199. const inputSource = controllerInputSources[ i ];
  16200. const controller = controllers[ i ];
  16201. if ( inputSource !== null && controller !== undefined ) {
  16202. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16203. }
  16204. }
  16205. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16206. if ( frame.detectedPlanes ) {
  16207. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16208. }
  16209. xrFrame = null;
  16210. }
  16211. const animation = new WebGLAnimation();
  16212. animation.setAnimationLoop( onAnimationFrame );
  16213. this.setAnimationLoop = function ( callback ) {
  16214. onAnimationFrameCallback = callback;
  16215. };
  16216. this.dispose = function () {};
  16217. }
  16218. }
  16219. function WebGLMaterials( renderer, properties ) {
  16220. function refreshTransformUniform( map, uniform ) {
  16221. if ( map.matrixAutoUpdate === true ) {
  16222. map.updateMatrix();
  16223. }
  16224. uniform.value.copy( map.matrix );
  16225. }
  16226. function refreshFogUniforms( uniforms, fog ) {
  16227. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16228. if ( fog.isFog ) {
  16229. uniforms.fogNear.value = fog.near;
  16230. uniforms.fogFar.value = fog.far;
  16231. } else if ( fog.isFogExp2 ) {
  16232. uniforms.fogDensity.value = fog.density;
  16233. }
  16234. }
  16235. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16236. if ( material.isMeshBasicMaterial ) {
  16237. refreshUniformsCommon( uniforms, material );
  16238. } else if ( material.isMeshLambertMaterial ) {
  16239. refreshUniformsCommon( uniforms, material );
  16240. } else if ( material.isMeshToonMaterial ) {
  16241. refreshUniformsCommon( uniforms, material );
  16242. refreshUniformsToon( uniforms, material );
  16243. } else if ( material.isMeshPhongMaterial ) {
  16244. refreshUniformsCommon( uniforms, material );
  16245. refreshUniformsPhong( uniforms, material );
  16246. } else if ( material.isMeshStandardMaterial ) {
  16247. refreshUniformsCommon( uniforms, material );
  16248. refreshUniformsStandard( uniforms, material );
  16249. if ( material.isMeshPhysicalMaterial ) {
  16250. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16251. }
  16252. } else if ( material.isMeshMatcapMaterial ) {
  16253. refreshUniformsCommon( uniforms, material );
  16254. refreshUniformsMatcap( uniforms, material );
  16255. } else if ( material.isMeshDepthMaterial ) {
  16256. refreshUniformsCommon( uniforms, material );
  16257. } else if ( material.isMeshDistanceMaterial ) {
  16258. refreshUniformsCommon( uniforms, material );
  16259. refreshUniformsDistance( uniforms, material );
  16260. } else if ( material.isMeshNormalMaterial ) {
  16261. refreshUniformsCommon( uniforms, material );
  16262. } else if ( material.isLineBasicMaterial ) {
  16263. refreshUniformsLine( uniforms, material );
  16264. if ( material.isLineDashedMaterial ) {
  16265. refreshUniformsDash( uniforms, material );
  16266. }
  16267. } else if ( material.isPointsMaterial ) {
  16268. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16269. } else if ( material.isSpriteMaterial ) {
  16270. refreshUniformsSprites( uniforms, material );
  16271. } else if ( material.isShadowMaterial ) {
  16272. uniforms.color.value.copy( material.color );
  16273. uniforms.opacity.value = material.opacity;
  16274. } else if ( material.isShaderMaterial ) {
  16275. material.uniformsNeedUpdate = false; // #15581
  16276. }
  16277. }
  16278. function refreshUniformsCommon( uniforms, material ) {
  16279. uniforms.opacity.value = material.opacity;
  16280. if ( material.color ) {
  16281. uniforms.diffuse.value.copy( material.color );
  16282. }
  16283. if ( material.emissive ) {
  16284. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16285. }
  16286. if ( material.map ) {
  16287. uniforms.map.value = material.map;
  16288. refreshTransformUniform( material.map, uniforms.mapTransform );
  16289. }
  16290. if ( material.alphaMap ) {
  16291. uniforms.alphaMap.value = material.alphaMap;
  16292. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16293. }
  16294. if ( material.bumpMap ) {
  16295. uniforms.bumpMap.value = material.bumpMap;
  16296. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16297. uniforms.bumpScale.value = material.bumpScale;
  16298. if ( material.side === BackSide ) {
  16299. uniforms.bumpScale.value *= - 1;
  16300. }
  16301. }
  16302. if ( material.normalMap ) {
  16303. uniforms.normalMap.value = material.normalMap;
  16304. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16305. uniforms.normalScale.value.copy( material.normalScale );
  16306. if ( material.side === BackSide ) {
  16307. uniforms.normalScale.value.negate();
  16308. }
  16309. }
  16310. if ( material.displacementMap ) {
  16311. uniforms.displacementMap.value = material.displacementMap;
  16312. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16313. uniforms.displacementScale.value = material.displacementScale;
  16314. uniforms.displacementBias.value = material.displacementBias;
  16315. }
  16316. if ( material.emissiveMap ) {
  16317. uniforms.emissiveMap.value = material.emissiveMap;
  16318. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16319. }
  16320. if ( material.specularMap ) {
  16321. uniforms.specularMap.value = material.specularMap;
  16322. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16323. }
  16324. if ( material.alphaTest > 0 ) {
  16325. uniforms.alphaTest.value = material.alphaTest;
  16326. }
  16327. const envMap = properties.get( material ).envMap;
  16328. if ( envMap ) {
  16329. uniforms.envMap.value = envMap;
  16330. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16331. uniforms.reflectivity.value = material.reflectivity;
  16332. uniforms.ior.value = material.ior;
  16333. uniforms.refractionRatio.value = material.refractionRatio;
  16334. }
  16335. if ( material.lightMap ) {
  16336. uniforms.lightMap.value = material.lightMap;
  16337. // artist-friendly light intensity scaling factor
  16338. const scaleFactor = ( renderer._useLegacyLights === true ) ? Math.PI : 1;
  16339. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16340. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16341. }
  16342. if ( material.aoMap ) {
  16343. uniforms.aoMap.value = material.aoMap;
  16344. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16345. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16346. }
  16347. }
  16348. function refreshUniformsLine( uniforms, material ) {
  16349. uniforms.diffuse.value.copy( material.color );
  16350. uniforms.opacity.value = material.opacity;
  16351. if ( material.map ) {
  16352. uniforms.map.value = material.map;
  16353. refreshTransformUniform( material.map, uniforms.mapTransform );
  16354. }
  16355. }
  16356. function refreshUniformsDash( uniforms, material ) {
  16357. uniforms.dashSize.value = material.dashSize;
  16358. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16359. uniforms.scale.value = material.scale;
  16360. }
  16361. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16362. uniforms.diffuse.value.copy( material.color );
  16363. uniforms.opacity.value = material.opacity;
  16364. uniforms.size.value = material.size * pixelRatio;
  16365. uniforms.scale.value = height * 0.5;
  16366. if ( material.map ) {
  16367. uniforms.map.value = material.map;
  16368. refreshTransformUniform( material.map, uniforms.uvTransform );
  16369. }
  16370. if ( material.alphaMap ) {
  16371. uniforms.alphaMap.value = material.alphaMap;
  16372. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16373. }
  16374. if ( material.alphaTest > 0 ) {
  16375. uniforms.alphaTest.value = material.alphaTest;
  16376. }
  16377. }
  16378. function refreshUniformsSprites( uniforms, material ) {
  16379. uniforms.diffuse.value.copy( material.color );
  16380. uniforms.opacity.value = material.opacity;
  16381. uniforms.rotation.value = material.rotation;
  16382. if ( material.map ) {
  16383. uniforms.map.value = material.map;
  16384. refreshTransformUniform( material.map, uniforms.mapTransform );
  16385. }
  16386. if ( material.alphaMap ) {
  16387. uniforms.alphaMap.value = material.alphaMap;
  16388. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16389. }
  16390. if ( material.alphaTest > 0 ) {
  16391. uniforms.alphaTest.value = material.alphaTest;
  16392. }
  16393. }
  16394. function refreshUniformsPhong( uniforms, material ) {
  16395. uniforms.specular.value.copy( material.specular );
  16396. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16397. }
  16398. function refreshUniformsToon( uniforms, material ) {
  16399. if ( material.gradientMap ) {
  16400. uniforms.gradientMap.value = material.gradientMap;
  16401. }
  16402. }
  16403. function refreshUniformsStandard( uniforms, material ) {
  16404. uniforms.metalness.value = material.metalness;
  16405. if ( material.metalnessMap ) {
  16406. uniforms.metalnessMap.value = material.metalnessMap;
  16407. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16408. }
  16409. uniforms.roughness.value = material.roughness;
  16410. if ( material.roughnessMap ) {
  16411. uniforms.roughnessMap.value = material.roughnessMap;
  16412. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16413. }
  16414. const envMap = properties.get( material ).envMap;
  16415. if ( envMap ) {
  16416. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16417. uniforms.envMapIntensity.value = material.envMapIntensity;
  16418. }
  16419. }
  16420. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16421. uniforms.ior.value = material.ior; // also part of uniforms common
  16422. if ( material.sheen > 0 ) {
  16423. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16424. uniforms.sheenRoughness.value = material.sheenRoughness;
  16425. if ( material.sheenColorMap ) {
  16426. uniforms.sheenColorMap.value = material.sheenColorMap;
  16427. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16428. }
  16429. if ( material.sheenRoughnessMap ) {
  16430. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16431. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16432. }
  16433. }
  16434. if ( material.clearcoat > 0 ) {
  16435. uniforms.clearcoat.value = material.clearcoat;
  16436. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16437. if ( material.clearcoatMap ) {
  16438. uniforms.clearcoatMap.value = material.clearcoatMap;
  16439. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16440. }
  16441. if ( material.clearcoatRoughnessMap ) {
  16442. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16443. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16444. }
  16445. if ( material.clearcoatNormalMap ) {
  16446. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16447. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16448. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16449. if ( material.side === BackSide ) {
  16450. uniforms.clearcoatNormalScale.value.negate();
  16451. }
  16452. }
  16453. }
  16454. if ( material.iridescence > 0 ) {
  16455. uniforms.iridescence.value = material.iridescence;
  16456. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16457. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16458. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16459. if ( material.iridescenceMap ) {
  16460. uniforms.iridescenceMap.value = material.iridescenceMap;
  16461. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16462. }
  16463. if ( material.iridescenceThicknessMap ) {
  16464. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16465. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16466. }
  16467. }
  16468. if ( material.transmission > 0 ) {
  16469. uniforms.transmission.value = material.transmission;
  16470. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16471. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16472. if ( material.transmissionMap ) {
  16473. uniforms.transmissionMap.value = material.transmissionMap;
  16474. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16475. }
  16476. uniforms.thickness.value = material.thickness;
  16477. if ( material.thicknessMap ) {
  16478. uniforms.thicknessMap.value = material.thicknessMap;
  16479. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16480. }
  16481. uniforms.attenuationDistance.value = material.attenuationDistance;
  16482. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16483. }
  16484. if ( material.anisotropy > 0 ) {
  16485. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16486. if ( material.anisotropyMap ) {
  16487. uniforms.anisotropyMap.value = material.anisotropyMap;
  16488. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16489. }
  16490. }
  16491. uniforms.specularIntensity.value = material.specularIntensity;
  16492. uniforms.specularColor.value.copy( material.specularColor );
  16493. if ( material.specularColorMap ) {
  16494. uniforms.specularColorMap.value = material.specularColorMap;
  16495. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16496. }
  16497. if ( material.specularIntensityMap ) {
  16498. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16499. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16500. }
  16501. }
  16502. function refreshUniformsMatcap( uniforms, material ) {
  16503. if ( material.matcap ) {
  16504. uniforms.matcap.value = material.matcap;
  16505. }
  16506. }
  16507. function refreshUniformsDistance( uniforms, material ) {
  16508. const light = properties.get( material ).light;
  16509. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16510. uniforms.nearDistance.value = light.shadow.camera.near;
  16511. uniforms.farDistance.value = light.shadow.camera.far;
  16512. }
  16513. return {
  16514. refreshFogUniforms: refreshFogUniforms,
  16515. refreshMaterialUniforms: refreshMaterialUniforms
  16516. };
  16517. }
  16518. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16519. let buffers = {};
  16520. let updateList = {};
  16521. let allocatedBindingPoints = [];
  16522. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  16523. function bind( uniformsGroup, program ) {
  16524. const webglProgram = program.program;
  16525. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16526. }
  16527. function update( uniformsGroup, program ) {
  16528. let buffer = buffers[ uniformsGroup.id ];
  16529. if ( buffer === undefined ) {
  16530. prepareUniformsGroup( uniformsGroup );
  16531. buffer = createBuffer( uniformsGroup );
  16532. buffers[ uniformsGroup.id ] = buffer;
  16533. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16534. }
  16535. // ensure to update the binding points/block indices mapping for this program
  16536. const webglProgram = program.program;
  16537. state.updateUBOMapping( uniformsGroup, webglProgram );
  16538. // update UBO once per frame
  16539. const frame = info.render.frame;
  16540. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16541. updateBufferData( uniformsGroup );
  16542. updateList[ uniformsGroup.id ] = frame;
  16543. }
  16544. }
  16545. function createBuffer( uniformsGroup ) {
  16546. // the setup of an UBO is independent of a particular shader program but global
  16547. const bindingPointIndex = allocateBindingPointIndex();
  16548. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16549. const buffer = gl.createBuffer();
  16550. const size = uniformsGroup.__size;
  16551. const usage = uniformsGroup.usage;
  16552. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16553. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16554. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16555. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16556. return buffer;
  16557. }
  16558. function allocateBindingPointIndex() {
  16559. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16560. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16561. allocatedBindingPoints.push( i );
  16562. return i;
  16563. }
  16564. }
  16565. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16566. return 0;
  16567. }
  16568. function updateBufferData( uniformsGroup ) {
  16569. const buffer = buffers[ uniformsGroup.id ];
  16570. const uniforms = uniformsGroup.uniforms;
  16571. const cache = uniformsGroup.__cache;
  16572. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16573. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16574. const uniform = uniforms[ i ];
  16575. // partly update the buffer if necessary
  16576. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16577. const offset = uniform.__offset;
  16578. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16579. let arrayOffset = 0;
  16580. for ( let i = 0; i < values.length; i ++ ) {
  16581. const value = values[ i ];
  16582. const info = getUniformSize( value );
  16583. if ( typeof value === 'number' ) {
  16584. uniform.__data[ 0 ] = value;
  16585. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16586. } else if ( value.isMatrix3 ) {
  16587. // manually converting 3x3 to 3x4
  16588. uniform.__data[ 0 ] = value.elements[ 0 ];
  16589. uniform.__data[ 1 ] = value.elements[ 1 ];
  16590. uniform.__data[ 2 ] = value.elements[ 2 ];
  16591. uniform.__data[ 3 ] = value.elements[ 0 ];
  16592. uniform.__data[ 4 ] = value.elements[ 3 ];
  16593. uniform.__data[ 5 ] = value.elements[ 4 ];
  16594. uniform.__data[ 6 ] = value.elements[ 5 ];
  16595. uniform.__data[ 7 ] = value.elements[ 0 ];
  16596. uniform.__data[ 8 ] = value.elements[ 6 ];
  16597. uniform.__data[ 9 ] = value.elements[ 7 ];
  16598. uniform.__data[ 10 ] = value.elements[ 8 ];
  16599. uniform.__data[ 11 ] = value.elements[ 0 ];
  16600. } else {
  16601. value.toArray( uniform.__data, arrayOffset );
  16602. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16603. }
  16604. }
  16605. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16606. }
  16607. }
  16608. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16609. }
  16610. function hasUniformChanged( uniform, index, cache ) {
  16611. const value = uniform.value;
  16612. if ( cache[ index ] === undefined ) {
  16613. // cache entry does not exist so far
  16614. if ( typeof value === 'number' ) {
  16615. cache[ index ] = value;
  16616. } else {
  16617. const values = Array.isArray( value ) ? value : [ value ];
  16618. const tempValues = [];
  16619. for ( let i = 0; i < values.length; i ++ ) {
  16620. tempValues.push( values[ i ].clone() );
  16621. }
  16622. cache[ index ] = tempValues;
  16623. }
  16624. return true;
  16625. } else {
  16626. // compare current value with cached entry
  16627. if ( typeof value === 'number' ) {
  16628. if ( cache[ index ] !== value ) {
  16629. cache[ index ] = value;
  16630. return true;
  16631. }
  16632. } else {
  16633. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16634. const values = Array.isArray( value ) ? value : [ value ];
  16635. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16636. const cachedObject = cachedObjects[ i ];
  16637. if ( cachedObject.equals( values[ i ] ) === false ) {
  16638. cachedObject.copy( values[ i ] );
  16639. return true;
  16640. }
  16641. }
  16642. }
  16643. }
  16644. return false;
  16645. }
  16646. function prepareUniformsGroup( uniformsGroup ) {
  16647. // determine total buffer size according to the STD140 layout
  16648. // Hint: STD140 is the only supported layout in WebGL 2
  16649. const uniforms = uniformsGroup.uniforms;
  16650. let offset = 0; // global buffer offset in bytes
  16651. const chunkSize = 16; // size of a chunk in bytes
  16652. let chunkOffset = 0; // offset within a single chunk in bytes
  16653. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16654. const uniform = uniforms[ i ];
  16655. const infos = {
  16656. boundary: 0, // bytes
  16657. storage: 0 // bytes
  16658. };
  16659. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16660. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16661. const value = values[ j ];
  16662. const info = getUniformSize( value );
  16663. infos.boundary += info.boundary;
  16664. infos.storage += info.storage;
  16665. }
  16666. // the following two properties will be used for partial buffer updates
  16667. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16668. uniform.__offset = offset;
  16669. //
  16670. if ( i > 0 ) {
  16671. chunkOffset = offset % chunkSize;
  16672. const remainingSizeInChunk = chunkSize - chunkOffset;
  16673. // check for chunk overflow
  16674. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16675. // add padding and adjust offset
  16676. offset += ( chunkSize - chunkOffset );
  16677. uniform.__offset = offset;
  16678. }
  16679. }
  16680. offset += infos.storage;
  16681. }
  16682. // ensure correct final padding
  16683. chunkOffset = offset % chunkSize;
  16684. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16685. //
  16686. uniformsGroup.__size = offset;
  16687. uniformsGroup.__cache = {};
  16688. return this;
  16689. }
  16690. function getUniformSize( value ) {
  16691. const info = {
  16692. boundary: 0, // bytes
  16693. storage: 0 // bytes
  16694. };
  16695. // determine sizes according to STD140
  16696. if ( typeof value === 'number' ) {
  16697. // float/int
  16698. info.boundary = 4;
  16699. info.storage = 4;
  16700. } else if ( value.isVector2 ) {
  16701. // vec2
  16702. info.boundary = 8;
  16703. info.storage = 8;
  16704. } else if ( value.isVector3 || value.isColor ) {
  16705. // vec3
  16706. info.boundary = 16;
  16707. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16708. } else if ( value.isVector4 ) {
  16709. // vec4
  16710. info.boundary = 16;
  16711. info.storage = 16;
  16712. } else if ( value.isMatrix3 ) {
  16713. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16714. info.boundary = 48;
  16715. info.storage = 48;
  16716. } else if ( value.isMatrix4 ) {
  16717. // mat4
  16718. info.boundary = 64;
  16719. info.storage = 64;
  16720. } else if ( value.isTexture ) {
  16721. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16722. } else {
  16723. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16724. }
  16725. return info;
  16726. }
  16727. function onUniformsGroupsDispose( event ) {
  16728. const uniformsGroup = event.target;
  16729. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16730. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16731. allocatedBindingPoints.splice( index, 1 );
  16732. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16733. delete buffers[ uniformsGroup.id ];
  16734. delete updateList[ uniformsGroup.id ];
  16735. }
  16736. function dispose() {
  16737. for ( const id in buffers ) {
  16738. gl.deleteBuffer( buffers[ id ] );
  16739. }
  16740. allocatedBindingPoints = [];
  16741. buffers = {};
  16742. updateList = {};
  16743. }
  16744. return {
  16745. bind: bind,
  16746. update: update,
  16747. dispose: dispose
  16748. };
  16749. }
  16750. class WebGLRenderer {
  16751. constructor( parameters = {} ) {
  16752. const {
  16753. canvas = createCanvasElement(),
  16754. context = null,
  16755. depth = true,
  16756. stencil = true,
  16757. alpha = false,
  16758. antialias = false,
  16759. premultipliedAlpha = true,
  16760. preserveDrawingBuffer = false,
  16761. powerPreference = 'default',
  16762. failIfMajorPerformanceCaveat = false,
  16763. } = parameters;
  16764. this.isWebGLRenderer = true;
  16765. let _alpha;
  16766. if ( context !== null ) {
  16767. _alpha = context.getContextAttributes().alpha;
  16768. } else {
  16769. _alpha = alpha;
  16770. }
  16771. const uintClearColor = new Uint32Array( 4 );
  16772. const intClearColor = new Int32Array( 4 );
  16773. let currentRenderList = null;
  16774. let currentRenderState = null;
  16775. // render() can be called from within a callback triggered by another render.
  16776. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16777. const renderListStack = [];
  16778. const renderStateStack = [];
  16779. // public properties
  16780. this.domElement = canvas;
  16781. // Debug configuration container
  16782. this.debug = {
  16783. /**
  16784. * Enables error checking and reporting when shader programs are being compiled
  16785. * @type {boolean}
  16786. */
  16787. checkShaderErrors: true,
  16788. /**
  16789. * Callback for custom error reporting.
  16790. * @type {?Function}
  16791. */
  16792. onShaderError: null
  16793. };
  16794. // clearing
  16795. this.autoClear = true;
  16796. this.autoClearColor = true;
  16797. this.autoClearDepth = true;
  16798. this.autoClearStencil = true;
  16799. // scene graph
  16800. this.sortObjects = true;
  16801. // user-defined clipping
  16802. this.clippingPlanes = [];
  16803. this.localClippingEnabled = false;
  16804. // physically based shading
  16805. this._outputColorSpace = SRGBColorSpace;
  16806. // physical lights
  16807. this._useLegacyLights = false;
  16808. // tone mapping
  16809. this.toneMapping = NoToneMapping;
  16810. this.toneMappingExposure = 1.0;
  16811. // internal properties
  16812. const _this = this;
  16813. let _isContextLost = false;
  16814. // internal state cache
  16815. let _currentActiveCubeFace = 0;
  16816. let _currentActiveMipmapLevel = 0;
  16817. let _currentRenderTarget = null;
  16818. let _currentMaterialId = - 1;
  16819. let _currentCamera = null;
  16820. const _currentViewport = new Vector4();
  16821. const _currentScissor = new Vector4();
  16822. let _currentScissorTest = null;
  16823. const _currentClearColor = new Color( 0x000000 );
  16824. let _currentClearAlpha = 0;
  16825. //
  16826. let _width = canvas.width;
  16827. let _height = canvas.height;
  16828. let _pixelRatio = 1;
  16829. let _opaqueSort = null;
  16830. let _transparentSort = null;
  16831. const _viewport = new Vector4( 0, 0, _width, _height );
  16832. const _scissor = new Vector4( 0, 0, _width, _height );
  16833. let _scissorTest = false;
  16834. // frustum
  16835. const _frustum = new Frustum();
  16836. // clipping
  16837. let _clippingEnabled = false;
  16838. let _localClippingEnabled = false;
  16839. // transmission
  16840. let _transmissionRenderTarget = null;
  16841. // camera matrices cache
  16842. const _projScreenMatrix = new Matrix4();
  16843. const _vector2 = new Vector2();
  16844. const _vector3 = new Vector3();
  16845. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16846. function getTargetPixelRatio() {
  16847. return _currentRenderTarget === null ? _pixelRatio : 1;
  16848. }
  16849. // initialize
  16850. let _gl = context;
  16851. function getContext( contextNames, contextAttributes ) {
  16852. for ( let i = 0; i < contextNames.length; i ++ ) {
  16853. const contextName = contextNames[ i ];
  16854. const context = canvas.getContext( contextName, contextAttributes );
  16855. if ( context !== null ) return context;
  16856. }
  16857. return null;
  16858. }
  16859. try {
  16860. const contextAttributes = {
  16861. alpha: true,
  16862. depth,
  16863. stencil,
  16864. antialias,
  16865. premultipliedAlpha,
  16866. preserveDrawingBuffer,
  16867. powerPreference,
  16868. failIfMajorPerformanceCaveat,
  16869. };
  16870. // OffscreenCanvas does not have setAttribute, see #22811
  16871. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16872. // event listeners must be registered before WebGL context is created, see #12753
  16873. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16874. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16875. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16876. if ( _gl === null ) {
  16877. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16878. if ( _this.isWebGL1Renderer === true ) {
  16879. contextNames.shift();
  16880. }
  16881. _gl = getContext( contextNames, contextAttributes );
  16882. if ( _gl === null ) {
  16883. if ( getContext( contextNames ) ) {
  16884. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16885. } else {
  16886. throw new Error( 'Error creating WebGL context.' );
  16887. }
  16888. }
  16889. }
  16890. if ( typeof WebGLRenderingContext !== 'undefined' && _gl instanceof WebGLRenderingContext ) { // @deprecated, r153
  16891. console.warn( 'THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163.' );
  16892. }
  16893. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16894. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16895. _gl.getShaderPrecisionFormat = function () {
  16896. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16897. };
  16898. }
  16899. } catch ( error ) {
  16900. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16901. throw error;
  16902. }
  16903. let extensions, capabilities, state, info;
  16904. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16905. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16906. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16907. let utils, bindingStates, uniformsGroups;
  16908. function initGLContext() {
  16909. extensions = new WebGLExtensions( _gl );
  16910. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16911. extensions.init( capabilities );
  16912. utils = new WebGLUtils( _gl, extensions, capabilities );
  16913. state = new WebGLState( _gl, extensions, capabilities );
  16914. info = new WebGLInfo( _gl );
  16915. properties = new WebGLProperties();
  16916. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16917. cubemaps = new WebGLCubeMaps( _this );
  16918. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16919. attributes = new WebGLAttributes( _gl, capabilities );
  16920. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16921. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16922. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16923. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16924. clipping = new WebGLClipping( properties );
  16925. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16926. materials = new WebGLMaterials( _this, properties );
  16927. renderLists = new WebGLRenderLists();
  16928. renderStates = new WebGLRenderStates( extensions, capabilities );
  16929. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16930. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16931. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16932. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16933. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16934. info.programs = programCache.programs;
  16935. _this.capabilities = capabilities;
  16936. _this.extensions = extensions;
  16937. _this.properties = properties;
  16938. _this.renderLists = renderLists;
  16939. _this.shadowMap = shadowMap;
  16940. _this.state = state;
  16941. _this.info = info;
  16942. }
  16943. initGLContext();
  16944. // xr
  16945. const xr = new WebXRManager( _this, _gl );
  16946. this.xr = xr;
  16947. // API
  16948. this.getContext = function () {
  16949. return _gl;
  16950. };
  16951. this.getContextAttributes = function () {
  16952. return _gl.getContextAttributes();
  16953. };
  16954. this.forceContextLoss = function () {
  16955. const extension = extensions.get( 'WEBGL_lose_context' );
  16956. if ( extension ) extension.loseContext();
  16957. };
  16958. this.forceContextRestore = function () {
  16959. const extension = extensions.get( 'WEBGL_lose_context' );
  16960. if ( extension ) extension.restoreContext();
  16961. };
  16962. this.getPixelRatio = function () {
  16963. return _pixelRatio;
  16964. };
  16965. this.setPixelRatio = function ( value ) {
  16966. if ( value === undefined ) return;
  16967. _pixelRatio = value;
  16968. this.setSize( _width, _height, false );
  16969. };
  16970. this.getSize = function ( target ) {
  16971. return target.set( _width, _height );
  16972. };
  16973. this.setSize = function ( width, height, updateStyle = true ) {
  16974. if ( xr.isPresenting ) {
  16975. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16976. return;
  16977. }
  16978. _width = width;
  16979. _height = height;
  16980. canvas.width = Math.floor( width * _pixelRatio );
  16981. canvas.height = Math.floor( height * _pixelRatio );
  16982. if ( updateStyle === true ) {
  16983. canvas.style.width = width + 'px';
  16984. canvas.style.height = height + 'px';
  16985. }
  16986. this.setViewport( 0, 0, width, height );
  16987. };
  16988. this.getDrawingBufferSize = function ( target ) {
  16989. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16990. };
  16991. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16992. _width = width;
  16993. _height = height;
  16994. _pixelRatio = pixelRatio;
  16995. canvas.width = Math.floor( width * pixelRatio );
  16996. canvas.height = Math.floor( height * pixelRatio );
  16997. this.setViewport( 0, 0, width, height );
  16998. };
  16999. this.getCurrentViewport = function ( target ) {
  17000. return target.copy( _currentViewport );
  17001. };
  17002. this.getViewport = function ( target ) {
  17003. return target.copy( _viewport );
  17004. };
  17005. this.setViewport = function ( x, y, width, height ) {
  17006. if ( x.isVector4 ) {
  17007. _viewport.set( x.x, x.y, x.z, x.w );
  17008. } else {
  17009. _viewport.set( x, y, width, height );
  17010. }
  17011. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  17012. };
  17013. this.getScissor = function ( target ) {
  17014. return target.copy( _scissor );
  17015. };
  17016. this.setScissor = function ( x, y, width, height ) {
  17017. if ( x.isVector4 ) {
  17018. _scissor.set( x.x, x.y, x.z, x.w );
  17019. } else {
  17020. _scissor.set( x, y, width, height );
  17021. }
  17022. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  17023. };
  17024. this.getScissorTest = function () {
  17025. return _scissorTest;
  17026. };
  17027. this.setScissorTest = function ( boolean ) {
  17028. state.setScissorTest( _scissorTest = boolean );
  17029. };
  17030. this.setOpaqueSort = function ( method ) {
  17031. _opaqueSort = method;
  17032. };
  17033. this.setTransparentSort = function ( method ) {
  17034. _transparentSort = method;
  17035. };
  17036. // Clearing
  17037. this.getClearColor = function ( target ) {
  17038. return target.copy( background.getClearColor() );
  17039. };
  17040. this.setClearColor = function () {
  17041. background.setClearColor.apply( background, arguments );
  17042. };
  17043. this.getClearAlpha = function () {
  17044. return background.getClearAlpha();
  17045. };
  17046. this.setClearAlpha = function () {
  17047. background.setClearAlpha.apply( background, arguments );
  17048. };
  17049. this.clear = function ( color = true, depth = true, stencil = true ) {
  17050. let bits = 0;
  17051. if ( color ) {
  17052. // check if we're trying to clear an integer target
  17053. let isIntegerFormat = false;
  17054. if ( _currentRenderTarget !== null ) {
  17055. const targetFormat = _currentRenderTarget.texture.format;
  17056. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17057. targetFormat === RGIntegerFormat ||
  17058. targetFormat === RedIntegerFormat;
  17059. }
  17060. // use the appropriate clear functions to clear the target if it's a signed
  17061. // or unsigned integer target
  17062. if ( isIntegerFormat ) {
  17063. const targetType = _currentRenderTarget.texture.type;
  17064. const isUnsignedType = targetType === UnsignedByteType ||
  17065. targetType === UnsignedIntType ||
  17066. targetType === UnsignedShortType ||
  17067. targetType === UnsignedInt248Type ||
  17068. targetType === UnsignedShort4444Type ||
  17069. targetType === UnsignedShort5551Type;
  17070. const clearColor = background.getClearColor();
  17071. const a = background.getClearAlpha();
  17072. const r = clearColor.r;
  17073. const g = clearColor.g;
  17074. const b = clearColor.b;
  17075. if ( isUnsignedType ) {
  17076. uintClearColor[ 0 ] = r;
  17077. uintClearColor[ 1 ] = g;
  17078. uintClearColor[ 2 ] = b;
  17079. uintClearColor[ 3 ] = a;
  17080. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17081. } else {
  17082. intClearColor[ 0 ] = r;
  17083. intClearColor[ 1 ] = g;
  17084. intClearColor[ 2 ] = b;
  17085. intClearColor[ 3 ] = a;
  17086. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17087. }
  17088. } else {
  17089. bits |= _gl.COLOR_BUFFER_BIT;
  17090. }
  17091. }
  17092. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17093. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  17094. _gl.clear( bits );
  17095. };
  17096. this.clearColor = function () {
  17097. this.clear( true, false, false );
  17098. };
  17099. this.clearDepth = function () {
  17100. this.clear( false, true, false );
  17101. };
  17102. this.clearStencil = function () {
  17103. this.clear( false, false, true );
  17104. };
  17105. //
  17106. this.dispose = function () {
  17107. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17108. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17109. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17110. renderLists.dispose();
  17111. renderStates.dispose();
  17112. properties.dispose();
  17113. cubemaps.dispose();
  17114. cubeuvmaps.dispose();
  17115. objects.dispose();
  17116. bindingStates.dispose();
  17117. uniformsGroups.dispose();
  17118. programCache.dispose();
  17119. xr.dispose();
  17120. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17121. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17122. if ( _transmissionRenderTarget ) {
  17123. _transmissionRenderTarget.dispose();
  17124. _transmissionRenderTarget = null;
  17125. }
  17126. animation.stop();
  17127. };
  17128. // Events
  17129. function onContextLost( event ) {
  17130. event.preventDefault();
  17131. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17132. _isContextLost = true;
  17133. }
  17134. function onContextRestore( /* event */ ) {
  17135. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17136. _isContextLost = false;
  17137. const infoAutoReset = info.autoReset;
  17138. const shadowMapEnabled = shadowMap.enabled;
  17139. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17140. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17141. const shadowMapType = shadowMap.type;
  17142. initGLContext();
  17143. info.autoReset = infoAutoReset;
  17144. shadowMap.enabled = shadowMapEnabled;
  17145. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17146. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17147. shadowMap.type = shadowMapType;
  17148. }
  17149. function onContextCreationError( event ) {
  17150. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17151. }
  17152. function onMaterialDispose( event ) {
  17153. const material = event.target;
  17154. material.removeEventListener( 'dispose', onMaterialDispose );
  17155. deallocateMaterial( material );
  17156. }
  17157. // Buffer deallocation
  17158. function deallocateMaterial( material ) {
  17159. releaseMaterialProgramReferences( material );
  17160. properties.remove( material );
  17161. }
  17162. function releaseMaterialProgramReferences( material ) {
  17163. const programs = properties.get( material ).programs;
  17164. if ( programs !== undefined ) {
  17165. programs.forEach( function ( program ) {
  17166. programCache.releaseProgram( program );
  17167. } );
  17168. if ( material.isShaderMaterial ) {
  17169. programCache.releaseShaderCache( material );
  17170. }
  17171. }
  17172. }
  17173. // Buffer rendering
  17174. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17175. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17176. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17177. const program = setProgram( camera, scene, geometry, material, object );
  17178. state.setMaterial( material, frontFaceCW );
  17179. //
  17180. let index = geometry.index;
  17181. let rangeFactor = 1;
  17182. if ( material.wireframe === true ) {
  17183. index = geometries.getWireframeAttribute( geometry );
  17184. if ( index === undefined ) return;
  17185. rangeFactor = 2;
  17186. }
  17187. //
  17188. const drawRange = geometry.drawRange;
  17189. const position = geometry.attributes.position;
  17190. let drawStart = drawRange.start * rangeFactor;
  17191. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17192. if ( group !== null ) {
  17193. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17194. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17195. }
  17196. if ( index !== null ) {
  17197. drawStart = Math.max( drawStart, 0 );
  17198. drawEnd = Math.min( drawEnd, index.count );
  17199. } else if ( position !== undefined && position !== null ) {
  17200. drawStart = Math.max( drawStart, 0 );
  17201. drawEnd = Math.min( drawEnd, position.count );
  17202. }
  17203. const drawCount = drawEnd - drawStart;
  17204. if ( drawCount < 0 || drawCount === Infinity ) return;
  17205. //
  17206. bindingStates.setup( object, material, program, geometry, index );
  17207. let attribute;
  17208. let renderer = bufferRenderer;
  17209. if ( index !== null ) {
  17210. attribute = attributes.get( index );
  17211. renderer = indexedBufferRenderer;
  17212. renderer.setIndex( attribute );
  17213. }
  17214. //
  17215. if ( object.isMesh ) {
  17216. if ( material.wireframe === true ) {
  17217. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17218. renderer.setMode( _gl.LINES );
  17219. } else {
  17220. renderer.setMode( _gl.TRIANGLES );
  17221. }
  17222. } else if ( object.isLine ) {
  17223. let lineWidth = material.linewidth;
  17224. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17225. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17226. if ( object.isLineSegments ) {
  17227. renderer.setMode( _gl.LINES );
  17228. } else if ( object.isLineLoop ) {
  17229. renderer.setMode( _gl.LINE_LOOP );
  17230. } else {
  17231. renderer.setMode( _gl.LINE_STRIP );
  17232. }
  17233. } else if ( object.isPoints ) {
  17234. renderer.setMode( _gl.POINTS );
  17235. } else if ( object.isSprite ) {
  17236. renderer.setMode( _gl.TRIANGLES );
  17237. }
  17238. if ( object.isInstancedMesh ) {
  17239. renderer.renderInstances( drawStart, drawCount, object.count );
  17240. } else if ( geometry.isInstancedBufferGeometry ) {
  17241. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17242. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17243. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17244. } else {
  17245. renderer.render( drawStart, drawCount );
  17246. }
  17247. };
  17248. // Compile
  17249. this.compile = function ( scene, camera ) {
  17250. function prepare( material, scene, object ) {
  17251. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17252. material.side = BackSide;
  17253. material.needsUpdate = true;
  17254. getProgram( material, scene, object );
  17255. material.side = FrontSide;
  17256. material.needsUpdate = true;
  17257. getProgram( material, scene, object );
  17258. material.side = DoubleSide;
  17259. } else {
  17260. getProgram( material, scene, object );
  17261. }
  17262. }
  17263. currentRenderState = renderStates.get( scene );
  17264. currentRenderState.init();
  17265. renderStateStack.push( currentRenderState );
  17266. scene.traverseVisible( function ( object ) {
  17267. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17268. currentRenderState.pushLight( object );
  17269. if ( object.castShadow ) {
  17270. currentRenderState.pushShadow( object );
  17271. }
  17272. }
  17273. } );
  17274. currentRenderState.setupLights( _this._useLegacyLights );
  17275. scene.traverse( function ( object ) {
  17276. const material = object.material;
  17277. if ( material ) {
  17278. if ( Array.isArray( material ) ) {
  17279. for ( let i = 0; i < material.length; i ++ ) {
  17280. const material2 = material[ i ];
  17281. prepare( material2, scene, object );
  17282. }
  17283. } else {
  17284. prepare( material, scene, object );
  17285. }
  17286. }
  17287. } );
  17288. renderStateStack.pop();
  17289. currentRenderState = null;
  17290. };
  17291. // Animation Loop
  17292. let onAnimationFrameCallback = null;
  17293. function onAnimationFrame( time ) {
  17294. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17295. }
  17296. function onXRSessionStart() {
  17297. animation.stop();
  17298. }
  17299. function onXRSessionEnd() {
  17300. animation.start();
  17301. }
  17302. const animation = new WebGLAnimation();
  17303. animation.setAnimationLoop( onAnimationFrame );
  17304. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17305. this.setAnimationLoop = function ( callback ) {
  17306. onAnimationFrameCallback = callback;
  17307. xr.setAnimationLoop( callback );
  17308. ( callback === null ) ? animation.stop() : animation.start();
  17309. };
  17310. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17311. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17312. // Rendering
  17313. this.render = function ( scene, camera ) {
  17314. if ( camera !== undefined && camera.isCamera !== true ) {
  17315. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17316. return;
  17317. }
  17318. if ( _isContextLost === true ) return;
  17319. // update scene graph
  17320. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17321. // update camera matrices and frustum
  17322. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17323. if ( xr.enabled === true && xr.isPresenting === true ) {
  17324. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17325. camera = xr.getCamera(); // use XR camera for rendering
  17326. }
  17327. //
  17328. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17329. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17330. currentRenderState.init();
  17331. renderStateStack.push( currentRenderState );
  17332. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17333. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17334. _localClippingEnabled = this.localClippingEnabled;
  17335. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17336. currentRenderList = renderLists.get( scene, renderListStack.length );
  17337. currentRenderList.init();
  17338. renderListStack.push( currentRenderList );
  17339. projectObject( scene, camera, 0, _this.sortObjects );
  17340. currentRenderList.finish();
  17341. if ( _this.sortObjects === true ) {
  17342. currentRenderList.sort( _opaqueSort, _transparentSort );
  17343. }
  17344. //
  17345. this.info.render.frame ++;
  17346. if ( _clippingEnabled === true ) clipping.beginShadows();
  17347. const shadowsArray = currentRenderState.state.shadowsArray;
  17348. shadowMap.render( shadowsArray, scene, camera );
  17349. if ( _clippingEnabled === true ) clipping.endShadows();
  17350. //
  17351. if ( this.info.autoReset === true ) this.info.reset();
  17352. //
  17353. background.render( currentRenderList, scene );
  17354. // render scene
  17355. currentRenderState.setupLights( _this._useLegacyLights );
  17356. if ( camera.isArrayCamera ) {
  17357. const cameras = camera.cameras;
  17358. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17359. const camera2 = cameras[ i ];
  17360. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17361. }
  17362. } else {
  17363. renderScene( currentRenderList, scene, camera );
  17364. }
  17365. //
  17366. if ( _currentRenderTarget !== null ) {
  17367. // resolve multisample renderbuffers to a single-sample texture if necessary
  17368. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17369. // Generate mipmap if we're using any kind of mipmap filtering
  17370. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17371. }
  17372. //
  17373. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17374. // _gl.finish();
  17375. bindingStates.resetDefaultState();
  17376. _currentMaterialId = - 1;
  17377. _currentCamera = null;
  17378. renderStateStack.pop();
  17379. if ( renderStateStack.length > 0 ) {
  17380. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17381. } else {
  17382. currentRenderState = null;
  17383. }
  17384. renderListStack.pop();
  17385. if ( renderListStack.length > 0 ) {
  17386. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17387. } else {
  17388. currentRenderList = null;
  17389. }
  17390. };
  17391. function projectObject( object, camera, groupOrder, sortObjects ) {
  17392. if ( object.visible === false ) return;
  17393. const visible = object.layers.test( camera.layers );
  17394. if ( visible ) {
  17395. if ( object.isGroup ) {
  17396. groupOrder = object.renderOrder;
  17397. } else if ( object.isLOD ) {
  17398. if ( object.autoUpdate === true ) object.update( camera );
  17399. } else if ( object.isLight ) {
  17400. currentRenderState.pushLight( object );
  17401. if ( object.castShadow ) {
  17402. currentRenderState.pushShadow( object );
  17403. }
  17404. } else if ( object.isSprite ) {
  17405. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17406. if ( sortObjects ) {
  17407. _vector3.setFromMatrixPosition( object.matrixWorld )
  17408. .applyMatrix4( _projScreenMatrix );
  17409. }
  17410. const geometry = objects.update( object );
  17411. const material = object.material;
  17412. if ( material.visible ) {
  17413. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17414. }
  17415. }
  17416. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17417. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17418. const geometry = objects.update( object );
  17419. const material = object.material;
  17420. if ( sortObjects ) {
  17421. if ( object.boundingSphere !== undefined ) {
  17422. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17423. _vector3.copy( object.boundingSphere.center );
  17424. } else {
  17425. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17426. _vector3.copy( geometry.boundingSphere.center );
  17427. }
  17428. _vector3
  17429. .applyMatrix4( object.matrixWorld )
  17430. .applyMatrix4( _projScreenMatrix );
  17431. }
  17432. if ( Array.isArray( material ) ) {
  17433. const groups = geometry.groups;
  17434. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17435. const group = groups[ i ];
  17436. const groupMaterial = material[ group.materialIndex ];
  17437. if ( groupMaterial && groupMaterial.visible ) {
  17438. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17439. }
  17440. }
  17441. } else if ( material.visible ) {
  17442. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17443. }
  17444. }
  17445. }
  17446. }
  17447. const children = object.children;
  17448. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17449. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17450. }
  17451. }
  17452. function renderScene( currentRenderList, scene, camera, viewport ) {
  17453. const opaqueObjects = currentRenderList.opaque;
  17454. const transmissiveObjects = currentRenderList.transmissive;
  17455. const transparentObjects = currentRenderList.transparent;
  17456. currentRenderState.setupLightsView( camera );
  17457. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17458. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17459. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17460. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17461. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17462. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17463. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17464. state.buffers.depth.setTest( true );
  17465. state.buffers.depth.setMask( true );
  17466. state.buffers.color.setMask( true );
  17467. state.setPolygonOffset( false );
  17468. }
  17469. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17470. const isWebGL2 = capabilities.isWebGL2;
  17471. if ( _transmissionRenderTarget === null ) {
  17472. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  17473. generateMipmaps: true,
  17474. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17475. minFilter: LinearMipmapLinearFilter,
  17476. samples: ( isWebGL2 ) ? 4 : 0
  17477. } );
  17478. // debug
  17479. /*
  17480. const geometry = new PlaneGeometry();
  17481. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17482. const mesh = new Mesh( geometry, material );
  17483. scene.add( mesh );
  17484. */
  17485. }
  17486. _this.getDrawingBufferSize( _vector2 );
  17487. if ( isWebGL2 ) {
  17488. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  17489. } else {
  17490. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  17491. }
  17492. //
  17493. const currentRenderTarget = _this.getRenderTarget();
  17494. _this.setRenderTarget( _transmissionRenderTarget );
  17495. _this.getClearColor( _currentClearColor );
  17496. _currentClearAlpha = _this.getClearAlpha();
  17497. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17498. _this.clear();
  17499. // Turn off the features which can affect the frag color for opaque objects pass.
  17500. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17501. const currentToneMapping = _this.toneMapping;
  17502. _this.toneMapping = NoToneMapping;
  17503. renderObjects( opaqueObjects, scene, camera );
  17504. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17505. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17506. let renderTargetNeedsUpdate = false;
  17507. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17508. const renderItem = transmissiveObjects[ i ];
  17509. const object = renderItem.object;
  17510. const geometry = renderItem.geometry;
  17511. const material = renderItem.material;
  17512. const group = renderItem.group;
  17513. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17514. const currentSide = material.side;
  17515. material.side = BackSide;
  17516. material.needsUpdate = true;
  17517. renderObject( object, scene, camera, geometry, material, group );
  17518. material.side = currentSide;
  17519. material.needsUpdate = true;
  17520. renderTargetNeedsUpdate = true;
  17521. }
  17522. }
  17523. if ( renderTargetNeedsUpdate === true ) {
  17524. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17525. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17526. }
  17527. _this.setRenderTarget( currentRenderTarget );
  17528. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17529. _this.toneMapping = currentToneMapping;
  17530. }
  17531. function renderObjects( renderList, scene, camera ) {
  17532. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17533. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17534. const renderItem = renderList[ i ];
  17535. const object = renderItem.object;
  17536. const geometry = renderItem.geometry;
  17537. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17538. const group = renderItem.group;
  17539. if ( object.layers.test( camera.layers ) ) {
  17540. renderObject( object, scene, camera, geometry, material, group );
  17541. }
  17542. }
  17543. }
  17544. function renderObject( object, scene, camera, geometry, material, group ) {
  17545. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17546. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17547. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17548. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17549. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17550. material.side = BackSide;
  17551. material.needsUpdate = true;
  17552. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17553. material.side = FrontSide;
  17554. material.needsUpdate = true;
  17555. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17556. material.side = DoubleSide;
  17557. } else {
  17558. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17559. }
  17560. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17561. }
  17562. function getProgram( material, scene, object ) {
  17563. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17564. const materialProperties = properties.get( material );
  17565. const lights = currentRenderState.state.lights;
  17566. const shadowsArray = currentRenderState.state.shadowsArray;
  17567. const lightsStateVersion = lights.state.version;
  17568. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17569. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17570. let programs = materialProperties.programs;
  17571. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17572. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17573. materialProperties.fog = scene.fog;
  17574. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17575. if ( programs === undefined ) {
  17576. // new material
  17577. material.addEventListener( 'dispose', onMaterialDispose );
  17578. programs = new Map();
  17579. materialProperties.programs = programs;
  17580. }
  17581. let program = programs.get( programCacheKey );
  17582. if ( program !== undefined ) {
  17583. // early out if program and light state is identical
  17584. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17585. updateCommonMaterialProperties( material, parameters );
  17586. return program;
  17587. }
  17588. } else {
  17589. parameters.uniforms = programCache.getUniforms( material );
  17590. material.onBuild( object, parameters, _this );
  17591. material.onBeforeCompile( parameters, _this );
  17592. program = programCache.acquireProgram( parameters, programCacheKey );
  17593. programs.set( programCacheKey, program );
  17594. materialProperties.uniforms = parameters.uniforms;
  17595. }
  17596. const uniforms = materialProperties.uniforms;
  17597. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17598. uniforms.clippingPlanes = clipping.uniform;
  17599. }
  17600. updateCommonMaterialProperties( material, parameters );
  17601. // store the light setup it was created for
  17602. materialProperties.needsLights = materialNeedsLights( material );
  17603. materialProperties.lightsStateVersion = lightsStateVersion;
  17604. if ( materialProperties.needsLights ) {
  17605. // wire up the material to this renderer's lighting state
  17606. uniforms.ambientLightColor.value = lights.state.ambient;
  17607. uniforms.lightProbe.value = lights.state.probe;
  17608. uniforms.directionalLights.value = lights.state.directional;
  17609. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17610. uniforms.spotLights.value = lights.state.spot;
  17611. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17612. uniforms.rectAreaLights.value = lights.state.rectArea;
  17613. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17614. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17615. uniforms.pointLights.value = lights.state.point;
  17616. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17617. uniforms.hemisphereLights.value = lights.state.hemi;
  17618. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17619. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17620. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17621. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17622. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17623. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17624. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17625. // TODO (abelnation): add area lights shadow info to uniforms
  17626. }
  17627. const progUniforms = program.getUniforms();
  17628. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17629. materialProperties.currentProgram = program;
  17630. materialProperties.uniformsList = uniformsList;
  17631. return program;
  17632. }
  17633. function updateCommonMaterialProperties( material, parameters ) {
  17634. const materialProperties = properties.get( material );
  17635. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17636. materialProperties.instancing = parameters.instancing;
  17637. materialProperties.instancingColor = parameters.instancingColor;
  17638. materialProperties.skinning = parameters.skinning;
  17639. materialProperties.morphTargets = parameters.morphTargets;
  17640. materialProperties.morphNormals = parameters.morphNormals;
  17641. materialProperties.morphColors = parameters.morphColors;
  17642. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17643. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17644. materialProperties.numIntersection = parameters.numClipIntersection;
  17645. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17646. materialProperties.vertexTangents = parameters.vertexTangents;
  17647. materialProperties.toneMapping = parameters.toneMapping;
  17648. }
  17649. function setProgram( camera, scene, geometry, material, object ) {
  17650. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17651. textures.resetTextureUnits();
  17652. const fog = scene.fog;
  17653. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17654. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17655. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17656. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17657. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  17658. const morphTargets = !! geometry.morphAttributes.position;
  17659. const morphNormals = !! geometry.morphAttributes.normal;
  17660. const morphColors = !! geometry.morphAttributes.color;
  17661. let toneMapping = NoToneMapping;
  17662. if ( material.toneMapped ) {
  17663. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  17664. toneMapping = _this.toneMapping;
  17665. }
  17666. }
  17667. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17668. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17669. const materialProperties = properties.get( material );
  17670. const lights = currentRenderState.state.lights;
  17671. if ( _clippingEnabled === true ) {
  17672. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17673. const useCache =
  17674. camera === _currentCamera &&
  17675. material.id === _currentMaterialId;
  17676. // we might want to call this function with some ClippingGroup
  17677. // object instead of the material, once it becomes feasible
  17678. // (#8465, #8379)
  17679. clipping.setState( material, camera, useCache );
  17680. }
  17681. }
  17682. //
  17683. let needsProgramChange = false;
  17684. if ( material.version === materialProperties.__version ) {
  17685. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17686. needsProgramChange = true;
  17687. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17688. needsProgramChange = true;
  17689. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17690. needsProgramChange = true;
  17691. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17692. needsProgramChange = true;
  17693. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17694. needsProgramChange = true;
  17695. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17696. needsProgramChange = true;
  17697. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  17698. needsProgramChange = true;
  17699. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  17700. needsProgramChange = true;
  17701. } else if ( materialProperties.envMap !== envMap ) {
  17702. needsProgramChange = true;
  17703. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17704. needsProgramChange = true;
  17705. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17706. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17707. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17708. needsProgramChange = true;
  17709. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17710. needsProgramChange = true;
  17711. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17712. needsProgramChange = true;
  17713. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17714. needsProgramChange = true;
  17715. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17716. needsProgramChange = true;
  17717. } else if ( materialProperties.morphColors !== morphColors ) {
  17718. needsProgramChange = true;
  17719. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17720. needsProgramChange = true;
  17721. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17722. needsProgramChange = true;
  17723. }
  17724. } else {
  17725. needsProgramChange = true;
  17726. materialProperties.__version = material.version;
  17727. }
  17728. //
  17729. let program = materialProperties.currentProgram;
  17730. if ( needsProgramChange === true ) {
  17731. program = getProgram( material, scene, object );
  17732. }
  17733. let refreshProgram = false;
  17734. let refreshMaterial = false;
  17735. let refreshLights = false;
  17736. const p_uniforms = program.getUniforms(),
  17737. m_uniforms = materialProperties.uniforms;
  17738. if ( state.useProgram( program.program ) ) {
  17739. refreshProgram = true;
  17740. refreshMaterial = true;
  17741. refreshLights = true;
  17742. }
  17743. if ( material.id !== _currentMaterialId ) {
  17744. _currentMaterialId = material.id;
  17745. refreshMaterial = true;
  17746. }
  17747. if ( refreshProgram || _currentCamera !== camera ) {
  17748. // common camera uniforms
  17749. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17750. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17751. const uCamPos = p_uniforms.map.cameraPosition;
  17752. if ( uCamPos !== undefined ) {
  17753. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17754. }
  17755. if ( capabilities.logarithmicDepthBuffer ) {
  17756. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17757. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17758. }
  17759. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  17760. if ( material.isMeshPhongMaterial ||
  17761. material.isMeshToonMaterial ||
  17762. material.isMeshLambertMaterial ||
  17763. material.isMeshBasicMaterial ||
  17764. material.isMeshStandardMaterial ||
  17765. material.isShaderMaterial ) {
  17766. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17767. }
  17768. if ( _currentCamera !== camera ) {
  17769. _currentCamera = camera;
  17770. // lighting uniforms depend on the camera so enforce an update
  17771. // now, in case this material supports lights - or later, when
  17772. // the next material that does gets activated:
  17773. refreshMaterial = true; // set to true on material change
  17774. refreshLights = true; // remains set until update done
  17775. }
  17776. }
  17777. // skinning and morph target uniforms must be set even if material didn't change
  17778. // auto-setting of texture unit for bone and morph texture must go before other textures
  17779. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17780. if ( object.isSkinnedMesh ) {
  17781. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17782. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17783. const skeleton = object.skeleton;
  17784. if ( skeleton ) {
  17785. if ( capabilities.floatVertexTextures ) {
  17786. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17787. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17788. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17789. } else {
  17790. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17791. }
  17792. }
  17793. }
  17794. const morphAttributes = geometry.morphAttributes;
  17795. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17796. morphtargets.update( object, geometry, program );
  17797. }
  17798. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17799. materialProperties.receiveShadow = object.receiveShadow;
  17800. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17801. }
  17802. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17803. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17804. m_uniforms.envMap.value = envMap;
  17805. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17806. }
  17807. if ( refreshMaterial ) {
  17808. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17809. if ( materialProperties.needsLights ) {
  17810. // the current material requires lighting info
  17811. // note: all lighting uniforms are always set correctly
  17812. // they simply reference the renderer's state for their
  17813. // values
  17814. //
  17815. // use the current material's .needsUpdate flags to set
  17816. // the GL state when required
  17817. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17818. }
  17819. // refresh uniforms common to several materials
  17820. if ( fog && material.fog === true ) {
  17821. materials.refreshFogUniforms( m_uniforms, fog );
  17822. }
  17823. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17824. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17825. }
  17826. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17827. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17828. material.uniformsNeedUpdate = false;
  17829. }
  17830. if ( material.isSpriteMaterial ) {
  17831. p_uniforms.setValue( _gl, 'center', object.center );
  17832. }
  17833. // common matrices
  17834. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17835. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17836. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17837. // UBOs
  17838. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17839. const groups = material.uniformsGroups;
  17840. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17841. if ( capabilities.isWebGL2 ) {
  17842. const group = groups[ i ];
  17843. uniformsGroups.update( group, program );
  17844. uniformsGroups.bind( group, program );
  17845. } else {
  17846. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17847. }
  17848. }
  17849. }
  17850. return program;
  17851. }
  17852. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17853. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17854. uniforms.ambientLightColor.needsUpdate = value;
  17855. uniforms.lightProbe.needsUpdate = value;
  17856. uniforms.directionalLights.needsUpdate = value;
  17857. uniforms.directionalLightShadows.needsUpdate = value;
  17858. uniforms.pointLights.needsUpdate = value;
  17859. uniforms.pointLightShadows.needsUpdate = value;
  17860. uniforms.spotLights.needsUpdate = value;
  17861. uniforms.spotLightShadows.needsUpdate = value;
  17862. uniforms.rectAreaLights.needsUpdate = value;
  17863. uniforms.hemisphereLights.needsUpdate = value;
  17864. }
  17865. function materialNeedsLights( material ) {
  17866. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17867. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17868. ( material.isShaderMaterial && material.lights === true );
  17869. }
  17870. this.getActiveCubeFace = function () {
  17871. return _currentActiveCubeFace;
  17872. };
  17873. this.getActiveMipmapLevel = function () {
  17874. return _currentActiveMipmapLevel;
  17875. };
  17876. this.getRenderTarget = function () {
  17877. return _currentRenderTarget;
  17878. };
  17879. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17880. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17881. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17882. const renderTargetProperties = properties.get( renderTarget );
  17883. renderTargetProperties.__hasExternalTextures = true;
  17884. if ( renderTargetProperties.__hasExternalTextures ) {
  17885. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17886. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17887. // The multisample_render_to_texture extension doesn't work properly if there
  17888. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17889. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17890. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17891. renderTargetProperties.__useRenderToTexture = false;
  17892. }
  17893. }
  17894. }
  17895. };
  17896. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17897. const renderTargetProperties = properties.get( renderTarget );
  17898. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17899. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17900. };
  17901. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17902. _currentRenderTarget = renderTarget;
  17903. _currentActiveCubeFace = activeCubeFace;
  17904. _currentActiveMipmapLevel = activeMipmapLevel;
  17905. let useDefaultFramebuffer = true;
  17906. let framebuffer = null;
  17907. let isCube = false;
  17908. let isRenderTarget3D = false;
  17909. if ( renderTarget ) {
  17910. const renderTargetProperties = properties.get( renderTarget );
  17911. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17912. // We need to make sure to rebind the framebuffer.
  17913. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17914. useDefaultFramebuffer = false;
  17915. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17916. textures.setupRenderTarget( renderTarget );
  17917. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17918. // Color and depth texture must be rebound in order for the swapchain to update.
  17919. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17920. }
  17921. const texture = renderTarget.texture;
  17922. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17923. isRenderTarget3D = true;
  17924. }
  17925. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17926. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17927. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  17928. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  17929. } else {
  17930. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17931. }
  17932. isCube = true;
  17933. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17934. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17935. } else {
  17936. if ( Array.isArray( __webglFramebuffer ) ) {
  17937. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  17938. } else {
  17939. framebuffer = __webglFramebuffer;
  17940. }
  17941. }
  17942. _currentViewport.copy( renderTarget.viewport );
  17943. _currentScissor.copy( renderTarget.scissor );
  17944. _currentScissorTest = renderTarget.scissorTest;
  17945. } else {
  17946. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17947. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17948. _currentScissorTest = _scissorTest;
  17949. }
  17950. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17951. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17952. state.drawBuffers( renderTarget, framebuffer );
  17953. }
  17954. state.viewport( _currentViewport );
  17955. state.scissor( _currentScissor );
  17956. state.setScissorTest( _currentScissorTest );
  17957. if ( isCube ) {
  17958. const textureProperties = properties.get( renderTarget.texture );
  17959. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17960. } else if ( isRenderTarget3D ) {
  17961. const textureProperties = properties.get( renderTarget.texture );
  17962. const layer = activeCubeFace || 0;
  17963. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17964. }
  17965. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17966. };
  17967. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17968. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17969. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17970. return;
  17971. }
  17972. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17973. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17974. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17975. }
  17976. if ( framebuffer ) {
  17977. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17978. try {
  17979. const texture = renderTarget.texture;
  17980. const textureFormat = texture.format;
  17981. const textureType = texture.type;
  17982. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17983. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17984. return;
  17985. }
  17986. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17987. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17988. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17989. ! halfFloatSupportedByExt ) {
  17990. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17991. return;
  17992. }
  17993. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17994. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17995. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17996. }
  17997. } finally {
  17998. // restore framebuffer of current render target if necessary
  17999. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18000. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18001. }
  18002. }
  18003. };
  18004. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  18005. const levelScale = Math.pow( 2, - level );
  18006. const width = Math.floor( texture.image.width * levelScale );
  18007. const height = Math.floor( texture.image.height * levelScale );
  18008. textures.setTexture2D( texture, 0 );
  18009. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  18010. state.unbindTexture();
  18011. };
  18012. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  18013. const width = srcTexture.image.width;
  18014. const height = srcTexture.image.height;
  18015. const glFormat = utils.convert( dstTexture.format );
  18016. const glType = utils.convert( dstTexture.type );
  18017. textures.setTexture2D( dstTexture, 0 );
  18018. // As another texture upload may have changed pixelStorei
  18019. // parameters, make sure they are correct for the dstTexture
  18020. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18021. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18022. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18023. if ( srcTexture.isDataTexture ) {
  18024. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  18025. } else {
  18026. if ( srcTexture.isCompressedTexture ) {
  18027. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  18028. } else {
  18029. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  18030. }
  18031. }
  18032. // Generate mipmaps only when copying level 0
  18033. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18034. state.unbindTexture();
  18035. };
  18036. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  18037. if ( _this.isWebGL1Renderer ) {
  18038. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  18039. return;
  18040. }
  18041. const width = sourceBox.max.x - sourceBox.min.x + 1;
  18042. const height = sourceBox.max.y - sourceBox.min.y + 1;
  18043. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  18044. const glFormat = utils.convert( dstTexture.format );
  18045. const glType = utils.convert( dstTexture.type );
  18046. let glTarget;
  18047. if ( dstTexture.isData3DTexture ) {
  18048. textures.setTexture3D( dstTexture, 0 );
  18049. glTarget = _gl.TEXTURE_3D;
  18050. } else if ( dstTexture.isDataArrayTexture ) {
  18051. textures.setTexture2DArray( dstTexture, 0 );
  18052. glTarget = _gl.TEXTURE_2D_ARRAY;
  18053. } else {
  18054. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18055. return;
  18056. }
  18057. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18058. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18059. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18060. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18061. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18062. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18063. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18064. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18065. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  18066. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18067. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18068. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  18069. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  18070. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  18071. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18072. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  18073. } else {
  18074. if ( srcTexture.isCompressedArrayTexture ) {
  18075. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  18076. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  18077. } else {
  18078. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  18079. }
  18080. }
  18081. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  18082. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  18083. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  18084. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  18085. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  18086. // Generate mipmaps only when copying level 0
  18087. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18088. state.unbindTexture();
  18089. };
  18090. this.initTexture = function ( texture ) {
  18091. if ( texture.isCubeTexture ) {
  18092. textures.setTextureCube( texture, 0 );
  18093. } else if ( texture.isData3DTexture ) {
  18094. textures.setTexture3D( texture, 0 );
  18095. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18096. textures.setTexture2DArray( texture, 0 );
  18097. } else {
  18098. textures.setTexture2D( texture, 0 );
  18099. }
  18100. state.unbindTexture();
  18101. };
  18102. this.resetState = function () {
  18103. _currentActiveCubeFace = 0;
  18104. _currentActiveMipmapLevel = 0;
  18105. _currentRenderTarget = null;
  18106. state.reset();
  18107. bindingStates.reset();
  18108. };
  18109. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18110. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18111. }
  18112. }
  18113. get coordinateSystem() {
  18114. return WebGLCoordinateSystem;
  18115. }
  18116. get outputColorSpace() {
  18117. return this._outputColorSpace;
  18118. }
  18119. set outputColorSpace( colorSpace ) {
  18120. this._outputColorSpace = colorSpace;
  18121. const gl = this.getContext();
  18122. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18123. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18124. }
  18125. get physicallyCorrectLights() { // @deprecated, r150
  18126. console.warn( 'THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  18127. return ! this.useLegacyLights;
  18128. }
  18129. set physicallyCorrectLights( value ) { // @deprecated, r150
  18130. console.warn( 'THREE.WebGLRenderer: The property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  18131. this.useLegacyLights = ! value;
  18132. }
  18133. get outputEncoding() { // @deprecated, r152
  18134. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18135. return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  18136. }
  18137. set outputEncoding( encoding ) { // @deprecated, r152
  18138. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18139. this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  18140. }
  18141. get useLegacyLights() { // @deprecated, r155
  18142. 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.' );
  18143. return this._useLegacyLights;
  18144. }
  18145. set useLegacyLights( value ) { // @deprecated, r155
  18146. 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.' );
  18147. this._useLegacyLights = value;
  18148. }
  18149. }
  18150. class WebGL1Renderer extends WebGLRenderer {}
  18151. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  18152. class FogExp2 {
  18153. constructor( color, density = 0.00025 ) {
  18154. this.isFogExp2 = true;
  18155. this.name = '';
  18156. this.color = new Color( color );
  18157. this.density = density;
  18158. }
  18159. clone() {
  18160. return new FogExp2( this.color, this.density );
  18161. }
  18162. toJSON( /* meta */ ) {
  18163. return {
  18164. type: 'FogExp2',
  18165. name: this.name,
  18166. color: this.color.getHex(),
  18167. density: this.density
  18168. };
  18169. }
  18170. }
  18171. class Fog {
  18172. constructor( color, near = 1, far = 1000 ) {
  18173. this.isFog = true;
  18174. this.name = '';
  18175. this.color = new Color( color );
  18176. this.near = near;
  18177. this.far = far;
  18178. }
  18179. clone() {
  18180. return new Fog( this.color, this.near, this.far );
  18181. }
  18182. toJSON( /* meta */ ) {
  18183. return {
  18184. type: 'Fog',
  18185. name: this.name,
  18186. color: this.color.getHex(),
  18187. near: this.near,
  18188. far: this.far
  18189. };
  18190. }
  18191. }
  18192. class Scene extends Object3D {
  18193. constructor() {
  18194. super();
  18195. this.isScene = true;
  18196. this.type = 'Scene';
  18197. this.background = null;
  18198. this.environment = null;
  18199. this.fog = null;
  18200. this.backgroundBlurriness = 0;
  18201. this.backgroundIntensity = 1;
  18202. this.overrideMaterial = null;
  18203. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18204. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18205. }
  18206. }
  18207. copy( source, recursive ) {
  18208. super.copy( source, recursive );
  18209. if ( source.background !== null ) this.background = source.background.clone();
  18210. if ( source.environment !== null ) this.environment = source.environment.clone();
  18211. if ( source.fog !== null ) this.fog = source.fog.clone();
  18212. this.backgroundBlurriness = source.backgroundBlurriness;
  18213. this.backgroundIntensity = source.backgroundIntensity;
  18214. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18215. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18216. return this;
  18217. }
  18218. toJSON( meta ) {
  18219. const data = super.toJSON( meta );
  18220. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18221. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18222. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18223. return data;
  18224. }
  18225. }
  18226. class InterleavedBuffer {
  18227. constructor( array, stride ) {
  18228. this.isInterleavedBuffer = true;
  18229. this.array = array;
  18230. this.stride = stride;
  18231. this.count = array !== undefined ? array.length / stride : 0;
  18232. this.usage = StaticDrawUsage;
  18233. this.updateRange = { offset: 0, count: - 1 };
  18234. this.version = 0;
  18235. this.uuid = generateUUID();
  18236. }
  18237. onUploadCallback() {}
  18238. set needsUpdate( value ) {
  18239. if ( value === true ) this.version ++;
  18240. }
  18241. setUsage( value ) {
  18242. this.usage = value;
  18243. return this;
  18244. }
  18245. copy( source ) {
  18246. this.array = new source.array.constructor( source.array );
  18247. this.count = source.count;
  18248. this.stride = source.stride;
  18249. this.usage = source.usage;
  18250. return this;
  18251. }
  18252. copyAt( index1, attribute, index2 ) {
  18253. index1 *= this.stride;
  18254. index2 *= attribute.stride;
  18255. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18256. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18257. }
  18258. return this;
  18259. }
  18260. set( value, offset = 0 ) {
  18261. this.array.set( value, offset );
  18262. return this;
  18263. }
  18264. clone( data ) {
  18265. if ( data.arrayBuffers === undefined ) {
  18266. data.arrayBuffers = {};
  18267. }
  18268. if ( this.array.buffer._uuid === undefined ) {
  18269. this.array.buffer._uuid = generateUUID();
  18270. }
  18271. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18272. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18273. }
  18274. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18275. const ib = new this.constructor( array, this.stride );
  18276. ib.setUsage( this.usage );
  18277. return ib;
  18278. }
  18279. onUpload( callback ) {
  18280. this.onUploadCallback = callback;
  18281. return this;
  18282. }
  18283. toJSON( data ) {
  18284. if ( data.arrayBuffers === undefined ) {
  18285. data.arrayBuffers = {};
  18286. }
  18287. // generate UUID for array buffer if necessary
  18288. if ( this.array.buffer._uuid === undefined ) {
  18289. this.array.buffer._uuid = generateUUID();
  18290. }
  18291. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18292. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18293. }
  18294. //
  18295. return {
  18296. uuid: this.uuid,
  18297. buffer: this.array.buffer._uuid,
  18298. type: this.array.constructor.name,
  18299. stride: this.stride
  18300. };
  18301. }
  18302. }
  18303. const _vector$5 = /*@__PURE__*/ new Vector3();
  18304. class InterleavedBufferAttribute {
  18305. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18306. this.isInterleavedBufferAttribute = true;
  18307. this.name = '';
  18308. this.data = interleavedBuffer;
  18309. this.itemSize = itemSize;
  18310. this.offset = offset;
  18311. this.normalized = normalized;
  18312. }
  18313. get count() {
  18314. return this.data.count;
  18315. }
  18316. get array() {
  18317. return this.data.array;
  18318. }
  18319. set needsUpdate( value ) {
  18320. this.data.needsUpdate = value;
  18321. }
  18322. applyMatrix4( m ) {
  18323. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18324. _vector$5.fromBufferAttribute( this, i );
  18325. _vector$5.applyMatrix4( m );
  18326. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18327. }
  18328. return this;
  18329. }
  18330. applyNormalMatrix( m ) {
  18331. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18332. _vector$5.fromBufferAttribute( this, i );
  18333. _vector$5.applyNormalMatrix( m );
  18334. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18335. }
  18336. return this;
  18337. }
  18338. transformDirection( m ) {
  18339. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18340. _vector$5.fromBufferAttribute( this, i );
  18341. _vector$5.transformDirection( m );
  18342. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18343. }
  18344. return this;
  18345. }
  18346. setX( index, x ) {
  18347. if ( this.normalized ) x = normalize( x, this.array );
  18348. this.data.array[ index * this.data.stride + this.offset ] = x;
  18349. return this;
  18350. }
  18351. setY( index, y ) {
  18352. if ( this.normalized ) y = normalize( y, this.array );
  18353. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18354. return this;
  18355. }
  18356. setZ( index, z ) {
  18357. if ( this.normalized ) z = normalize( z, this.array );
  18358. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18359. return this;
  18360. }
  18361. setW( index, w ) {
  18362. if ( this.normalized ) w = normalize( w, this.array );
  18363. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18364. return this;
  18365. }
  18366. getX( index ) {
  18367. let x = this.data.array[ index * this.data.stride + this.offset ];
  18368. if ( this.normalized ) x = denormalize( x, this.array );
  18369. return x;
  18370. }
  18371. getY( index ) {
  18372. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18373. if ( this.normalized ) y = denormalize( y, this.array );
  18374. return y;
  18375. }
  18376. getZ( index ) {
  18377. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18378. if ( this.normalized ) z = denormalize( z, this.array );
  18379. return z;
  18380. }
  18381. getW( index ) {
  18382. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18383. if ( this.normalized ) w = denormalize( w, this.array );
  18384. return w;
  18385. }
  18386. setXY( index, x, y ) {
  18387. index = index * this.data.stride + this.offset;
  18388. if ( this.normalized ) {
  18389. x = normalize( x, this.array );
  18390. y = normalize( y, this.array );
  18391. }
  18392. this.data.array[ index + 0 ] = x;
  18393. this.data.array[ index + 1 ] = y;
  18394. return this;
  18395. }
  18396. setXYZ( index, x, y, z ) {
  18397. index = index * this.data.stride + this.offset;
  18398. if ( this.normalized ) {
  18399. x = normalize( x, this.array );
  18400. y = normalize( y, this.array );
  18401. z = normalize( z, this.array );
  18402. }
  18403. this.data.array[ index + 0 ] = x;
  18404. this.data.array[ index + 1 ] = y;
  18405. this.data.array[ index + 2 ] = z;
  18406. return this;
  18407. }
  18408. setXYZW( index, x, y, z, w ) {
  18409. index = index * this.data.stride + this.offset;
  18410. if ( this.normalized ) {
  18411. x = normalize( x, this.array );
  18412. y = normalize( y, this.array );
  18413. z = normalize( z, this.array );
  18414. w = normalize( w, this.array );
  18415. }
  18416. this.data.array[ index + 0 ] = x;
  18417. this.data.array[ index + 1 ] = y;
  18418. this.data.array[ index + 2 ] = z;
  18419. this.data.array[ index + 3 ] = w;
  18420. return this;
  18421. }
  18422. clone( data ) {
  18423. if ( data === undefined ) {
  18424. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18425. const array = [];
  18426. for ( let i = 0; i < this.count; i ++ ) {
  18427. const index = i * this.data.stride + this.offset;
  18428. for ( let j = 0; j < this.itemSize; j ++ ) {
  18429. array.push( this.data.array[ index + j ] );
  18430. }
  18431. }
  18432. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18433. } else {
  18434. if ( data.interleavedBuffers === undefined ) {
  18435. data.interleavedBuffers = {};
  18436. }
  18437. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18438. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18439. }
  18440. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18441. }
  18442. }
  18443. toJSON( data ) {
  18444. if ( data === undefined ) {
  18445. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18446. const array = [];
  18447. for ( let i = 0; i < this.count; i ++ ) {
  18448. const index = i * this.data.stride + this.offset;
  18449. for ( let j = 0; j < this.itemSize; j ++ ) {
  18450. array.push( this.data.array[ index + j ] );
  18451. }
  18452. }
  18453. // de-interleave data and save it as an ordinary buffer attribute for now
  18454. return {
  18455. itemSize: this.itemSize,
  18456. type: this.array.constructor.name,
  18457. array: array,
  18458. normalized: this.normalized
  18459. };
  18460. } else {
  18461. // save as true interleaved attribute
  18462. if ( data.interleavedBuffers === undefined ) {
  18463. data.interleavedBuffers = {};
  18464. }
  18465. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18466. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18467. }
  18468. return {
  18469. isInterleavedBufferAttribute: true,
  18470. itemSize: this.itemSize,
  18471. data: this.data.uuid,
  18472. offset: this.offset,
  18473. normalized: this.normalized
  18474. };
  18475. }
  18476. }
  18477. }
  18478. class SpriteMaterial extends Material {
  18479. constructor( parameters ) {
  18480. super();
  18481. this.isSpriteMaterial = true;
  18482. this.type = 'SpriteMaterial';
  18483. this.color = new Color( 0xffffff );
  18484. this.map = null;
  18485. this.alphaMap = null;
  18486. this.rotation = 0;
  18487. this.sizeAttenuation = true;
  18488. this.transparent = true;
  18489. this.fog = true;
  18490. this.setValues( parameters );
  18491. }
  18492. copy( source ) {
  18493. super.copy( source );
  18494. this.color.copy( source.color );
  18495. this.map = source.map;
  18496. this.alphaMap = source.alphaMap;
  18497. this.rotation = source.rotation;
  18498. this.sizeAttenuation = source.sizeAttenuation;
  18499. this.fog = source.fog;
  18500. return this;
  18501. }
  18502. }
  18503. let _geometry;
  18504. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18505. const _worldScale = /*@__PURE__*/ new Vector3();
  18506. const _mvPosition = /*@__PURE__*/ new Vector3();
  18507. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18508. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18509. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18510. const _vA = /*@__PURE__*/ new Vector3();
  18511. const _vB = /*@__PURE__*/ new Vector3();
  18512. const _vC = /*@__PURE__*/ new Vector3();
  18513. const _uvA = /*@__PURE__*/ new Vector2();
  18514. const _uvB = /*@__PURE__*/ new Vector2();
  18515. const _uvC = /*@__PURE__*/ new Vector2();
  18516. class Sprite extends Object3D {
  18517. constructor( material = new SpriteMaterial() ) {
  18518. super();
  18519. this.isSprite = true;
  18520. this.type = 'Sprite';
  18521. if ( _geometry === undefined ) {
  18522. _geometry = new BufferGeometry();
  18523. const float32Array = new Float32Array( [
  18524. - 0.5, - 0.5, 0, 0, 0,
  18525. 0.5, - 0.5, 0, 1, 0,
  18526. 0.5, 0.5, 0, 1, 1,
  18527. - 0.5, 0.5, 0, 0, 1
  18528. ] );
  18529. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18530. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18531. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18532. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18533. }
  18534. this.geometry = _geometry;
  18535. this.material = material;
  18536. this.center = new Vector2( 0.5, 0.5 );
  18537. }
  18538. raycast( raycaster, intersects ) {
  18539. if ( raycaster.camera === null ) {
  18540. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18541. }
  18542. _worldScale.setFromMatrixScale( this.matrixWorld );
  18543. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18544. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18545. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18546. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18547. _worldScale.multiplyScalar( - _mvPosition.z );
  18548. }
  18549. const rotation = this.material.rotation;
  18550. let sin, cos;
  18551. if ( rotation !== 0 ) {
  18552. cos = Math.cos( rotation );
  18553. sin = Math.sin( rotation );
  18554. }
  18555. const center = this.center;
  18556. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18557. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18558. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18559. _uvA.set( 0, 0 );
  18560. _uvB.set( 1, 0 );
  18561. _uvC.set( 1, 1 );
  18562. // check first triangle
  18563. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18564. if ( intersect === null ) {
  18565. // check second triangle
  18566. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18567. _uvB.set( 0, 1 );
  18568. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18569. if ( intersect === null ) {
  18570. return;
  18571. }
  18572. }
  18573. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18574. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18575. intersects.push( {
  18576. distance: distance,
  18577. point: _intersectPoint.clone(),
  18578. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18579. face: null,
  18580. object: this
  18581. } );
  18582. }
  18583. copy( source, recursive ) {
  18584. super.copy( source, recursive );
  18585. if ( source.center !== undefined ) this.center.copy( source.center );
  18586. this.material = source.material;
  18587. return this;
  18588. }
  18589. }
  18590. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18591. // compute position in camera space
  18592. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18593. // to check if rotation is not zero
  18594. if ( sin !== undefined ) {
  18595. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18596. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18597. } else {
  18598. _rotatedPosition.copy( _alignedPosition );
  18599. }
  18600. vertexPosition.copy( mvPosition );
  18601. vertexPosition.x += _rotatedPosition.x;
  18602. vertexPosition.y += _rotatedPosition.y;
  18603. // transform to world space
  18604. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18605. }
  18606. const _v1$2 = /*@__PURE__*/ new Vector3();
  18607. const _v2$1 = /*@__PURE__*/ new Vector3();
  18608. class LOD extends Object3D {
  18609. constructor() {
  18610. super();
  18611. this._currentLevel = 0;
  18612. this.type = 'LOD';
  18613. Object.defineProperties( this, {
  18614. levels: {
  18615. enumerable: true,
  18616. value: []
  18617. },
  18618. isLOD: {
  18619. value: true,
  18620. }
  18621. } );
  18622. this.autoUpdate = true;
  18623. }
  18624. copy( source ) {
  18625. super.copy( source, false );
  18626. const levels = source.levels;
  18627. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18628. const level = levels[ i ];
  18629. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18630. }
  18631. this.autoUpdate = source.autoUpdate;
  18632. return this;
  18633. }
  18634. addLevel( object, distance = 0, hysteresis = 0 ) {
  18635. distance = Math.abs( distance );
  18636. const levels = this.levels;
  18637. let l;
  18638. for ( l = 0; l < levels.length; l ++ ) {
  18639. if ( distance < levels[ l ].distance ) {
  18640. break;
  18641. }
  18642. }
  18643. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18644. this.add( object );
  18645. return this;
  18646. }
  18647. getCurrentLevel() {
  18648. return this._currentLevel;
  18649. }
  18650. getObjectForDistance( distance ) {
  18651. const levels = this.levels;
  18652. if ( levels.length > 0 ) {
  18653. let i, l;
  18654. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18655. let levelDistance = levels[ i ].distance;
  18656. if ( levels[ i ].object.visible ) {
  18657. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18658. }
  18659. if ( distance < levelDistance ) {
  18660. break;
  18661. }
  18662. }
  18663. return levels[ i - 1 ].object;
  18664. }
  18665. return null;
  18666. }
  18667. raycast( raycaster, intersects ) {
  18668. const levels = this.levels;
  18669. if ( levels.length > 0 ) {
  18670. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18671. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18672. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18673. }
  18674. }
  18675. update( camera ) {
  18676. const levels = this.levels;
  18677. if ( levels.length > 1 ) {
  18678. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18679. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18680. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18681. levels[ 0 ].object.visible = true;
  18682. let i, l;
  18683. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18684. let levelDistance = levels[ i ].distance;
  18685. if ( levels[ i ].object.visible ) {
  18686. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18687. }
  18688. if ( distance >= levelDistance ) {
  18689. levels[ i - 1 ].object.visible = false;
  18690. levels[ i ].object.visible = true;
  18691. } else {
  18692. break;
  18693. }
  18694. }
  18695. this._currentLevel = i - 1;
  18696. for ( ; i < l; i ++ ) {
  18697. levels[ i ].object.visible = false;
  18698. }
  18699. }
  18700. }
  18701. toJSON( meta ) {
  18702. const data = super.toJSON( meta );
  18703. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18704. data.object.levels = [];
  18705. const levels = this.levels;
  18706. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18707. const level = levels[ i ];
  18708. data.object.levels.push( {
  18709. object: level.object.uuid,
  18710. distance: level.distance,
  18711. hysteresis: level.hysteresis
  18712. } );
  18713. }
  18714. return data;
  18715. }
  18716. }
  18717. const _basePosition = /*@__PURE__*/ new Vector3();
  18718. const _skinIndex = /*@__PURE__*/ new Vector4();
  18719. const _skinWeight = /*@__PURE__*/ new Vector4();
  18720. const _vector3 = /*@__PURE__*/ new Vector3();
  18721. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18722. const _vertex = /*@__PURE__*/ new Vector3();
  18723. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18724. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18725. const _ray$2 = /*@__PURE__*/ new Ray();
  18726. class SkinnedMesh extends Mesh {
  18727. constructor( geometry, material ) {
  18728. super( geometry, material );
  18729. this.isSkinnedMesh = true;
  18730. this.type = 'SkinnedMesh';
  18731. this.bindMode = 'attached';
  18732. this.bindMatrix = new Matrix4();
  18733. this.bindMatrixInverse = new Matrix4();
  18734. this.boundingBox = null;
  18735. this.boundingSphere = null;
  18736. }
  18737. computeBoundingBox() {
  18738. const geometry = this.geometry;
  18739. if ( this.boundingBox === null ) {
  18740. this.boundingBox = new Box3();
  18741. }
  18742. this.boundingBox.makeEmpty();
  18743. const positionAttribute = geometry.getAttribute( 'position' );
  18744. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18745. _vertex.fromBufferAttribute( positionAttribute, i );
  18746. this.applyBoneTransform( i, _vertex );
  18747. this.boundingBox.expandByPoint( _vertex );
  18748. }
  18749. }
  18750. computeBoundingSphere() {
  18751. const geometry = this.geometry;
  18752. if ( this.boundingSphere === null ) {
  18753. this.boundingSphere = new Sphere();
  18754. }
  18755. this.boundingSphere.makeEmpty();
  18756. const positionAttribute = geometry.getAttribute( 'position' );
  18757. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18758. _vertex.fromBufferAttribute( positionAttribute, i );
  18759. this.applyBoneTransform( i, _vertex );
  18760. this.boundingSphere.expandByPoint( _vertex );
  18761. }
  18762. }
  18763. copy( source, recursive ) {
  18764. super.copy( source, recursive );
  18765. this.bindMode = source.bindMode;
  18766. this.bindMatrix.copy( source.bindMatrix );
  18767. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18768. this.skeleton = source.skeleton;
  18769. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18770. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18771. return this;
  18772. }
  18773. raycast( raycaster, intersects ) {
  18774. const material = this.material;
  18775. const matrixWorld = this.matrixWorld;
  18776. if ( material === undefined ) return;
  18777. // test with bounding sphere in world space
  18778. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18779. _sphere$3.copy( this.boundingSphere );
  18780. _sphere$3.applyMatrix4( matrixWorld );
  18781. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  18782. // convert ray to local space of skinned mesh
  18783. _inverseMatrix$2.copy( matrixWorld ).invert();
  18784. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18785. // test with bounding box in local space
  18786. if ( this.boundingBox !== null ) {
  18787. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18788. }
  18789. // test for intersections with geometry
  18790. this._computeIntersections( raycaster, intersects, _ray$2 );
  18791. }
  18792. getVertexPosition( index, target ) {
  18793. super.getVertexPosition( index, target );
  18794. this.applyBoneTransform( index, target );
  18795. return target;
  18796. }
  18797. bind( skeleton, bindMatrix ) {
  18798. this.skeleton = skeleton;
  18799. if ( bindMatrix === undefined ) {
  18800. this.updateMatrixWorld( true );
  18801. this.skeleton.calculateInverses();
  18802. bindMatrix = this.matrixWorld;
  18803. }
  18804. this.bindMatrix.copy( bindMatrix );
  18805. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18806. }
  18807. pose() {
  18808. this.skeleton.pose();
  18809. }
  18810. normalizeSkinWeights() {
  18811. const vector = new Vector4();
  18812. const skinWeight = this.geometry.attributes.skinWeight;
  18813. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18814. vector.fromBufferAttribute( skinWeight, i );
  18815. const scale = 1.0 / vector.manhattanLength();
  18816. if ( scale !== Infinity ) {
  18817. vector.multiplyScalar( scale );
  18818. } else {
  18819. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18820. }
  18821. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18822. }
  18823. }
  18824. updateMatrixWorld( force ) {
  18825. super.updateMatrixWorld( force );
  18826. if ( this.bindMode === 'attached' ) {
  18827. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18828. } else if ( this.bindMode === 'detached' ) {
  18829. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18830. } else {
  18831. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18832. }
  18833. }
  18834. applyBoneTransform( index, vector ) {
  18835. const skeleton = this.skeleton;
  18836. const geometry = this.geometry;
  18837. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18838. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18839. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18840. vector.set( 0, 0, 0 );
  18841. for ( let i = 0; i < 4; i ++ ) {
  18842. const weight = _skinWeight.getComponent( i );
  18843. if ( weight !== 0 ) {
  18844. const boneIndex = _skinIndex.getComponent( i );
  18845. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18846. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18847. }
  18848. }
  18849. return vector.applyMatrix4( this.bindMatrixInverse );
  18850. }
  18851. boneTransform( index, vector ) { // @deprecated, r151
  18852. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  18853. return this.applyBoneTransform( index, vector );
  18854. }
  18855. }
  18856. class Bone extends Object3D {
  18857. constructor() {
  18858. super();
  18859. this.isBone = true;
  18860. this.type = 'Bone';
  18861. }
  18862. }
  18863. class DataTexture extends Texture {
  18864. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18865. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18866. this.isDataTexture = true;
  18867. this.image = { data: data, width: width, height: height };
  18868. this.generateMipmaps = false;
  18869. this.flipY = false;
  18870. this.unpackAlignment = 1;
  18871. }
  18872. }
  18873. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18874. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18875. class Skeleton {
  18876. constructor( bones = [], boneInverses = [] ) {
  18877. this.uuid = generateUUID();
  18878. this.bones = bones.slice( 0 );
  18879. this.boneInverses = boneInverses;
  18880. this.boneMatrices = null;
  18881. this.boneTexture = null;
  18882. this.boneTextureSize = 0;
  18883. this.init();
  18884. }
  18885. init() {
  18886. const bones = this.bones;
  18887. const boneInverses = this.boneInverses;
  18888. this.boneMatrices = new Float32Array( bones.length * 16 );
  18889. // calculate inverse bone matrices if necessary
  18890. if ( boneInverses.length === 0 ) {
  18891. this.calculateInverses();
  18892. } else {
  18893. // handle special case
  18894. if ( bones.length !== boneInverses.length ) {
  18895. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18896. this.boneInverses = [];
  18897. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18898. this.boneInverses.push( new Matrix4() );
  18899. }
  18900. }
  18901. }
  18902. }
  18903. calculateInverses() {
  18904. this.boneInverses.length = 0;
  18905. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18906. const inverse = new Matrix4();
  18907. if ( this.bones[ i ] ) {
  18908. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18909. }
  18910. this.boneInverses.push( inverse );
  18911. }
  18912. }
  18913. pose() {
  18914. // recover the bind-time world matrices
  18915. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18916. const bone = this.bones[ i ];
  18917. if ( bone ) {
  18918. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18919. }
  18920. }
  18921. // compute the local matrices, positions, rotations and scales
  18922. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18923. const bone = this.bones[ i ];
  18924. if ( bone ) {
  18925. if ( bone.parent && bone.parent.isBone ) {
  18926. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18927. bone.matrix.multiply( bone.matrixWorld );
  18928. } else {
  18929. bone.matrix.copy( bone.matrixWorld );
  18930. }
  18931. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18932. }
  18933. }
  18934. }
  18935. update() {
  18936. const bones = this.bones;
  18937. const boneInverses = this.boneInverses;
  18938. const boneMatrices = this.boneMatrices;
  18939. const boneTexture = this.boneTexture;
  18940. // flatten bone matrices to array
  18941. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18942. // compute the offset between the current and the original transform
  18943. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18944. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18945. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18946. }
  18947. if ( boneTexture !== null ) {
  18948. boneTexture.needsUpdate = true;
  18949. }
  18950. }
  18951. clone() {
  18952. return new Skeleton( this.bones, this.boneInverses );
  18953. }
  18954. computeBoneTexture() {
  18955. // layout (1 matrix = 4 pixels)
  18956. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18957. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18958. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18959. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18960. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18961. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18962. size = ceilPowerOfTwo( size );
  18963. size = Math.max( size, 4 );
  18964. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18965. boneMatrices.set( this.boneMatrices ); // copy current values
  18966. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18967. boneTexture.needsUpdate = true;
  18968. this.boneMatrices = boneMatrices;
  18969. this.boneTexture = boneTexture;
  18970. this.boneTextureSize = size;
  18971. return this;
  18972. }
  18973. getBoneByName( name ) {
  18974. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18975. const bone = this.bones[ i ];
  18976. if ( bone.name === name ) {
  18977. return bone;
  18978. }
  18979. }
  18980. return undefined;
  18981. }
  18982. dispose( ) {
  18983. if ( this.boneTexture !== null ) {
  18984. this.boneTexture.dispose();
  18985. this.boneTexture = null;
  18986. }
  18987. }
  18988. fromJSON( json, bones ) {
  18989. this.uuid = json.uuid;
  18990. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18991. const uuid = json.bones[ i ];
  18992. let bone = bones[ uuid ];
  18993. if ( bone === undefined ) {
  18994. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18995. bone = new Bone();
  18996. }
  18997. this.bones.push( bone );
  18998. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18999. }
  19000. this.init();
  19001. return this;
  19002. }
  19003. toJSON() {
  19004. const data = {
  19005. metadata: {
  19006. version: 4.6,
  19007. type: 'Skeleton',
  19008. generator: 'Skeleton.toJSON'
  19009. },
  19010. bones: [],
  19011. boneInverses: []
  19012. };
  19013. data.uuid = this.uuid;
  19014. const bones = this.bones;
  19015. const boneInverses = this.boneInverses;
  19016. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19017. const bone = bones[ i ];
  19018. data.bones.push( bone.uuid );
  19019. const boneInverse = boneInverses[ i ];
  19020. data.boneInverses.push( boneInverse.toArray() );
  19021. }
  19022. return data;
  19023. }
  19024. }
  19025. class InstancedBufferAttribute extends BufferAttribute {
  19026. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19027. super( array, itemSize, normalized );
  19028. this.isInstancedBufferAttribute = true;
  19029. this.meshPerAttribute = meshPerAttribute;
  19030. }
  19031. copy( source ) {
  19032. super.copy( source );
  19033. this.meshPerAttribute = source.meshPerAttribute;
  19034. return this;
  19035. }
  19036. toJSON() {
  19037. const data = super.toJSON();
  19038. data.meshPerAttribute = this.meshPerAttribute;
  19039. data.isInstancedBufferAttribute = true;
  19040. return data;
  19041. }
  19042. }
  19043. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19044. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19045. const _instanceIntersects = [];
  19046. const _box3 = /*@__PURE__*/ new Box3();
  19047. const _identity = /*@__PURE__*/ new Matrix4();
  19048. const _mesh = /*@__PURE__*/ new Mesh();
  19049. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19050. class InstancedMesh extends Mesh {
  19051. constructor( geometry, material, count ) {
  19052. super( geometry, material );
  19053. this.isInstancedMesh = true;
  19054. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19055. this.instanceColor = null;
  19056. this.count = count;
  19057. this.boundingBox = null;
  19058. this.boundingSphere = null;
  19059. for ( let i = 0; i < count; i ++ ) {
  19060. this.setMatrixAt( i, _identity );
  19061. }
  19062. }
  19063. computeBoundingBox() {
  19064. const geometry = this.geometry;
  19065. const count = this.count;
  19066. if ( this.boundingBox === null ) {
  19067. this.boundingBox = new Box3();
  19068. }
  19069. if ( geometry.boundingBox === null ) {
  19070. geometry.computeBoundingBox();
  19071. }
  19072. this.boundingBox.makeEmpty();
  19073. for ( let i = 0; i < count; i ++ ) {
  19074. this.getMatrixAt( i, _instanceLocalMatrix );
  19075. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19076. this.boundingBox.union( _box3 );
  19077. }
  19078. }
  19079. computeBoundingSphere() {
  19080. const geometry = this.geometry;
  19081. const count = this.count;
  19082. if ( this.boundingSphere === null ) {
  19083. this.boundingSphere = new Sphere();
  19084. }
  19085. if ( geometry.boundingSphere === null ) {
  19086. geometry.computeBoundingSphere();
  19087. }
  19088. this.boundingSphere.makeEmpty();
  19089. for ( let i = 0; i < count; i ++ ) {
  19090. this.getMatrixAt( i, _instanceLocalMatrix );
  19091. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19092. this.boundingSphere.union( _sphere$2 );
  19093. }
  19094. }
  19095. copy( source, recursive ) {
  19096. super.copy( source, recursive );
  19097. this.instanceMatrix.copy( source.instanceMatrix );
  19098. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19099. this.count = source.count;
  19100. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19101. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19102. return this;
  19103. }
  19104. getColorAt( index, color ) {
  19105. color.fromArray( this.instanceColor.array, index * 3 );
  19106. }
  19107. getMatrixAt( index, matrix ) {
  19108. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19109. }
  19110. raycast( raycaster, intersects ) {
  19111. const matrixWorld = this.matrixWorld;
  19112. const raycastTimes = this.count;
  19113. _mesh.geometry = this.geometry;
  19114. _mesh.material = this.material;
  19115. if ( _mesh.material === undefined ) return;
  19116. // test with bounding sphere first
  19117. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19118. _sphere$2.copy( this.boundingSphere );
  19119. _sphere$2.applyMatrix4( matrixWorld );
  19120. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  19121. // now test each instance
  19122. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19123. // calculate the world matrix for each instance
  19124. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19125. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19126. // the mesh represents this single instance
  19127. _mesh.matrixWorld = _instanceWorldMatrix;
  19128. _mesh.raycast( raycaster, _instanceIntersects );
  19129. // process the result of raycast
  19130. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19131. const intersect = _instanceIntersects[ i ];
  19132. intersect.instanceId = instanceId;
  19133. intersect.object = this;
  19134. intersects.push( intersect );
  19135. }
  19136. _instanceIntersects.length = 0;
  19137. }
  19138. }
  19139. setColorAt( index, color ) {
  19140. if ( this.instanceColor === null ) {
  19141. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19142. }
  19143. color.toArray( this.instanceColor.array, index * 3 );
  19144. }
  19145. setMatrixAt( index, matrix ) {
  19146. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19147. }
  19148. updateMorphTargets() {
  19149. }
  19150. dispose() {
  19151. this.dispatchEvent( { type: 'dispose' } );
  19152. }
  19153. }
  19154. class LineBasicMaterial extends Material {
  19155. constructor( parameters ) {
  19156. super();
  19157. this.isLineBasicMaterial = true;
  19158. this.type = 'LineBasicMaterial';
  19159. this.color = new Color( 0xffffff );
  19160. this.map = null;
  19161. this.linewidth = 1;
  19162. this.linecap = 'round';
  19163. this.linejoin = 'round';
  19164. this.fog = true;
  19165. this.setValues( parameters );
  19166. }
  19167. copy( source ) {
  19168. super.copy( source );
  19169. this.color.copy( source.color );
  19170. this.map = source.map;
  19171. this.linewidth = source.linewidth;
  19172. this.linecap = source.linecap;
  19173. this.linejoin = source.linejoin;
  19174. this.fog = source.fog;
  19175. return this;
  19176. }
  19177. }
  19178. const _start$1 = /*@__PURE__*/ new Vector3();
  19179. const _end$1 = /*@__PURE__*/ new Vector3();
  19180. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  19181. const _ray$1 = /*@__PURE__*/ new Ray();
  19182. const _sphere$1 = /*@__PURE__*/ new Sphere();
  19183. class Line extends Object3D {
  19184. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  19185. super();
  19186. this.isLine = true;
  19187. this.type = 'Line';
  19188. this.geometry = geometry;
  19189. this.material = material;
  19190. this.updateMorphTargets();
  19191. }
  19192. copy( source, recursive ) {
  19193. super.copy( source, recursive );
  19194. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  19195. this.geometry = source.geometry;
  19196. return this;
  19197. }
  19198. computeLineDistances() {
  19199. const geometry = this.geometry;
  19200. // we assume non-indexed geometry
  19201. if ( geometry.index === null ) {
  19202. const positionAttribute = geometry.attributes.position;
  19203. const lineDistances = [ 0 ];
  19204. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  19205. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  19206. _end$1.fromBufferAttribute( positionAttribute, i );
  19207. lineDistances[ i ] = lineDistances[ i - 1 ];
  19208. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  19209. }
  19210. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19211. } else {
  19212. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19213. }
  19214. return this;
  19215. }
  19216. raycast( raycaster, intersects ) {
  19217. const geometry = this.geometry;
  19218. const matrixWorld = this.matrixWorld;
  19219. const threshold = raycaster.params.Line.threshold;
  19220. const drawRange = geometry.drawRange;
  19221. // Checking boundingSphere distance to ray
  19222. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19223. _sphere$1.copy( geometry.boundingSphere );
  19224. _sphere$1.applyMatrix4( matrixWorld );
  19225. _sphere$1.radius += threshold;
  19226. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  19227. //
  19228. _inverseMatrix$1.copy( matrixWorld ).invert();
  19229. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  19230. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19231. const localThresholdSq = localThreshold * localThreshold;
  19232. const vStart = new Vector3();
  19233. const vEnd = new Vector3();
  19234. const interSegment = new Vector3();
  19235. const interRay = new Vector3();
  19236. const step = this.isLineSegments ? 2 : 1;
  19237. const index = geometry.index;
  19238. const attributes = geometry.attributes;
  19239. const positionAttribute = attributes.position;
  19240. if ( index !== null ) {
  19241. const start = Math.max( 0, drawRange.start );
  19242. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  19243. for ( let i = start, l = end - 1; i < l; i += step ) {
  19244. const a = index.getX( i );
  19245. const b = index.getX( i + 1 );
  19246. vStart.fromBufferAttribute( positionAttribute, a );
  19247. vEnd.fromBufferAttribute( positionAttribute, b );
  19248. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19249. if ( distSq > localThresholdSq ) continue;
  19250. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19251. const distance = raycaster.ray.origin.distanceTo( interRay );
  19252. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19253. intersects.push( {
  19254. distance: distance,
  19255. // What do we want? intersection point on the ray or on the segment??
  19256. // point: raycaster.ray.at( distance ),
  19257. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19258. index: i,
  19259. face: null,
  19260. faceIndex: null,
  19261. object: this
  19262. } );
  19263. }
  19264. } else {
  19265. const start = Math.max( 0, drawRange.start );
  19266. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  19267. for ( let i = start, l = end - 1; i < l; i += step ) {
  19268. vStart.fromBufferAttribute( positionAttribute, i );
  19269. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  19270. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19271. if ( distSq > localThresholdSq ) continue;
  19272. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19273. const distance = raycaster.ray.origin.distanceTo( interRay );
  19274. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19275. intersects.push( {
  19276. distance: distance,
  19277. // What do we want? intersection point on the ray or on the segment??
  19278. // point: raycaster.ray.at( distance ),
  19279. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19280. index: i,
  19281. face: null,
  19282. faceIndex: null,
  19283. object: this
  19284. } );
  19285. }
  19286. }
  19287. }
  19288. updateMorphTargets() {
  19289. const geometry = this.geometry;
  19290. const morphAttributes = geometry.morphAttributes;
  19291. const keys = Object.keys( morphAttributes );
  19292. if ( keys.length > 0 ) {
  19293. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  19294. if ( morphAttribute !== undefined ) {
  19295. this.morphTargetInfluences = [];
  19296. this.morphTargetDictionary = {};
  19297. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  19298. const name = morphAttribute[ m ].name || String( m );
  19299. this.morphTargetInfluences.push( 0 );
  19300. this.morphTargetDictionary[ name ] = m;
  19301. }
  19302. }
  19303. }
  19304. }
  19305. }
  19306. const _start = /*@__PURE__*/ new Vector3();
  19307. const _end = /*@__PURE__*/ new Vector3();
  19308. class LineSegments extends Line {
  19309. constructor( geometry, material ) {
  19310. super( geometry, material );
  19311. this.isLineSegments = true;
  19312. this.type = 'LineSegments';
  19313. }
  19314. computeLineDistances() {
  19315. const geometry = this.geometry;
  19316. // we assume non-indexed geometry
  19317. if ( geometry.index === null ) {
  19318. const positionAttribute = geometry.attributes.position;
  19319. const lineDistances = [];
  19320. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  19321. _start.fromBufferAttribute( positionAttribute, i );
  19322. _end.fromBufferAttribute( positionAttribute, i + 1 );
  19323. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19324. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  19325. }
  19326. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19327. } else {
  19328. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19329. }
  19330. return this;
  19331. }
  19332. }
  19333. class LineLoop extends Line {
  19334. constructor( geometry, material ) {
  19335. super( geometry, material );
  19336. this.isLineLoop = true;
  19337. this.type = 'LineLoop';
  19338. }
  19339. }
  19340. class PointsMaterial extends Material {
  19341. constructor( parameters ) {
  19342. super();
  19343. this.isPointsMaterial = true;
  19344. this.type = 'PointsMaterial';
  19345. this.color = new Color( 0xffffff );
  19346. this.map = null;
  19347. this.alphaMap = null;
  19348. this.size = 1;
  19349. this.sizeAttenuation = true;
  19350. this.fog = true;
  19351. this.setValues( parameters );
  19352. }
  19353. copy( source ) {
  19354. super.copy( source );
  19355. this.color.copy( source.color );
  19356. this.map = source.map;
  19357. this.alphaMap = source.alphaMap;
  19358. this.size = source.size;
  19359. this.sizeAttenuation = source.sizeAttenuation;
  19360. this.fog = source.fog;
  19361. return this;
  19362. }
  19363. }
  19364. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  19365. const _ray = /*@__PURE__*/ new Ray();
  19366. const _sphere = /*@__PURE__*/ new Sphere();
  19367. const _position$2 = /*@__PURE__*/ new Vector3();
  19368. class Points extends Object3D {
  19369. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  19370. super();
  19371. this.isPoints = true;
  19372. this.type = 'Points';
  19373. this.geometry = geometry;
  19374. this.material = material;
  19375. this.updateMorphTargets();
  19376. }
  19377. copy( source, recursive ) {
  19378. super.copy( source, recursive );
  19379. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  19380. this.geometry = source.geometry;
  19381. return this;
  19382. }
  19383. raycast( raycaster, intersects ) {
  19384. const geometry = this.geometry;
  19385. const matrixWorld = this.matrixWorld;
  19386. const threshold = raycaster.params.Points.threshold;
  19387. const drawRange = geometry.drawRange;
  19388. // Checking boundingSphere distance to ray
  19389. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19390. _sphere.copy( geometry.boundingSphere );
  19391. _sphere.applyMatrix4( matrixWorld );
  19392. _sphere.radius += threshold;
  19393. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  19394. //
  19395. _inverseMatrix.copy( matrixWorld ).invert();
  19396. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  19397. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19398. const localThresholdSq = localThreshold * localThreshold;
  19399. const index = geometry.index;
  19400. const attributes = geometry.attributes;
  19401. const positionAttribute = attributes.position;
  19402. if ( index !== null ) {
  19403. const start = Math.max( 0, drawRange.start );
  19404. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  19405. for ( let i = start, il = end; i < il; i ++ ) {
  19406. const a = index.getX( i );
  19407. _position$2.fromBufferAttribute( positionAttribute, a );
  19408. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19409. }
  19410. } else {
  19411. const start = Math.max( 0, drawRange.start );
  19412. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  19413. for ( let i = start, l = end; i < l; i ++ ) {
  19414. _position$2.fromBufferAttribute( positionAttribute, i );
  19415. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19416. }
  19417. }
  19418. }
  19419. updateMorphTargets() {
  19420. const geometry = this.geometry;
  19421. const morphAttributes = geometry.morphAttributes;
  19422. const keys = Object.keys( morphAttributes );
  19423. if ( keys.length > 0 ) {
  19424. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  19425. if ( morphAttribute !== undefined ) {
  19426. this.morphTargetInfluences = [];
  19427. this.morphTargetDictionary = {};
  19428. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  19429. const name = morphAttribute[ m ].name || String( m );
  19430. this.morphTargetInfluences.push( 0 );
  19431. this.morphTargetDictionary[ name ] = m;
  19432. }
  19433. }
  19434. }
  19435. }
  19436. }
  19437. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  19438. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  19439. if ( rayPointDistanceSq < localThresholdSq ) {
  19440. const intersectPoint = new Vector3();
  19441. _ray.closestPointToPoint( point, intersectPoint );
  19442. intersectPoint.applyMatrix4( matrixWorld );
  19443. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19444. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19445. intersects.push( {
  19446. distance: distance,
  19447. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19448. point: intersectPoint,
  19449. index: index,
  19450. face: null,
  19451. object: object
  19452. } );
  19453. }
  19454. }
  19455. class VideoTexture extends Texture {
  19456. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19457. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19458. this.isVideoTexture = true;
  19459. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  19460. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  19461. this.generateMipmaps = false;
  19462. const scope = this;
  19463. function updateVideo() {
  19464. scope.needsUpdate = true;
  19465. video.requestVideoFrameCallback( updateVideo );
  19466. }
  19467. if ( 'requestVideoFrameCallback' in video ) {
  19468. video.requestVideoFrameCallback( updateVideo );
  19469. }
  19470. }
  19471. clone() {
  19472. return new this.constructor( this.image ).copy( this );
  19473. }
  19474. update() {
  19475. const video = this.image;
  19476. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  19477. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  19478. this.needsUpdate = true;
  19479. }
  19480. }
  19481. }
  19482. class FramebufferTexture extends Texture {
  19483. constructor( width, height ) {
  19484. super( { width, height } );
  19485. this.isFramebufferTexture = true;
  19486. this.magFilter = NearestFilter;
  19487. this.minFilter = NearestFilter;
  19488. this.generateMipmaps = false;
  19489. this.needsUpdate = true;
  19490. }
  19491. }
  19492. class CompressedTexture extends Texture {
  19493. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  19494. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19495. this.isCompressedTexture = true;
  19496. this.image = { width: width, height: height };
  19497. this.mipmaps = mipmaps;
  19498. // no flipping for cube textures
  19499. // (also flipping doesn't work for compressed textures )
  19500. this.flipY = false;
  19501. // can't generate mipmaps for compressed textures
  19502. // mips must be embedded in DDS files
  19503. this.generateMipmaps = false;
  19504. }
  19505. }
  19506. class CompressedArrayTexture extends CompressedTexture {
  19507. constructor( mipmaps, width, height, depth, format, type ) {
  19508. super( mipmaps, width, height, format, type );
  19509. this.isCompressedArrayTexture = true;
  19510. this.image.depth = depth;
  19511. this.wrapR = ClampToEdgeWrapping;
  19512. }
  19513. }
  19514. class CompressedCubeTexture extends CompressedTexture {
  19515. constructor( images, format, type ) {
  19516. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  19517. this.isCompressedCubeTexture = true;
  19518. this.isCubeTexture = true;
  19519. this.image = images;
  19520. }
  19521. }
  19522. class CanvasTexture extends Texture {
  19523. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19524. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19525. this.isCanvasTexture = true;
  19526. this.needsUpdate = true;
  19527. }
  19528. }
  19529. /**
  19530. * Extensible curve object.
  19531. *
  19532. * Some common of curve methods:
  19533. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19534. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19535. * .getPoints(), .getSpacedPoints()
  19536. * .getLength()
  19537. * .updateArcLengths()
  19538. *
  19539. * This following curves inherit from THREE.Curve:
  19540. *
  19541. * -- 2D curves --
  19542. * THREE.ArcCurve
  19543. * THREE.CubicBezierCurve
  19544. * THREE.EllipseCurve
  19545. * THREE.LineCurve
  19546. * THREE.QuadraticBezierCurve
  19547. * THREE.SplineCurve
  19548. *
  19549. * -- 3D curves --
  19550. * THREE.CatmullRomCurve3
  19551. * THREE.CubicBezierCurve3
  19552. * THREE.LineCurve3
  19553. * THREE.QuadraticBezierCurve3
  19554. *
  19555. * A series of curves can be represented as a THREE.CurvePath.
  19556. *
  19557. **/
  19558. class Curve {
  19559. constructor() {
  19560. this.type = 'Curve';
  19561. this.arcLengthDivisions = 200;
  19562. }
  19563. // Virtual base class method to overwrite and implement in subclasses
  19564. // - t [0 .. 1]
  19565. getPoint( /* t, optionalTarget */ ) {
  19566. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19567. return null;
  19568. }
  19569. // Get point at relative position in curve according to arc length
  19570. // - u [0 .. 1]
  19571. getPointAt( u, optionalTarget ) {
  19572. const t = this.getUtoTmapping( u );
  19573. return this.getPoint( t, optionalTarget );
  19574. }
  19575. // Get sequence of points using getPoint( t )
  19576. getPoints( divisions = 5 ) {
  19577. const points = [];
  19578. for ( let d = 0; d <= divisions; d ++ ) {
  19579. points.push( this.getPoint( d / divisions ) );
  19580. }
  19581. return points;
  19582. }
  19583. // Get sequence of points using getPointAt( u )
  19584. getSpacedPoints( divisions = 5 ) {
  19585. const points = [];
  19586. for ( let d = 0; d <= divisions; d ++ ) {
  19587. points.push( this.getPointAt( d / divisions ) );
  19588. }
  19589. return points;
  19590. }
  19591. // Get total curve arc length
  19592. getLength() {
  19593. const lengths = this.getLengths();
  19594. return lengths[ lengths.length - 1 ];
  19595. }
  19596. // Get list of cumulative segment lengths
  19597. getLengths( divisions = this.arcLengthDivisions ) {
  19598. if ( this.cacheArcLengths &&
  19599. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19600. ! this.needsUpdate ) {
  19601. return this.cacheArcLengths;
  19602. }
  19603. this.needsUpdate = false;
  19604. const cache = [];
  19605. let current, last = this.getPoint( 0 );
  19606. let sum = 0;
  19607. cache.push( 0 );
  19608. for ( let p = 1; p <= divisions; p ++ ) {
  19609. current = this.getPoint( p / divisions );
  19610. sum += current.distanceTo( last );
  19611. cache.push( sum );
  19612. last = current;
  19613. }
  19614. this.cacheArcLengths = cache;
  19615. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19616. }
  19617. updateArcLengths() {
  19618. this.needsUpdate = true;
  19619. this.getLengths();
  19620. }
  19621. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19622. getUtoTmapping( u, distance ) {
  19623. const arcLengths = this.getLengths();
  19624. let i = 0;
  19625. const il = arcLengths.length;
  19626. let targetArcLength; // The targeted u distance value to get
  19627. if ( distance ) {
  19628. targetArcLength = distance;
  19629. } else {
  19630. targetArcLength = u * arcLengths[ il - 1 ];
  19631. }
  19632. // binary search for the index with largest value smaller than target u distance
  19633. let low = 0, high = il - 1, comparison;
  19634. while ( low <= high ) {
  19635. 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
  19636. comparison = arcLengths[ i ] - targetArcLength;
  19637. if ( comparison < 0 ) {
  19638. low = i + 1;
  19639. } else if ( comparison > 0 ) {
  19640. high = i - 1;
  19641. } else {
  19642. high = i;
  19643. break;
  19644. // DONE
  19645. }
  19646. }
  19647. i = high;
  19648. if ( arcLengths[ i ] === targetArcLength ) {
  19649. return i / ( il - 1 );
  19650. }
  19651. // we could get finer grain at lengths, or use simple interpolation between two points
  19652. const lengthBefore = arcLengths[ i ];
  19653. const lengthAfter = arcLengths[ i + 1 ];
  19654. const segmentLength = lengthAfter - lengthBefore;
  19655. // determine where we are between the 'before' and 'after' points
  19656. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19657. // add that fractional amount to t
  19658. const t = ( i + segmentFraction ) / ( il - 1 );
  19659. return t;
  19660. }
  19661. // Returns a unit vector tangent at t
  19662. // In case any sub curve does not implement its tangent derivation,
  19663. // 2 points a small delta apart will be used to find its gradient
  19664. // which seems to give a reasonable approximation
  19665. getTangent( t, optionalTarget ) {
  19666. const delta = 0.0001;
  19667. let t1 = t - delta;
  19668. let t2 = t + delta;
  19669. // Capping in case of danger
  19670. if ( t1 < 0 ) t1 = 0;
  19671. if ( t2 > 1 ) t2 = 1;
  19672. const pt1 = this.getPoint( t1 );
  19673. const pt2 = this.getPoint( t2 );
  19674. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19675. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19676. return tangent;
  19677. }
  19678. getTangentAt( u, optionalTarget ) {
  19679. const t = this.getUtoTmapping( u );
  19680. return this.getTangent( t, optionalTarget );
  19681. }
  19682. computeFrenetFrames( segments, closed ) {
  19683. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19684. const normal = new Vector3();
  19685. const tangents = [];
  19686. const normals = [];
  19687. const binormals = [];
  19688. const vec = new Vector3();
  19689. const mat = new Matrix4();
  19690. // compute the tangent vectors for each segment on the curve
  19691. for ( let i = 0; i <= segments; i ++ ) {
  19692. const u = i / segments;
  19693. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19694. }
  19695. // select an initial normal vector perpendicular to the first tangent vector,
  19696. // and in the direction of the minimum tangent xyz component
  19697. normals[ 0 ] = new Vector3();
  19698. binormals[ 0 ] = new Vector3();
  19699. let min = Number.MAX_VALUE;
  19700. const tx = Math.abs( tangents[ 0 ].x );
  19701. const ty = Math.abs( tangents[ 0 ].y );
  19702. const tz = Math.abs( tangents[ 0 ].z );
  19703. if ( tx <= min ) {
  19704. min = tx;
  19705. normal.set( 1, 0, 0 );
  19706. }
  19707. if ( ty <= min ) {
  19708. min = ty;
  19709. normal.set( 0, 1, 0 );
  19710. }
  19711. if ( tz <= min ) {
  19712. normal.set( 0, 0, 1 );
  19713. }
  19714. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19715. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19716. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19717. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19718. for ( let i = 1; i <= segments; i ++ ) {
  19719. normals[ i ] = normals[ i - 1 ].clone();
  19720. binormals[ i ] = binormals[ i - 1 ].clone();
  19721. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19722. if ( vec.length() > Number.EPSILON ) {
  19723. vec.normalize();
  19724. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19725. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19726. }
  19727. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19728. }
  19729. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19730. if ( closed === true ) {
  19731. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19732. theta /= segments;
  19733. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19734. theta = - theta;
  19735. }
  19736. for ( let i = 1; i <= segments; i ++ ) {
  19737. // twist a little...
  19738. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19739. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19740. }
  19741. }
  19742. return {
  19743. tangents: tangents,
  19744. normals: normals,
  19745. binormals: binormals
  19746. };
  19747. }
  19748. clone() {
  19749. return new this.constructor().copy( this );
  19750. }
  19751. copy( source ) {
  19752. this.arcLengthDivisions = source.arcLengthDivisions;
  19753. return this;
  19754. }
  19755. toJSON() {
  19756. const data = {
  19757. metadata: {
  19758. version: 4.6,
  19759. type: 'Curve',
  19760. generator: 'Curve.toJSON'
  19761. }
  19762. };
  19763. data.arcLengthDivisions = this.arcLengthDivisions;
  19764. data.type = this.type;
  19765. return data;
  19766. }
  19767. fromJSON( json ) {
  19768. this.arcLengthDivisions = json.arcLengthDivisions;
  19769. return this;
  19770. }
  19771. }
  19772. class EllipseCurve extends Curve {
  19773. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19774. super();
  19775. this.isEllipseCurve = true;
  19776. this.type = 'EllipseCurve';
  19777. this.aX = aX;
  19778. this.aY = aY;
  19779. this.xRadius = xRadius;
  19780. this.yRadius = yRadius;
  19781. this.aStartAngle = aStartAngle;
  19782. this.aEndAngle = aEndAngle;
  19783. this.aClockwise = aClockwise;
  19784. this.aRotation = aRotation;
  19785. }
  19786. getPoint( t, optionalTarget ) {
  19787. const point = optionalTarget || new Vector2();
  19788. const twoPi = Math.PI * 2;
  19789. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19790. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19791. // ensures that deltaAngle is 0 .. 2 PI
  19792. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19793. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19794. if ( deltaAngle < Number.EPSILON ) {
  19795. if ( samePoints ) {
  19796. deltaAngle = 0;
  19797. } else {
  19798. deltaAngle = twoPi;
  19799. }
  19800. }
  19801. if ( this.aClockwise === true && ! samePoints ) {
  19802. if ( deltaAngle === twoPi ) {
  19803. deltaAngle = - twoPi;
  19804. } else {
  19805. deltaAngle = deltaAngle - twoPi;
  19806. }
  19807. }
  19808. const angle = this.aStartAngle + t * deltaAngle;
  19809. let x = this.aX + this.xRadius * Math.cos( angle );
  19810. let y = this.aY + this.yRadius * Math.sin( angle );
  19811. if ( this.aRotation !== 0 ) {
  19812. const cos = Math.cos( this.aRotation );
  19813. const sin = Math.sin( this.aRotation );
  19814. const tx = x - this.aX;
  19815. const ty = y - this.aY;
  19816. // Rotate the point about the center of the ellipse.
  19817. x = tx * cos - ty * sin + this.aX;
  19818. y = tx * sin + ty * cos + this.aY;
  19819. }
  19820. return point.set( x, y );
  19821. }
  19822. copy( source ) {
  19823. super.copy( source );
  19824. this.aX = source.aX;
  19825. this.aY = source.aY;
  19826. this.xRadius = source.xRadius;
  19827. this.yRadius = source.yRadius;
  19828. this.aStartAngle = source.aStartAngle;
  19829. this.aEndAngle = source.aEndAngle;
  19830. this.aClockwise = source.aClockwise;
  19831. this.aRotation = source.aRotation;
  19832. return this;
  19833. }
  19834. toJSON() {
  19835. const data = super.toJSON();
  19836. data.aX = this.aX;
  19837. data.aY = this.aY;
  19838. data.xRadius = this.xRadius;
  19839. data.yRadius = this.yRadius;
  19840. data.aStartAngle = this.aStartAngle;
  19841. data.aEndAngle = this.aEndAngle;
  19842. data.aClockwise = this.aClockwise;
  19843. data.aRotation = this.aRotation;
  19844. return data;
  19845. }
  19846. fromJSON( json ) {
  19847. super.fromJSON( json );
  19848. this.aX = json.aX;
  19849. this.aY = json.aY;
  19850. this.xRadius = json.xRadius;
  19851. this.yRadius = json.yRadius;
  19852. this.aStartAngle = json.aStartAngle;
  19853. this.aEndAngle = json.aEndAngle;
  19854. this.aClockwise = json.aClockwise;
  19855. this.aRotation = json.aRotation;
  19856. return this;
  19857. }
  19858. }
  19859. class ArcCurve extends EllipseCurve {
  19860. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19861. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19862. this.isArcCurve = true;
  19863. this.type = 'ArcCurve';
  19864. }
  19865. }
  19866. /**
  19867. * Centripetal CatmullRom Curve - which is useful for avoiding
  19868. * cusps and self-intersections in non-uniform catmull rom curves.
  19869. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19870. *
  19871. * curve.type accepts centripetal(default), chordal and catmullrom
  19872. * curve.tension is used for catmullrom which defaults to 0.5
  19873. */
  19874. /*
  19875. Based on an optimized c++ solution in
  19876. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19877. - http://ideone.com/NoEbVM
  19878. This CubicPoly class could be used for reusing some variables and calculations,
  19879. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19880. which can be placed in CurveUtils.
  19881. */
  19882. function CubicPoly() {
  19883. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19884. /*
  19885. * Compute coefficients for a cubic polynomial
  19886. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19887. * such that
  19888. * p(0) = x0, p(1) = x1
  19889. * and
  19890. * p'(0) = t0, p'(1) = t1.
  19891. */
  19892. function init( x0, x1, t0, t1 ) {
  19893. c0 = x0;
  19894. c1 = t0;
  19895. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19896. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19897. }
  19898. return {
  19899. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19900. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19901. },
  19902. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19903. // compute tangents when parameterized in [t1,t2]
  19904. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19905. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19906. // rescale tangents for parametrization in [0,1]
  19907. t1 *= dt1;
  19908. t2 *= dt1;
  19909. init( x1, x2, t1, t2 );
  19910. },
  19911. calc: function ( t ) {
  19912. const t2 = t * t;
  19913. const t3 = t2 * t;
  19914. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19915. }
  19916. };
  19917. }
  19918. //
  19919. const tmp = /*@__PURE__*/ new Vector3();
  19920. const px = /*@__PURE__*/ new CubicPoly();
  19921. const py = /*@__PURE__*/ new CubicPoly();
  19922. const pz = /*@__PURE__*/ new CubicPoly();
  19923. class CatmullRomCurve3 extends Curve {
  19924. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19925. super();
  19926. this.isCatmullRomCurve3 = true;
  19927. this.type = 'CatmullRomCurve3';
  19928. this.points = points;
  19929. this.closed = closed;
  19930. this.curveType = curveType;
  19931. this.tension = tension;
  19932. }
  19933. getPoint( t, optionalTarget = new Vector3() ) {
  19934. const point = optionalTarget;
  19935. const points = this.points;
  19936. const l = points.length;
  19937. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19938. let intPoint = Math.floor( p );
  19939. let weight = p - intPoint;
  19940. if ( this.closed ) {
  19941. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19942. } else if ( weight === 0 && intPoint === l - 1 ) {
  19943. intPoint = l - 2;
  19944. weight = 1;
  19945. }
  19946. let p0, p3; // 4 points (p1 & p2 defined below)
  19947. if ( this.closed || intPoint > 0 ) {
  19948. p0 = points[ ( intPoint - 1 ) % l ];
  19949. } else {
  19950. // extrapolate first point
  19951. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19952. p0 = tmp;
  19953. }
  19954. const p1 = points[ intPoint % l ];
  19955. const p2 = points[ ( intPoint + 1 ) % l ];
  19956. if ( this.closed || intPoint + 2 < l ) {
  19957. p3 = points[ ( intPoint + 2 ) % l ];
  19958. } else {
  19959. // extrapolate last point
  19960. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19961. p3 = tmp;
  19962. }
  19963. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19964. // init Centripetal / Chordal Catmull-Rom
  19965. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19966. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19967. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19968. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19969. // safety check for repeated points
  19970. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19971. if ( dt0 < 1e-4 ) dt0 = dt1;
  19972. if ( dt2 < 1e-4 ) dt2 = dt1;
  19973. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19974. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19975. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19976. } else if ( this.curveType === 'catmullrom' ) {
  19977. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19978. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19979. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19980. }
  19981. point.set(
  19982. px.calc( weight ),
  19983. py.calc( weight ),
  19984. pz.calc( weight )
  19985. );
  19986. return point;
  19987. }
  19988. copy( source ) {
  19989. super.copy( source );
  19990. this.points = [];
  19991. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19992. const point = source.points[ i ];
  19993. this.points.push( point.clone() );
  19994. }
  19995. this.closed = source.closed;
  19996. this.curveType = source.curveType;
  19997. this.tension = source.tension;
  19998. return this;
  19999. }
  20000. toJSON() {
  20001. const data = super.toJSON();
  20002. data.points = [];
  20003. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20004. const point = this.points[ i ];
  20005. data.points.push( point.toArray() );
  20006. }
  20007. data.closed = this.closed;
  20008. data.curveType = this.curveType;
  20009. data.tension = this.tension;
  20010. return data;
  20011. }
  20012. fromJSON( json ) {
  20013. super.fromJSON( json );
  20014. this.points = [];
  20015. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20016. const point = json.points[ i ];
  20017. this.points.push( new Vector3().fromArray( point ) );
  20018. }
  20019. this.closed = json.closed;
  20020. this.curveType = json.curveType;
  20021. this.tension = json.tension;
  20022. return this;
  20023. }
  20024. }
  20025. /**
  20026. * Bezier Curves formulas obtained from
  20027. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  20028. */
  20029. function CatmullRom( t, p0, p1, p2, p3 ) {
  20030. const v0 = ( p2 - p0 ) * 0.5;
  20031. const v1 = ( p3 - p1 ) * 0.5;
  20032. const t2 = t * t;
  20033. const t3 = t * t2;
  20034. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20035. }
  20036. //
  20037. function QuadraticBezierP0( t, p ) {
  20038. const k = 1 - t;
  20039. return k * k * p;
  20040. }
  20041. function QuadraticBezierP1( t, p ) {
  20042. return 2 * ( 1 - t ) * t * p;
  20043. }
  20044. function QuadraticBezierP2( t, p ) {
  20045. return t * t * p;
  20046. }
  20047. function QuadraticBezier( t, p0, p1, p2 ) {
  20048. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  20049. QuadraticBezierP2( t, p2 );
  20050. }
  20051. //
  20052. function CubicBezierP0( t, p ) {
  20053. const k = 1 - t;
  20054. return k * k * k * p;
  20055. }
  20056. function CubicBezierP1( t, p ) {
  20057. const k = 1 - t;
  20058. return 3 * k * k * t * p;
  20059. }
  20060. function CubicBezierP2( t, p ) {
  20061. return 3 * ( 1 - t ) * t * t * p;
  20062. }
  20063. function CubicBezierP3( t, p ) {
  20064. return t * t * t * p;
  20065. }
  20066. function CubicBezier( t, p0, p1, p2, p3 ) {
  20067. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  20068. CubicBezierP3( t, p3 );
  20069. }
  20070. class CubicBezierCurve extends Curve {
  20071. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  20072. super();
  20073. this.isCubicBezierCurve = true;
  20074. this.type = 'CubicBezierCurve';
  20075. this.v0 = v0;
  20076. this.v1 = v1;
  20077. this.v2 = v2;
  20078. this.v3 = v3;
  20079. }
  20080. getPoint( t, optionalTarget = new Vector2() ) {
  20081. const point = optionalTarget;
  20082. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20083. point.set(
  20084. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20085. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  20086. );
  20087. return point;
  20088. }
  20089. copy( source ) {
  20090. super.copy( source );
  20091. this.v0.copy( source.v0 );
  20092. this.v1.copy( source.v1 );
  20093. this.v2.copy( source.v2 );
  20094. this.v3.copy( source.v3 );
  20095. return this;
  20096. }
  20097. toJSON() {
  20098. const data = super.toJSON();
  20099. data.v0 = this.v0.toArray();
  20100. data.v1 = this.v1.toArray();
  20101. data.v2 = this.v2.toArray();
  20102. data.v3 = this.v3.toArray();
  20103. return data;
  20104. }
  20105. fromJSON( json ) {
  20106. super.fromJSON( json );
  20107. this.v0.fromArray( json.v0 );
  20108. this.v1.fromArray( json.v1 );
  20109. this.v2.fromArray( json.v2 );
  20110. this.v3.fromArray( json.v3 );
  20111. return this;
  20112. }
  20113. }
  20114. class CubicBezierCurve3 extends Curve {
  20115. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  20116. super();
  20117. this.isCubicBezierCurve3 = true;
  20118. this.type = 'CubicBezierCurve3';
  20119. this.v0 = v0;
  20120. this.v1 = v1;
  20121. this.v2 = v2;
  20122. this.v3 = v3;
  20123. }
  20124. getPoint( t, optionalTarget = new Vector3() ) {
  20125. const point = optionalTarget;
  20126. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  20127. point.set(
  20128. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  20129. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  20130. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  20131. );
  20132. return point;
  20133. }
  20134. copy( source ) {
  20135. super.copy( source );
  20136. this.v0.copy( source.v0 );
  20137. this.v1.copy( source.v1 );
  20138. this.v2.copy( source.v2 );
  20139. this.v3.copy( source.v3 );
  20140. return this;
  20141. }
  20142. toJSON() {
  20143. const data = super.toJSON();
  20144. data.v0 = this.v0.toArray();
  20145. data.v1 = this.v1.toArray();
  20146. data.v2 = this.v2.toArray();
  20147. data.v3 = this.v3.toArray();
  20148. return data;
  20149. }
  20150. fromJSON( json ) {
  20151. super.fromJSON( json );
  20152. this.v0.fromArray( json.v0 );
  20153. this.v1.fromArray( json.v1 );
  20154. this.v2.fromArray( json.v2 );
  20155. this.v3.fromArray( json.v3 );
  20156. return this;
  20157. }
  20158. }
  20159. class LineCurve extends Curve {
  20160. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  20161. super();
  20162. this.isLineCurve = true;
  20163. this.type = 'LineCurve';
  20164. this.v1 = v1;
  20165. this.v2 = v2;
  20166. }
  20167. getPoint( t, optionalTarget = new Vector2() ) {
  20168. const point = optionalTarget;
  20169. if ( t === 1 ) {
  20170. point.copy( this.v2 );
  20171. } else {
  20172. point.copy( this.v2 ).sub( this.v1 );
  20173. point.multiplyScalar( t ).add( this.v1 );
  20174. }
  20175. return point;
  20176. }
  20177. // Line curve is linear, so we can overwrite default getPointAt
  20178. getPointAt( u, optionalTarget ) {
  20179. return this.getPoint( u, optionalTarget );
  20180. }
  20181. getTangent( t, optionalTarget = new Vector2() ) {
  20182. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20183. }
  20184. getTangentAt( u, optionalTarget ) {
  20185. return this.getTangent( u, optionalTarget );
  20186. }
  20187. copy( source ) {
  20188. super.copy( source );
  20189. this.v1.copy( source.v1 );
  20190. this.v2.copy( source.v2 );
  20191. return this;
  20192. }
  20193. toJSON() {
  20194. const data = super.toJSON();
  20195. data.v1 = this.v1.toArray();
  20196. data.v2 = this.v2.toArray();
  20197. return data;
  20198. }
  20199. fromJSON( json ) {
  20200. super.fromJSON( json );
  20201. this.v1.fromArray( json.v1 );
  20202. this.v2.fromArray( json.v2 );
  20203. return this;
  20204. }
  20205. }
  20206. class LineCurve3 extends Curve {
  20207. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  20208. super();
  20209. this.isLineCurve3 = true;
  20210. this.type = 'LineCurve3';
  20211. this.v1 = v1;
  20212. this.v2 = v2;
  20213. }
  20214. getPoint( t, optionalTarget = new Vector3() ) {
  20215. const point = optionalTarget;
  20216. if ( t === 1 ) {
  20217. point.copy( this.v2 );
  20218. } else {
  20219. point.copy( this.v2 ).sub( this.v1 );
  20220. point.multiplyScalar( t ).add( this.v1 );
  20221. }
  20222. return point;
  20223. }
  20224. // Line curve is linear, so we can overwrite default getPointAt
  20225. getPointAt( u, optionalTarget ) {
  20226. return this.getPoint( u, optionalTarget );
  20227. }
  20228. getTangent( t, optionalTarget = new Vector3() ) {
  20229. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20230. }
  20231. getTangentAt( u, optionalTarget ) {
  20232. return this.getTangent( u, optionalTarget );
  20233. }
  20234. copy( source ) {
  20235. super.copy( source );
  20236. this.v1.copy( source.v1 );
  20237. this.v2.copy( source.v2 );
  20238. return this;
  20239. }
  20240. toJSON() {
  20241. const data = super.toJSON();
  20242. data.v1 = this.v1.toArray();
  20243. data.v2 = this.v2.toArray();
  20244. return data;
  20245. }
  20246. fromJSON( json ) {
  20247. super.fromJSON( json );
  20248. this.v1.fromArray( json.v1 );
  20249. this.v2.fromArray( json.v2 );
  20250. return this;
  20251. }
  20252. }
  20253. class QuadraticBezierCurve extends Curve {
  20254. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  20255. super();
  20256. this.isQuadraticBezierCurve = true;
  20257. this.type = 'QuadraticBezierCurve';
  20258. this.v0 = v0;
  20259. this.v1 = v1;
  20260. this.v2 = v2;
  20261. }
  20262. getPoint( t, optionalTarget = new Vector2() ) {
  20263. const point = optionalTarget;
  20264. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20265. point.set(
  20266. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20267. QuadraticBezier( t, v0.y, v1.y, v2.y )
  20268. );
  20269. return point;
  20270. }
  20271. copy( source ) {
  20272. super.copy( source );
  20273. this.v0.copy( source.v0 );
  20274. this.v1.copy( source.v1 );
  20275. this.v2.copy( source.v2 );
  20276. return this;
  20277. }
  20278. toJSON() {
  20279. const data = super.toJSON();
  20280. data.v0 = this.v0.toArray();
  20281. data.v1 = this.v1.toArray();
  20282. data.v2 = this.v2.toArray();
  20283. return data;
  20284. }
  20285. fromJSON( json ) {
  20286. super.fromJSON( json );
  20287. this.v0.fromArray( json.v0 );
  20288. this.v1.fromArray( json.v1 );
  20289. this.v2.fromArray( json.v2 );
  20290. return this;
  20291. }
  20292. }
  20293. class QuadraticBezierCurve3 extends Curve {
  20294. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  20295. super();
  20296. this.isQuadraticBezierCurve3 = true;
  20297. this.type = 'QuadraticBezierCurve3';
  20298. this.v0 = v0;
  20299. this.v1 = v1;
  20300. this.v2 = v2;
  20301. }
  20302. getPoint( t, optionalTarget = new Vector3() ) {
  20303. const point = optionalTarget;
  20304. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20305. point.set(
  20306. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20307. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  20308. QuadraticBezier( t, v0.z, v1.z, v2.z )
  20309. );
  20310. return point;
  20311. }
  20312. copy( source ) {
  20313. super.copy( source );
  20314. this.v0.copy( source.v0 );
  20315. this.v1.copy( source.v1 );
  20316. this.v2.copy( source.v2 );
  20317. return this;
  20318. }
  20319. toJSON() {
  20320. const data = super.toJSON();
  20321. data.v0 = this.v0.toArray();
  20322. data.v1 = this.v1.toArray();
  20323. data.v2 = this.v2.toArray();
  20324. return data;
  20325. }
  20326. fromJSON( json ) {
  20327. super.fromJSON( json );
  20328. this.v0.fromArray( json.v0 );
  20329. this.v1.fromArray( json.v1 );
  20330. this.v2.fromArray( json.v2 );
  20331. return this;
  20332. }
  20333. }
  20334. class SplineCurve extends Curve {
  20335. constructor( points = [] ) {
  20336. super();
  20337. this.isSplineCurve = true;
  20338. this.type = 'SplineCurve';
  20339. this.points = points;
  20340. }
  20341. getPoint( t, optionalTarget = new Vector2() ) {
  20342. const point = optionalTarget;
  20343. const points = this.points;
  20344. const p = ( points.length - 1 ) * t;
  20345. const intPoint = Math.floor( p );
  20346. const weight = p - intPoint;
  20347. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20348. const p1 = points[ intPoint ];
  20349. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20350. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20351. point.set(
  20352. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  20353. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  20354. );
  20355. return point;
  20356. }
  20357. copy( source ) {
  20358. super.copy( source );
  20359. this.points = [];
  20360. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  20361. const point = source.points[ i ];
  20362. this.points.push( point.clone() );
  20363. }
  20364. return this;
  20365. }
  20366. toJSON() {
  20367. const data = super.toJSON();
  20368. data.points = [];
  20369. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20370. const point = this.points[ i ];
  20371. data.points.push( point.toArray() );
  20372. }
  20373. return data;
  20374. }
  20375. fromJSON( json ) {
  20376. super.fromJSON( json );
  20377. this.points = [];
  20378. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20379. const point = json.points[ i ];
  20380. this.points.push( new Vector2().fromArray( point ) );
  20381. }
  20382. return this;
  20383. }
  20384. }
  20385. var Curves = /*#__PURE__*/Object.freeze({
  20386. __proto__: null,
  20387. ArcCurve: ArcCurve,
  20388. CatmullRomCurve3: CatmullRomCurve3,
  20389. CubicBezierCurve: CubicBezierCurve,
  20390. CubicBezierCurve3: CubicBezierCurve3,
  20391. EllipseCurve: EllipseCurve,
  20392. LineCurve: LineCurve,
  20393. LineCurve3: LineCurve3,
  20394. QuadraticBezierCurve: QuadraticBezierCurve,
  20395. QuadraticBezierCurve3: QuadraticBezierCurve3,
  20396. SplineCurve: SplineCurve
  20397. });
  20398. /**************************************************************
  20399. * Curved Path - a curve path is simply a array of connected
  20400. * curves, but retains the api of a curve
  20401. **************************************************************/
  20402. class CurvePath extends Curve {
  20403. constructor() {
  20404. super();
  20405. this.type = 'CurvePath';
  20406. this.curves = [];
  20407. this.autoClose = false; // Automatically closes the path
  20408. }
  20409. add( curve ) {
  20410. this.curves.push( curve );
  20411. }
  20412. closePath() {
  20413. // Add a line curve if start and end of lines are not connected
  20414. const startPoint = this.curves[ 0 ].getPoint( 0 );
  20415. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20416. if ( ! startPoint.equals( endPoint ) ) {
  20417. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20418. }
  20419. return this;
  20420. }
  20421. // To get accurate point with reference to
  20422. // entire path distance at time t,
  20423. // following has to be done:
  20424. // 1. Length of each sub path have to be known
  20425. // 2. Locate and identify type of curve
  20426. // 3. Get t for the curve
  20427. // 4. Return curve.getPointAt(t')
  20428. getPoint( t, optionalTarget ) {
  20429. const d = t * this.getLength();
  20430. const curveLengths = this.getCurveLengths();
  20431. let i = 0;
  20432. // To think about boundaries points.
  20433. while ( i < curveLengths.length ) {
  20434. if ( curveLengths[ i ] >= d ) {
  20435. const diff = curveLengths[ i ] - d;
  20436. const curve = this.curves[ i ];
  20437. const segmentLength = curve.getLength();
  20438. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20439. return curve.getPointAt( u, optionalTarget );
  20440. }
  20441. i ++;
  20442. }
  20443. return null;
  20444. // loop where sum != 0, sum > d , sum+1 <d
  20445. }
  20446. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20447. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20448. // getPoint() depends on getLength
  20449. getLength() {
  20450. const lens = this.getCurveLengths();
  20451. return lens[ lens.length - 1 ];
  20452. }
  20453. // cacheLengths must be recalculated.
  20454. updateArcLengths() {
  20455. this.needsUpdate = true;
  20456. this.cacheLengths = null;
  20457. this.getCurveLengths();
  20458. }
  20459. // Compute lengths and cache them
  20460. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20461. getCurveLengths() {
  20462. // We use cache values if curves and cache array are same length
  20463. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20464. return this.cacheLengths;
  20465. }
  20466. // Get length of sub-curve
  20467. // Push sums into cached array
  20468. const lengths = [];
  20469. let sums = 0;
  20470. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20471. sums += this.curves[ i ].getLength();
  20472. lengths.push( sums );
  20473. }
  20474. this.cacheLengths = lengths;
  20475. return lengths;
  20476. }
  20477. getSpacedPoints( divisions = 40 ) {
  20478. const points = [];
  20479. for ( let i = 0; i <= divisions; i ++ ) {
  20480. points.push( this.getPoint( i / divisions ) );
  20481. }
  20482. if ( this.autoClose ) {
  20483. points.push( points[ 0 ] );
  20484. }
  20485. return points;
  20486. }
  20487. getPoints( divisions = 12 ) {
  20488. const points = [];
  20489. let last;
  20490. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20491. const curve = curves[ i ];
  20492. const resolution = curve.isEllipseCurve ? divisions * 2
  20493. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  20494. : curve.isSplineCurve ? divisions * curve.points.length
  20495. : divisions;
  20496. const pts = curve.getPoints( resolution );
  20497. for ( let j = 0; j < pts.length; j ++ ) {
  20498. const point = pts[ j ];
  20499. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20500. points.push( point );
  20501. last = point;
  20502. }
  20503. }
  20504. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20505. points.push( points[ 0 ] );
  20506. }
  20507. return points;
  20508. }
  20509. copy( source ) {
  20510. super.copy( source );
  20511. this.curves = [];
  20512. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  20513. const curve = source.curves[ i ];
  20514. this.curves.push( curve.clone() );
  20515. }
  20516. this.autoClose = source.autoClose;
  20517. return this;
  20518. }
  20519. toJSON() {
  20520. const data = super.toJSON();
  20521. data.autoClose = this.autoClose;
  20522. data.curves = [];
  20523. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20524. const curve = this.curves[ i ];
  20525. data.curves.push( curve.toJSON() );
  20526. }
  20527. return data;
  20528. }
  20529. fromJSON( json ) {
  20530. super.fromJSON( json );
  20531. this.autoClose = json.autoClose;
  20532. this.curves = [];
  20533. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  20534. const curve = json.curves[ i ];
  20535. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  20536. }
  20537. return this;
  20538. }
  20539. }
  20540. class Path extends CurvePath {
  20541. constructor( points ) {
  20542. super();
  20543. this.type = 'Path';
  20544. this.currentPoint = new Vector2();
  20545. if ( points ) {
  20546. this.setFromPoints( points );
  20547. }
  20548. }
  20549. setFromPoints( points ) {
  20550. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  20551. for ( let i = 1, l = points.length; i < l; i ++ ) {
  20552. this.lineTo( points[ i ].x, points[ i ].y );
  20553. }
  20554. return this;
  20555. }
  20556. moveTo( x, y ) {
  20557. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20558. return this;
  20559. }
  20560. lineTo( x, y ) {
  20561. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20562. this.curves.push( curve );
  20563. this.currentPoint.set( x, y );
  20564. return this;
  20565. }
  20566. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  20567. const curve = new QuadraticBezierCurve(
  20568. this.currentPoint.clone(),
  20569. new Vector2( aCPx, aCPy ),
  20570. new Vector2( aX, aY )
  20571. );
  20572. this.curves.push( curve );
  20573. this.currentPoint.set( aX, aY );
  20574. return this;
  20575. }
  20576. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20577. const curve = new CubicBezierCurve(
  20578. this.currentPoint.clone(),
  20579. new Vector2( aCP1x, aCP1y ),
  20580. new Vector2( aCP2x, aCP2y ),
  20581. new Vector2( aX, aY )
  20582. );
  20583. this.curves.push( curve );
  20584. this.currentPoint.set( aX, aY );
  20585. return this;
  20586. }
  20587. splineThru( pts /*Array of Vector*/ ) {
  20588. const npts = [ this.currentPoint.clone() ].concat( pts );
  20589. const curve = new SplineCurve( npts );
  20590. this.curves.push( curve );
  20591. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20592. return this;
  20593. }
  20594. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20595. const x0 = this.currentPoint.x;
  20596. const y0 = this.currentPoint.y;
  20597. this.absarc( aX + x0, aY + y0, aRadius,
  20598. aStartAngle, aEndAngle, aClockwise );
  20599. return this;
  20600. }
  20601. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20602. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20603. return this;
  20604. }
  20605. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20606. const x0 = this.currentPoint.x;
  20607. const y0 = this.currentPoint.y;
  20608. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20609. return this;
  20610. }
  20611. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20612. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20613. if ( this.curves.length > 0 ) {
  20614. // if a previous curve is present, attempt to join
  20615. const firstPoint = curve.getPoint( 0 );
  20616. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20617. this.lineTo( firstPoint.x, firstPoint.y );
  20618. }
  20619. }
  20620. this.curves.push( curve );
  20621. const lastPoint = curve.getPoint( 1 );
  20622. this.currentPoint.copy( lastPoint );
  20623. return this;
  20624. }
  20625. copy( source ) {
  20626. super.copy( source );
  20627. this.currentPoint.copy( source.currentPoint );
  20628. return this;
  20629. }
  20630. toJSON() {
  20631. const data = super.toJSON();
  20632. data.currentPoint = this.currentPoint.toArray();
  20633. return data;
  20634. }
  20635. fromJSON( json ) {
  20636. super.fromJSON( json );
  20637. this.currentPoint.fromArray( json.currentPoint );
  20638. return this;
  20639. }
  20640. }
  20641. class LatheGeometry extends BufferGeometry {
  20642. 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 ) {
  20643. super();
  20644. this.type = 'LatheGeometry';
  20645. this.parameters = {
  20646. points: points,
  20647. segments: segments,
  20648. phiStart: phiStart,
  20649. phiLength: phiLength
  20650. };
  20651. segments = Math.floor( segments );
  20652. // clamp phiLength so it's in range of [ 0, 2PI ]
  20653. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20654. // buffers
  20655. const indices = [];
  20656. const vertices = [];
  20657. const uvs = [];
  20658. const initNormals = [];
  20659. const normals = [];
  20660. // helper variables
  20661. const inverseSegments = 1.0 / segments;
  20662. const vertex = new Vector3();
  20663. const uv = new Vector2();
  20664. const normal = new Vector3();
  20665. const curNormal = new Vector3();
  20666. const prevNormal = new Vector3();
  20667. let dx = 0;
  20668. let dy = 0;
  20669. // pre-compute normals for initial "meridian"
  20670. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20671. switch ( j ) {
  20672. case 0: // special handling for 1st vertex on path
  20673. dx = points[ j + 1 ].x - points[ j ].x;
  20674. dy = points[ j + 1 ].y - points[ j ].y;
  20675. normal.x = dy * 1.0;
  20676. normal.y = - dx;
  20677. normal.z = dy * 0.0;
  20678. prevNormal.copy( normal );
  20679. normal.normalize();
  20680. initNormals.push( normal.x, normal.y, normal.z );
  20681. break;
  20682. case ( points.length - 1 ): // special handling for last Vertex on path
  20683. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20684. break;
  20685. default: // default handling for all vertices in between
  20686. dx = points[ j + 1 ].x - points[ j ].x;
  20687. dy = points[ j + 1 ].y - points[ j ].y;
  20688. normal.x = dy * 1.0;
  20689. normal.y = - dx;
  20690. normal.z = dy * 0.0;
  20691. curNormal.copy( normal );
  20692. normal.x += prevNormal.x;
  20693. normal.y += prevNormal.y;
  20694. normal.z += prevNormal.z;
  20695. normal.normalize();
  20696. initNormals.push( normal.x, normal.y, normal.z );
  20697. prevNormal.copy( curNormal );
  20698. }
  20699. }
  20700. // generate vertices, uvs and normals
  20701. for ( let i = 0; i <= segments; i ++ ) {
  20702. const phi = phiStart + i * inverseSegments * phiLength;
  20703. const sin = Math.sin( phi );
  20704. const cos = Math.cos( phi );
  20705. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20706. // vertex
  20707. vertex.x = points[ j ].x * sin;
  20708. vertex.y = points[ j ].y;
  20709. vertex.z = points[ j ].x * cos;
  20710. vertices.push( vertex.x, vertex.y, vertex.z );
  20711. // uv
  20712. uv.x = i / segments;
  20713. uv.y = j / ( points.length - 1 );
  20714. uvs.push( uv.x, uv.y );
  20715. // normal
  20716. const x = initNormals[ 3 * j + 0 ] * sin;
  20717. const y = initNormals[ 3 * j + 1 ];
  20718. const z = initNormals[ 3 * j + 0 ] * cos;
  20719. normals.push( x, y, z );
  20720. }
  20721. }
  20722. // indices
  20723. for ( let i = 0; i < segments; i ++ ) {
  20724. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20725. const base = j + i * points.length;
  20726. const a = base;
  20727. const b = base + points.length;
  20728. const c = base + points.length + 1;
  20729. const d = base + 1;
  20730. // faces
  20731. indices.push( a, b, d );
  20732. indices.push( c, d, b );
  20733. }
  20734. }
  20735. // build geometry
  20736. this.setIndex( indices );
  20737. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20738. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20739. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20740. }
  20741. copy( source ) {
  20742. super.copy( source );
  20743. this.parameters = Object.assign( {}, source.parameters );
  20744. return this;
  20745. }
  20746. static fromJSON( data ) {
  20747. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20748. }
  20749. }
  20750. class CapsuleGeometry extends LatheGeometry {
  20751. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20752. const path = new Path();
  20753. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20754. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20755. super( path.getPoints( capSegments ), radialSegments );
  20756. this.type = 'CapsuleGeometry';
  20757. this.parameters = {
  20758. radius: radius,
  20759. length: length,
  20760. capSegments: capSegments,
  20761. radialSegments: radialSegments,
  20762. };
  20763. }
  20764. static fromJSON( data ) {
  20765. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20766. }
  20767. }
  20768. class CircleGeometry extends BufferGeometry {
  20769. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20770. super();
  20771. this.type = 'CircleGeometry';
  20772. this.parameters = {
  20773. radius: radius,
  20774. segments: segments,
  20775. thetaStart: thetaStart,
  20776. thetaLength: thetaLength
  20777. };
  20778. segments = Math.max( 3, segments );
  20779. // buffers
  20780. const indices = [];
  20781. const vertices = [];
  20782. const normals = [];
  20783. const uvs = [];
  20784. // helper variables
  20785. const vertex = new Vector3();
  20786. const uv = new Vector2();
  20787. // center point
  20788. vertices.push( 0, 0, 0 );
  20789. normals.push( 0, 0, 1 );
  20790. uvs.push( 0.5, 0.5 );
  20791. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20792. const segment = thetaStart + s / segments * thetaLength;
  20793. // vertex
  20794. vertex.x = radius * Math.cos( segment );
  20795. vertex.y = radius * Math.sin( segment );
  20796. vertices.push( vertex.x, vertex.y, vertex.z );
  20797. // normal
  20798. normals.push( 0, 0, 1 );
  20799. // uvs
  20800. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20801. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20802. uvs.push( uv.x, uv.y );
  20803. }
  20804. // indices
  20805. for ( let i = 1; i <= segments; i ++ ) {
  20806. indices.push( i, i + 1, 0 );
  20807. }
  20808. // build geometry
  20809. this.setIndex( indices );
  20810. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20811. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20812. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20813. }
  20814. copy( source ) {
  20815. super.copy( source );
  20816. this.parameters = Object.assign( {}, source.parameters );
  20817. return this;
  20818. }
  20819. static fromJSON( data ) {
  20820. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20821. }
  20822. }
  20823. class CylinderGeometry extends BufferGeometry {
  20824. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20825. super();
  20826. this.type = 'CylinderGeometry';
  20827. this.parameters = {
  20828. radiusTop: radiusTop,
  20829. radiusBottom: radiusBottom,
  20830. height: height,
  20831. radialSegments: radialSegments,
  20832. heightSegments: heightSegments,
  20833. openEnded: openEnded,
  20834. thetaStart: thetaStart,
  20835. thetaLength: thetaLength
  20836. };
  20837. const scope = this;
  20838. radialSegments = Math.floor( radialSegments );
  20839. heightSegments = Math.floor( heightSegments );
  20840. // buffers
  20841. const indices = [];
  20842. const vertices = [];
  20843. const normals = [];
  20844. const uvs = [];
  20845. // helper variables
  20846. let index = 0;
  20847. const indexArray = [];
  20848. const halfHeight = height / 2;
  20849. let groupStart = 0;
  20850. // generate geometry
  20851. generateTorso();
  20852. if ( openEnded === false ) {
  20853. if ( radiusTop > 0 ) generateCap( true );
  20854. if ( radiusBottom > 0 ) generateCap( false );
  20855. }
  20856. // build geometry
  20857. this.setIndex( indices );
  20858. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20859. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20860. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20861. function generateTorso() {
  20862. const normal = new Vector3();
  20863. const vertex = new Vector3();
  20864. let groupCount = 0;
  20865. // this will be used to calculate the normal
  20866. const slope = ( radiusBottom - radiusTop ) / height;
  20867. // generate vertices, normals and uvs
  20868. for ( let y = 0; y <= heightSegments; y ++ ) {
  20869. const indexRow = [];
  20870. const v = y / heightSegments;
  20871. // calculate the radius of the current row
  20872. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20873. for ( let x = 0; x <= radialSegments; x ++ ) {
  20874. const u = x / radialSegments;
  20875. const theta = u * thetaLength + thetaStart;
  20876. const sinTheta = Math.sin( theta );
  20877. const cosTheta = Math.cos( theta );
  20878. // vertex
  20879. vertex.x = radius * sinTheta;
  20880. vertex.y = - v * height + halfHeight;
  20881. vertex.z = radius * cosTheta;
  20882. vertices.push( vertex.x, vertex.y, vertex.z );
  20883. // normal
  20884. normal.set( sinTheta, slope, cosTheta ).normalize();
  20885. normals.push( normal.x, normal.y, normal.z );
  20886. // uv
  20887. uvs.push( u, 1 - v );
  20888. // save index of vertex in respective row
  20889. indexRow.push( index ++ );
  20890. }
  20891. // now save vertices of the row in our index array
  20892. indexArray.push( indexRow );
  20893. }
  20894. // generate indices
  20895. for ( let x = 0; x < radialSegments; x ++ ) {
  20896. for ( let y = 0; y < heightSegments; y ++ ) {
  20897. // we use the index array to access the correct indices
  20898. const a = indexArray[ y ][ x ];
  20899. const b = indexArray[ y + 1 ][ x ];
  20900. const c = indexArray[ y + 1 ][ x + 1 ];
  20901. const d = indexArray[ y ][ x + 1 ];
  20902. // faces
  20903. indices.push( a, b, d );
  20904. indices.push( b, c, d );
  20905. // update group counter
  20906. groupCount += 6;
  20907. }
  20908. }
  20909. // add a group to the geometry. this will ensure multi material support
  20910. scope.addGroup( groupStart, groupCount, 0 );
  20911. // calculate new start value for groups
  20912. groupStart += groupCount;
  20913. }
  20914. function generateCap( top ) {
  20915. // save the index of the first center vertex
  20916. const centerIndexStart = index;
  20917. const uv = new Vector2();
  20918. const vertex = new Vector3();
  20919. let groupCount = 0;
  20920. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20921. const sign = ( top === true ) ? 1 : - 1;
  20922. // first we generate the center vertex data of the cap.
  20923. // because the geometry needs one set of uvs per face,
  20924. // we must generate a center vertex per face/segment
  20925. for ( let x = 1; x <= radialSegments; x ++ ) {
  20926. // vertex
  20927. vertices.push( 0, halfHeight * sign, 0 );
  20928. // normal
  20929. normals.push( 0, sign, 0 );
  20930. // uv
  20931. uvs.push( 0.5, 0.5 );
  20932. // increase index
  20933. index ++;
  20934. }
  20935. // save the index of the last center vertex
  20936. const centerIndexEnd = index;
  20937. // now we generate the surrounding vertices, normals and uvs
  20938. for ( let x = 0; x <= radialSegments; x ++ ) {
  20939. const u = x / radialSegments;
  20940. const theta = u * thetaLength + thetaStart;
  20941. const cosTheta = Math.cos( theta );
  20942. const sinTheta = Math.sin( theta );
  20943. // vertex
  20944. vertex.x = radius * sinTheta;
  20945. vertex.y = halfHeight * sign;
  20946. vertex.z = radius * cosTheta;
  20947. vertices.push( vertex.x, vertex.y, vertex.z );
  20948. // normal
  20949. normals.push( 0, sign, 0 );
  20950. // uv
  20951. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20952. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20953. uvs.push( uv.x, uv.y );
  20954. // increase index
  20955. index ++;
  20956. }
  20957. // generate indices
  20958. for ( let x = 0; x < radialSegments; x ++ ) {
  20959. const c = centerIndexStart + x;
  20960. const i = centerIndexEnd + x;
  20961. if ( top === true ) {
  20962. // face top
  20963. indices.push( i, i + 1, c );
  20964. } else {
  20965. // face bottom
  20966. indices.push( i + 1, i, c );
  20967. }
  20968. groupCount += 3;
  20969. }
  20970. // add a group to the geometry. this will ensure multi material support
  20971. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20972. // calculate new start value for groups
  20973. groupStart += groupCount;
  20974. }
  20975. }
  20976. copy( source ) {
  20977. super.copy( source );
  20978. this.parameters = Object.assign( {}, source.parameters );
  20979. return this;
  20980. }
  20981. static fromJSON( data ) {
  20982. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20983. }
  20984. }
  20985. class ConeGeometry extends CylinderGeometry {
  20986. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20987. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20988. this.type = 'ConeGeometry';
  20989. this.parameters = {
  20990. radius: radius,
  20991. height: height,
  20992. radialSegments: radialSegments,
  20993. heightSegments: heightSegments,
  20994. openEnded: openEnded,
  20995. thetaStart: thetaStart,
  20996. thetaLength: thetaLength
  20997. };
  20998. }
  20999. static fromJSON( data ) {
  21000. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  21001. }
  21002. }
  21003. class PolyhedronGeometry extends BufferGeometry {
  21004. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  21005. super();
  21006. this.type = 'PolyhedronGeometry';
  21007. this.parameters = {
  21008. vertices: vertices,
  21009. indices: indices,
  21010. radius: radius,
  21011. detail: detail
  21012. };
  21013. // default buffer data
  21014. const vertexBuffer = [];
  21015. const uvBuffer = [];
  21016. // the subdivision creates the vertex buffer data
  21017. subdivide( detail );
  21018. // all vertices should lie on a conceptual sphere with a given radius
  21019. applyRadius( radius );
  21020. // finally, create the uv data
  21021. generateUVs();
  21022. // build non-indexed geometry
  21023. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  21024. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  21025. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  21026. if ( detail === 0 ) {
  21027. this.computeVertexNormals(); // flat normals
  21028. } else {
  21029. this.normalizeNormals(); // smooth normals
  21030. }
  21031. // helper functions
  21032. function subdivide( detail ) {
  21033. const a = new Vector3();
  21034. const b = new Vector3();
  21035. const c = new Vector3();
  21036. // iterate over all faces and apply a subdivision with the given detail value
  21037. for ( let i = 0; i < indices.length; i += 3 ) {
  21038. // get the vertices of the face
  21039. getVertexByIndex( indices[ i + 0 ], a );
  21040. getVertexByIndex( indices[ i + 1 ], b );
  21041. getVertexByIndex( indices[ i + 2 ], c );
  21042. // perform subdivision
  21043. subdivideFace( a, b, c, detail );
  21044. }
  21045. }
  21046. function subdivideFace( a, b, c, detail ) {
  21047. const cols = detail + 1;
  21048. // we use this multidimensional array as a data structure for creating the subdivision
  21049. const v = [];
  21050. // construct all of the vertices for this subdivision
  21051. for ( let i = 0; i <= cols; i ++ ) {
  21052. v[ i ] = [];
  21053. const aj = a.clone().lerp( c, i / cols );
  21054. const bj = b.clone().lerp( c, i / cols );
  21055. const rows = cols - i;
  21056. for ( let j = 0; j <= rows; j ++ ) {
  21057. if ( j === 0 && i === cols ) {
  21058. v[ i ][ j ] = aj;
  21059. } else {
  21060. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  21061. }
  21062. }
  21063. }
  21064. // construct all of the faces
  21065. for ( let i = 0; i < cols; i ++ ) {
  21066. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  21067. const k = Math.floor( j / 2 );
  21068. if ( j % 2 === 0 ) {
  21069. pushVertex( v[ i ][ k + 1 ] );
  21070. pushVertex( v[ i + 1 ][ k ] );
  21071. pushVertex( v[ i ][ k ] );
  21072. } else {
  21073. pushVertex( v[ i ][ k + 1 ] );
  21074. pushVertex( v[ i + 1 ][ k + 1 ] );
  21075. pushVertex( v[ i + 1 ][ k ] );
  21076. }
  21077. }
  21078. }
  21079. }
  21080. function applyRadius( radius ) {
  21081. const vertex = new Vector3();
  21082. // iterate over the entire buffer and apply the radius to each vertex
  21083. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  21084. vertex.x = vertexBuffer[ i + 0 ];
  21085. vertex.y = vertexBuffer[ i + 1 ];
  21086. vertex.z = vertexBuffer[ i + 2 ];
  21087. vertex.normalize().multiplyScalar( radius );
  21088. vertexBuffer[ i + 0 ] = vertex.x;
  21089. vertexBuffer[ i + 1 ] = vertex.y;
  21090. vertexBuffer[ i + 2 ] = vertex.z;
  21091. }
  21092. }
  21093. function generateUVs() {
  21094. const vertex = new Vector3();
  21095. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  21096. vertex.x = vertexBuffer[ i + 0 ];
  21097. vertex.y = vertexBuffer[ i + 1 ];
  21098. vertex.z = vertexBuffer[ i + 2 ];
  21099. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  21100. const v = inclination( vertex ) / Math.PI + 0.5;
  21101. uvBuffer.push( u, 1 - v );
  21102. }
  21103. correctUVs();
  21104. correctSeam();
  21105. }
  21106. function correctSeam() {
  21107. // handle case when face straddles the seam, see #3269
  21108. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  21109. // uv data of a single face
  21110. const x0 = uvBuffer[ i + 0 ];
  21111. const x1 = uvBuffer[ i + 2 ];
  21112. const x2 = uvBuffer[ i + 4 ];
  21113. const max = Math.max( x0, x1, x2 );
  21114. const min = Math.min( x0, x1, x2 );
  21115. // 0.9 is somewhat arbitrary
  21116. if ( max > 0.9 && min < 0.1 ) {
  21117. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  21118. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  21119. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  21120. }
  21121. }
  21122. }
  21123. function pushVertex( vertex ) {
  21124. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  21125. }
  21126. function getVertexByIndex( index, vertex ) {
  21127. const stride = index * 3;
  21128. vertex.x = vertices[ stride + 0 ];
  21129. vertex.y = vertices[ stride + 1 ];
  21130. vertex.z = vertices[ stride + 2 ];
  21131. }
  21132. function correctUVs() {
  21133. const a = new Vector3();
  21134. const b = new Vector3();
  21135. const c = new Vector3();
  21136. const centroid = new Vector3();
  21137. const uvA = new Vector2();
  21138. const uvB = new Vector2();
  21139. const uvC = new Vector2();
  21140. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  21141. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  21142. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  21143. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  21144. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  21145. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  21146. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  21147. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  21148. const azi = azimuth( centroid );
  21149. correctUV( uvA, j + 0, a, azi );
  21150. correctUV( uvB, j + 2, b, azi );
  21151. correctUV( uvC, j + 4, c, azi );
  21152. }
  21153. }
  21154. function correctUV( uv, stride, vector, azimuth ) {
  21155. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21156. uvBuffer[ stride ] = uv.x - 1;
  21157. }
  21158. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21159. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21160. }
  21161. }
  21162. // Angle around the Y axis, counter-clockwise when looking from above.
  21163. function azimuth( vector ) {
  21164. return Math.atan2( vector.z, - vector.x );
  21165. }
  21166. // Angle above the XZ plane.
  21167. function inclination( vector ) {
  21168. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21169. }
  21170. }
  21171. copy( source ) {
  21172. super.copy( source );
  21173. this.parameters = Object.assign( {}, source.parameters );
  21174. return this;
  21175. }
  21176. static fromJSON( data ) {
  21177. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  21178. }
  21179. }
  21180. class DodecahedronGeometry extends PolyhedronGeometry {
  21181. constructor( radius = 1, detail = 0 ) {
  21182. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21183. const r = 1 / t;
  21184. const vertices = [
  21185. // (±1, ±1, ±1)
  21186. - 1, - 1, - 1, - 1, - 1, 1,
  21187. - 1, 1, - 1, - 1, 1, 1,
  21188. 1, - 1, - 1, 1, - 1, 1,
  21189. 1, 1, - 1, 1, 1, 1,
  21190. // (0, ±1/φ, ±φ)
  21191. 0, - r, - t, 0, - r, t,
  21192. 0, r, - t, 0, r, t,
  21193. // (±1/φ, ±φ, 0)
  21194. - r, - t, 0, - r, t, 0,
  21195. r, - t, 0, r, t, 0,
  21196. // (±φ, 0, ±1/φ)
  21197. - t, 0, - r, t, 0, - r,
  21198. - t, 0, r, t, 0, r
  21199. ];
  21200. const indices = [
  21201. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21202. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  21203. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  21204. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  21205. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  21206. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  21207. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  21208. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  21209. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  21210. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  21211. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  21212. 1, 12, 14, 1, 14, 5, 1, 5, 9
  21213. ];
  21214. super( vertices, indices, radius, detail );
  21215. this.type = 'DodecahedronGeometry';
  21216. this.parameters = {
  21217. radius: radius,
  21218. detail: detail
  21219. };
  21220. }
  21221. static fromJSON( data ) {
  21222. return new DodecahedronGeometry( data.radius, data.detail );
  21223. }
  21224. }
  21225. const _v0 = /*@__PURE__*/ new Vector3();
  21226. const _v1$1 = /*@__PURE__*/ new Vector3();
  21227. const _normal = /*@__PURE__*/ new Vector3();
  21228. const _triangle = /*@__PURE__*/ new Triangle();
  21229. class EdgesGeometry extends BufferGeometry {
  21230. constructor( geometry = null, thresholdAngle = 1 ) {
  21231. super();
  21232. this.type = 'EdgesGeometry';
  21233. this.parameters = {
  21234. geometry: geometry,
  21235. thresholdAngle: thresholdAngle
  21236. };
  21237. if ( geometry !== null ) {
  21238. const precisionPoints = 4;
  21239. const precision = Math.pow( 10, precisionPoints );
  21240. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  21241. const indexAttr = geometry.getIndex();
  21242. const positionAttr = geometry.getAttribute( 'position' );
  21243. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  21244. const indexArr = [ 0, 0, 0 ];
  21245. const vertKeys = [ 'a', 'b', 'c' ];
  21246. const hashes = new Array( 3 );
  21247. const edgeData = {};
  21248. const vertices = [];
  21249. for ( let i = 0; i < indexCount; i += 3 ) {
  21250. if ( indexAttr ) {
  21251. indexArr[ 0 ] = indexAttr.getX( i );
  21252. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  21253. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  21254. } else {
  21255. indexArr[ 0 ] = i;
  21256. indexArr[ 1 ] = i + 1;
  21257. indexArr[ 2 ] = i + 2;
  21258. }
  21259. const { a, b, c } = _triangle;
  21260. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  21261. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  21262. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  21263. _triangle.getNormal( _normal );
  21264. // create hashes for the edge from the vertices
  21265. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  21266. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  21267. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  21268. // skip degenerate triangles
  21269. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  21270. continue;
  21271. }
  21272. // iterate over every edge
  21273. for ( let j = 0; j < 3; j ++ ) {
  21274. // get the first and next vertex making up the edge
  21275. const jNext = ( j + 1 ) % 3;
  21276. const vecHash0 = hashes[ j ];
  21277. const vecHash1 = hashes[ jNext ];
  21278. const v0 = _triangle[ vertKeys[ j ] ];
  21279. const v1 = _triangle[ vertKeys[ jNext ] ];
  21280. const hash = `${ vecHash0 }_${ vecHash1 }`;
  21281. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  21282. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  21283. // if we found a sibling edge add it into the vertex array if
  21284. // it meets the angle threshold and delete the edge from the map.
  21285. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  21286. vertices.push( v0.x, v0.y, v0.z );
  21287. vertices.push( v1.x, v1.y, v1.z );
  21288. }
  21289. edgeData[ reverseHash ] = null;
  21290. } else if ( ! ( hash in edgeData ) ) {
  21291. // if we've already got an edge here then skip adding a new one
  21292. edgeData[ hash ] = {
  21293. index0: indexArr[ j ],
  21294. index1: indexArr[ jNext ],
  21295. normal: _normal.clone(),
  21296. };
  21297. }
  21298. }
  21299. }
  21300. // iterate over all remaining, unmatched edges and add them to the vertex array
  21301. for ( const key in edgeData ) {
  21302. if ( edgeData[ key ] ) {
  21303. const { index0, index1 } = edgeData[ key ];
  21304. _v0.fromBufferAttribute( positionAttr, index0 );
  21305. _v1$1.fromBufferAttribute( positionAttr, index1 );
  21306. vertices.push( _v0.x, _v0.y, _v0.z );
  21307. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  21308. }
  21309. }
  21310. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21311. }
  21312. }
  21313. copy( source ) {
  21314. super.copy( source );
  21315. this.parameters = Object.assign( {}, source.parameters );
  21316. return this;
  21317. }
  21318. }
  21319. class Shape extends Path {
  21320. constructor( points ) {
  21321. super( points );
  21322. this.uuid = generateUUID();
  21323. this.type = 'Shape';
  21324. this.holes = [];
  21325. }
  21326. getPointsHoles( divisions ) {
  21327. const holesPts = [];
  21328. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  21329. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21330. }
  21331. return holesPts;
  21332. }
  21333. // get points of shape and holes (keypoints based on segments parameter)
  21334. extractPoints( divisions ) {
  21335. return {
  21336. shape: this.getPoints( divisions ),
  21337. holes: this.getPointsHoles( divisions )
  21338. };
  21339. }
  21340. copy( source ) {
  21341. super.copy( source );
  21342. this.holes = [];
  21343. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  21344. const hole = source.holes[ i ];
  21345. this.holes.push( hole.clone() );
  21346. }
  21347. return this;
  21348. }
  21349. toJSON() {
  21350. const data = super.toJSON();
  21351. data.uuid = this.uuid;
  21352. data.holes = [];
  21353. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  21354. const hole = this.holes[ i ];
  21355. data.holes.push( hole.toJSON() );
  21356. }
  21357. return data;
  21358. }
  21359. fromJSON( json ) {
  21360. super.fromJSON( json );
  21361. this.uuid = json.uuid;
  21362. this.holes = [];
  21363. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  21364. const hole = json.holes[ i ];
  21365. this.holes.push( new Path().fromJSON( hole ) );
  21366. }
  21367. return this;
  21368. }
  21369. }
  21370. /**
  21371. * Port from https://github.com/mapbox/earcut (v2.2.4)
  21372. */
  21373. const Earcut = {
  21374. triangulate: function ( data, holeIndices, dim = 2 ) {
  21375. const hasHoles = holeIndices && holeIndices.length;
  21376. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  21377. let outerNode = linkedList( data, 0, outerLen, dim, true );
  21378. const triangles = [];
  21379. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  21380. let minX, minY, maxX, maxY, x, y, invSize;
  21381. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  21382. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  21383. if ( data.length > 80 * dim ) {
  21384. minX = maxX = data[ 0 ];
  21385. minY = maxY = data[ 1 ];
  21386. for ( let i = dim; i < outerLen; i += dim ) {
  21387. x = data[ i ];
  21388. y = data[ i + 1 ];
  21389. if ( x < minX ) minX = x;
  21390. if ( y < minY ) minY = y;
  21391. if ( x > maxX ) maxX = x;
  21392. if ( y > maxY ) maxY = y;
  21393. }
  21394. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  21395. invSize = Math.max( maxX - minX, maxY - minY );
  21396. invSize = invSize !== 0 ? 32767 / invSize : 0;
  21397. }
  21398. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  21399. return triangles;
  21400. }
  21401. };
  21402. // create a circular doubly linked list from polygon points in the specified winding order
  21403. function linkedList( data, start, end, dim, clockwise ) {
  21404. let i, last;
  21405. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  21406. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21407. } else {
  21408. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21409. }
  21410. if ( last && equals( last, last.next ) ) {
  21411. removeNode( last );
  21412. last = last.next;
  21413. }
  21414. return last;
  21415. }
  21416. // eliminate colinear or duplicate points
  21417. function filterPoints( start, end ) {
  21418. if ( ! start ) return start;
  21419. if ( ! end ) end = start;
  21420. let p = start,
  21421. again;
  21422. do {
  21423. again = false;
  21424. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  21425. removeNode( p );
  21426. p = end = p.prev;
  21427. if ( p === p.next ) break;
  21428. again = true;
  21429. } else {
  21430. p = p.next;
  21431. }
  21432. } while ( again || p !== end );
  21433. return end;
  21434. }
  21435. // main ear slicing loop which triangulates a polygon (given as a linked list)
  21436. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  21437. if ( ! ear ) return;
  21438. // interlink polygon nodes in z-order
  21439. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  21440. let stop = ear,
  21441. prev, next;
  21442. // iterate through ears, slicing them one by one
  21443. while ( ear.prev !== ear.next ) {
  21444. prev = ear.prev;
  21445. next = ear.next;
  21446. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  21447. // cut off the triangle
  21448. triangles.push( prev.i / dim | 0 );
  21449. triangles.push( ear.i / dim | 0 );
  21450. triangles.push( next.i / dim | 0 );
  21451. removeNode( ear );
  21452. // skipping the next vertex leads to less sliver triangles
  21453. ear = next.next;
  21454. stop = next.next;
  21455. continue;
  21456. }
  21457. ear = next;
  21458. // if we looped through the whole remaining polygon and can't find any more ears
  21459. if ( ear === stop ) {
  21460. // try filtering points and slicing again
  21461. if ( ! pass ) {
  21462. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  21463. // if this didn't work, try curing all small self-intersections locally
  21464. } else if ( pass === 1 ) {
  21465. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  21466. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  21467. // as a last resort, try splitting the remaining polygon into two
  21468. } else if ( pass === 2 ) {
  21469. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  21470. }
  21471. break;
  21472. }
  21473. }
  21474. }
  21475. // check whether a polygon node forms a valid ear with adjacent nodes
  21476. function isEar( ear ) {
  21477. const a = ear.prev,
  21478. b = ear,
  21479. c = ear.next;
  21480. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21481. // now make sure we don't have other points inside the potential ear
  21482. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21483. // triangle bbox; min & max are calculated like this for speed
  21484. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21485. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21486. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21487. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21488. let p = c.next;
  21489. while ( p !== a ) {
  21490. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  21491. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  21492. area( p.prev, p, p.next ) >= 0 ) return false;
  21493. p = p.next;
  21494. }
  21495. return true;
  21496. }
  21497. function isEarHashed( ear, minX, minY, invSize ) {
  21498. const a = ear.prev,
  21499. b = ear,
  21500. c = ear.next;
  21501. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21502. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21503. // triangle bbox; min & max are calculated like this for speed
  21504. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21505. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21506. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21507. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21508. // z-order range for the current triangle bbox;
  21509. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  21510. maxZ = zOrder( x1, y1, minX, minY, invSize );
  21511. let p = ear.prevZ,
  21512. n = ear.nextZ;
  21513. // look for points inside the triangle in both directions
  21514. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  21515. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21516. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21517. p = p.prevZ;
  21518. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21519. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21520. n = n.nextZ;
  21521. }
  21522. // look for remaining points in decreasing z-order
  21523. while ( p && p.z >= minZ ) {
  21524. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21525. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21526. p = p.prevZ;
  21527. }
  21528. // look for remaining points in increasing z-order
  21529. while ( n && n.z <= maxZ ) {
  21530. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21531. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21532. n = n.nextZ;
  21533. }
  21534. return true;
  21535. }
  21536. // go through all polygon nodes and cure small local self-intersections
  21537. function cureLocalIntersections( start, triangles, dim ) {
  21538. let p = start;
  21539. do {
  21540. const a = p.prev,
  21541. b = p.next.next;
  21542. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21543. triangles.push( a.i / dim | 0 );
  21544. triangles.push( p.i / dim | 0 );
  21545. triangles.push( b.i / dim | 0 );
  21546. // remove two nodes involved
  21547. removeNode( p );
  21548. removeNode( p.next );
  21549. p = start = b;
  21550. }
  21551. p = p.next;
  21552. } while ( p !== start );
  21553. return filterPoints( p );
  21554. }
  21555. // try splitting polygon into two and triangulate them independently
  21556. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21557. // look for a valid diagonal that divides the polygon into two
  21558. let a = start;
  21559. do {
  21560. let b = a.next.next;
  21561. while ( b !== a.prev ) {
  21562. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21563. // split the polygon in two by the diagonal
  21564. let c = splitPolygon( a, b );
  21565. // filter colinear points around the cuts
  21566. a = filterPoints( a, a.next );
  21567. c = filterPoints( c, c.next );
  21568. // run earcut on each half
  21569. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  21570. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  21571. return;
  21572. }
  21573. b = b.next;
  21574. }
  21575. a = a.next;
  21576. } while ( a !== start );
  21577. }
  21578. // link every hole into the outer loop, producing a single-ring polygon without holes
  21579. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21580. const queue = [];
  21581. let i, len, start, end, list;
  21582. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21583. start = holeIndices[ i ] * dim;
  21584. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21585. list = linkedList( data, start, end, dim, false );
  21586. if ( list === list.next ) list.steiner = true;
  21587. queue.push( getLeftmost( list ) );
  21588. }
  21589. queue.sort( compareX );
  21590. // process holes from left to right
  21591. for ( i = 0; i < queue.length; i ++ ) {
  21592. outerNode = eliminateHole( queue[ i ], outerNode );
  21593. }
  21594. return outerNode;
  21595. }
  21596. function compareX( a, b ) {
  21597. return a.x - b.x;
  21598. }
  21599. // find a bridge between vertices that connects hole with an outer ring and link it
  21600. function eliminateHole( hole, outerNode ) {
  21601. const bridge = findHoleBridge( hole, outerNode );
  21602. if ( ! bridge ) {
  21603. return outerNode;
  21604. }
  21605. const bridgeReverse = splitPolygon( bridge, hole );
  21606. // filter collinear points around the cuts
  21607. filterPoints( bridgeReverse, bridgeReverse.next );
  21608. return filterPoints( bridge, bridge.next );
  21609. }
  21610. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21611. function findHoleBridge( hole, outerNode ) {
  21612. let p = outerNode,
  21613. qx = - Infinity,
  21614. m;
  21615. const hx = hole.x, hy = hole.y;
  21616. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21617. // segment's endpoint with lesser x will be potential connection point
  21618. do {
  21619. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21620. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21621. if ( x <= hx && x > qx ) {
  21622. qx = x;
  21623. m = p.x < p.next.x ? p : p.next;
  21624. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21625. }
  21626. }
  21627. p = p.next;
  21628. } while ( p !== outerNode );
  21629. if ( ! m ) return null;
  21630. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21631. // if there are no points found, we have a valid connection;
  21632. // otherwise choose the point of the minimum angle with the ray as connection point
  21633. const stop = m,
  21634. mx = m.x,
  21635. my = m.y;
  21636. let tanMin = Infinity, tan;
  21637. p = m;
  21638. do {
  21639. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21640. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21641. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21642. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21643. m = p;
  21644. tanMin = tan;
  21645. }
  21646. }
  21647. p = p.next;
  21648. } while ( p !== stop );
  21649. return m;
  21650. }
  21651. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21652. function sectorContainsSector( m, p ) {
  21653. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21654. }
  21655. // interlink polygon nodes in z-order
  21656. function indexCurve( start, minX, minY, invSize ) {
  21657. let p = start;
  21658. do {
  21659. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21660. p.prevZ = p.prev;
  21661. p.nextZ = p.next;
  21662. p = p.next;
  21663. } while ( p !== start );
  21664. p.prevZ.nextZ = null;
  21665. p.prevZ = null;
  21666. sortLinked( p );
  21667. }
  21668. // Simon Tatham's linked list merge sort algorithm
  21669. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21670. function sortLinked( list ) {
  21671. let i, p, q, e, tail, numMerges, pSize, qSize,
  21672. inSize = 1;
  21673. do {
  21674. p = list;
  21675. list = null;
  21676. tail = null;
  21677. numMerges = 0;
  21678. while ( p ) {
  21679. numMerges ++;
  21680. q = p;
  21681. pSize = 0;
  21682. for ( i = 0; i < inSize; i ++ ) {
  21683. pSize ++;
  21684. q = q.nextZ;
  21685. if ( ! q ) break;
  21686. }
  21687. qSize = inSize;
  21688. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21689. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21690. e = p;
  21691. p = p.nextZ;
  21692. pSize --;
  21693. } else {
  21694. e = q;
  21695. q = q.nextZ;
  21696. qSize --;
  21697. }
  21698. if ( tail ) tail.nextZ = e;
  21699. else list = e;
  21700. e.prevZ = tail;
  21701. tail = e;
  21702. }
  21703. p = q;
  21704. }
  21705. tail.nextZ = null;
  21706. inSize *= 2;
  21707. } while ( numMerges > 1 );
  21708. return list;
  21709. }
  21710. // z-order of a point given coords and inverse of the longer side of data bbox
  21711. function zOrder( x, y, minX, minY, invSize ) {
  21712. // coords are transformed into non-negative 15-bit integer range
  21713. x = ( x - minX ) * invSize | 0;
  21714. y = ( y - minY ) * invSize | 0;
  21715. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21716. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21717. x = ( x | ( x << 2 ) ) & 0x33333333;
  21718. x = ( x | ( x << 1 ) ) & 0x55555555;
  21719. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21720. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21721. y = ( y | ( y << 2 ) ) & 0x33333333;
  21722. y = ( y | ( y << 1 ) ) & 0x55555555;
  21723. return x | ( y << 1 );
  21724. }
  21725. // find the leftmost node of a polygon ring
  21726. function getLeftmost( start ) {
  21727. let p = start,
  21728. leftmost = start;
  21729. do {
  21730. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21731. p = p.next;
  21732. } while ( p !== start );
  21733. return leftmost;
  21734. }
  21735. // check if a point lies within a convex triangle
  21736. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21737. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21738. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21739. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21740. }
  21741. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21742. function isValidDiagonal( a, b ) {
  21743. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21744. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21745. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21746. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21747. }
  21748. // signed area of a triangle
  21749. function area( p, q, r ) {
  21750. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21751. }
  21752. // check if two points are equal
  21753. function equals( p1, p2 ) {
  21754. return p1.x === p2.x && p1.y === p2.y;
  21755. }
  21756. // check if two segments intersect
  21757. function intersects( p1, q1, p2, q2 ) {
  21758. const o1 = sign( area( p1, q1, p2 ) );
  21759. const o2 = sign( area( p1, q1, q2 ) );
  21760. const o3 = sign( area( p2, q2, p1 ) );
  21761. const o4 = sign( area( p2, q2, q1 ) );
  21762. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21763. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21764. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21765. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21766. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21767. return false;
  21768. }
  21769. // for collinear points p, q, r, check if point q lies on segment pr
  21770. function onSegment( p, q, r ) {
  21771. 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 );
  21772. }
  21773. function sign( num ) {
  21774. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21775. }
  21776. // check if a polygon diagonal intersects any polygon segments
  21777. function intersectsPolygon( a, b ) {
  21778. let p = a;
  21779. do {
  21780. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21781. intersects( p, p.next, a, b ) ) return true;
  21782. p = p.next;
  21783. } while ( p !== a );
  21784. return false;
  21785. }
  21786. // check if a polygon diagonal is locally inside the polygon
  21787. function locallyInside( a, b ) {
  21788. return area( a.prev, a, a.next ) < 0 ?
  21789. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21790. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21791. }
  21792. // check if the middle point of a polygon diagonal is inside the polygon
  21793. function middleInside( a, b ) {
  21794. let p = a,
  21795. inside = false;
  21796. const px = ( a.x + b.x ) / 2,
  21797. py = ( a.y + b.y ) / 2;
  21798. do {
  21799. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21800. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21801. inside = ! inside;
  21802. p = p.next;
  21803. } while ( p !== a );
  21804. return inside;
  21805. }
  21806. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21807. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21808. function splitPolygon( a, b ) {
  21809. const a2 = new Node( a.i, a.x, a.y ),
  21810. b2 = new Node( b.i, b.x, b.y ),
  21811. an = a.next,
  21812. bp = b.prev;
  21813. a.next = b;
  21814. b.prev = a;
  21815. a2.next = an;
  21816. an.prev = a2;
  21817. b2.next = a2;
  21818. a2.prev = b2;
  21819. bp.next = b2;
  21820. b2.prev = bp;
  21821. return b2;
  21822. }
  21823. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21824. function insertNode( i, x, y, last ) {
  21825. const p = new Node( i, x, y );
  21826. if ( ! last ) {
  21827. p.prev = p;
  21828. p.next = p;
  21829. } else {
  21830. p.next = last.next;
  21831. p.prev = last;
  21832. last.next.prev = p;
  21833. last.next = p;
  21834. }
  21835. return p;
  21836. }
  21837. function removeNode( p ) {
  21838. p.next.prev = p.prev;
  21839. p.prev.next = p.next;
  21840. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21841. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21842. }
  21843. function Node( i, x, y ) {
  21844. // vertex index in coordinates array
  21845. this.i = i;
  21846. // vertex coordinates
  21847. this.x = x;
  21848. this.y = y;
  21849. // previous and next vertex nodes in a polygon ring
  21850. this.prev = null;
  21851. this.next = null;
  21852. // z-order curve value
  21853. this.z = 0;
  21854. // previous and next nodes in z-order
  21855. this.prevZ = null;
  21856. this.nextZ = null;
  21857. // indicates whether this is a steiner point
  21858. this.steiner = false;
  21859. }
  21860. function signedArea( data, start, end, dim ) {
  21861. let sum = 0;
  21862. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21863. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21864. j = i;
  21865. }
  21866. return sum;
  21867. }
  21868. class ShapeUtils {
  21869. // calculate area of the contour polygon
  21870. static area( contour ) {
  21871. const n = contour.length;
  21872. let a = 0.0;
  21873. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21874. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21875. }
  21876. return a * 0.5;
  21877. }
  21878. static isClockWise( pts ) {
  21879. return ShapeUtils.area( pts ) < 0;
  21880. }
  21881. static triangulateShape( contour, holes ) {
  21882. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21883. const holeIndices = []; // array of hole indices
  21884. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21885. removeDupEndPts( contour );
  21886. addContour( vertices, contour );
  21887. //
  21888. let holeIndex = contour.length;
  21889. holes.forEach( removeDupEndPts );
  21890. for ( let i = 0; i < holes.length; i ++ ) {
  21891. holeIndices.push( holeIndex );
  21892. holeIndex += holes[ i ].length;
  21893. addContour( vertices, holes[ i ] );
  21894. }
  21895. //
  21896. const triangles = Earcut.triangulate( vertices, holeIndices );
  21897. //
  21898. for ( let i = 0; i < triangles.length; i += 3 ) {
  21899. faces.push( triangles.slice( i, i + 3 ) );
  21900. }
  21901. return faces;
  21902. }
  21903. }
  21904. function removeDupEndPts( points ) {
  21905. const l = points.length;
  21906. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21907. points.pop();
  21908. }
  21909. }
  21910. function addContour( vertices, contour ) {
  21911. for ( let i = 0; i < contour.length; i ++ ) {
  21912. vertices.push( contour[ i ].x );
  21913. vertices.push( contour[ i ].y );
  21914. }
  21915. }
  21916. /**
  21917. * Creates extruded geometry from a path shape.
  21918. *
  21919. * parameters = {
  21920. *
  21921. * curveSegments: <int>, // number of points on the curves
  21922. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21923. * depth: <float>, // Depth to extrude the shape
  21924. *
  21925. * bevelEnabled: <bool>, // turn on bevel
  21926. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21927. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21928. * bevelOffset: <float>, // how far from shape outline does bevel start
  21929. * bevelSegments: <int>, // number of bevel layers
  21930. *
  21931. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21932. *
  21933. * UVGenerator: <Object> // object that provides UV generator functions
  21934. *
  21935. * }
  21936. */
  21937. class ExtrudeGeometry extends BufferGeometry {
  21938. 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 = {} ) {
  21939. super();
  21940. this.type = 'ExtrudeGeometry';
  21941. this.parameters = {
  21942. shapes: shapes,
  21943. options: options
  21944. };
  21945. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21946. const scope = this;
  21947. const verticesArray = [];
  21948. const uvArray = [];
  21949. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21950. const shape = shapes[ i ];
  21951. addShape( shape );
  21952. }
  21953. // build geometry
  21954. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21955. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21956. this.computeVertexNormals();
  21957. // functions
  21958. function addShape( shape ) {
  21959. const placeholder = [];
  21960. // options
  21961. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21962. const steps = options.steps !== undefined ? options.steps : 1;
  21963. const depth = options.depth !== undefined ? options.depth : 1;
  21964. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21965. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21966. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21967. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21968. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21969. const extrudePath = options.extrudePath;
  21970. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21971. //
  21972. let extrudePts, extrudeByPath = false;
  21973. let splineTube, binormal, normal, position2;
  21974. if ( extrudePath ) {
  21975. extrudePts = extrudePath.getSpacedPoints( steps );
  21976. extrudeByPath = true;
  21977. bevelEnabled = false; // bevels not supported for path extrusion
  21978. // SETUP TNB variables
  21979. // TODO1 - have a .isClosed in spline?
  21980. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21981. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21982. binormal = new Vector3();
  21983. normal = new Vector3();
  21984. position2 = new Vector3();
  21985. }
  21986. // Safeguards if bevels are not enabled
  21987. if ( ! bevelEnabled ) {
  21988. bevelSegments = 0;
  21989. bevelThickness = 0;
  21990. bevelSize = 0;
  21991. bevelOffset = 0;
  21992. }
  21993. // Variables initialization
  21994. const shapePoints = shape.extractPoints( curveSegments );
  21995. let vertices = shapePoints.shape;
  21996. const holes = shapePoints.holes;
  21997. const reverse = ! ShapeUtils.isClockWise( vertices );
  21998. if ( reverse ) {
  21999. vertices = vertices.reverse();
  22000. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  22001. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22002. const ahole = holes[ h ];
  22003. if ( ShapeUtils.isClockWise( ahole ) ) {
  22004. holes[ h ] = ahole.reverse();
  22005. }
  22006. }
  22007. }
  22008. const faces = ShapeUtils.triangulateShape( vertices, holes );
  22009. /* Vertices */
  22010. const contour = vertices; // vertices has all points but contour has only points of circumference
  22011. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22012. const ahole = holes[ h ];
  22013. vertices = vertices.concat( ahole );
  22014. }
  22015. function scalePt2( pt, vec, size ) {
  22016. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  22017. return pt.clone().addScaledVector( vec, size );
  22018. }
  22019. const vlen = vertices.length, flen = faces.length;
  22020. // Find directions for point movement
  22021. function getBevelVec( inPt, inPrev, inNext ) {
  22022. // computes for inPt the corresponding point inPt' on a new contour
  22023. // shifted by 1 unit (length of normalized vector) to the left
  22024. // if we walk along contour clockwise, this new contour is outside the old one
  22025. //
  22026. // inPt' is the intersection of the two lines parallel to the two
  22027. // adjacent edges of inPt at a distance of 1 unit on the left side.
  22028. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  22029. // good reading for geometry algorithms (here: line-line intersection)
  22030. // http://geomalgorithms.com/a05-_intersect-1.html
  22031. const v_prev_x = inPt.x - inPrev.x,
  22032. v_prev_y = inPt.y - inPrev.y;
  22033. const v_next_x = inNext.x - inPt.x,
  22034. v_next_y = inNext.y - inPt.y;
  22035. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  22036. // check for collinear edges
  22037. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22038. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  22039. // not collinear
  22040. // length of vectors for normalizing
  22041. const v_prev_len = Math.sqrt( v_prev_lensq );
  22042. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  22043. // shift adjacent points by unit vectors to the left
  22044. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  22045. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  22046. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  22047. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  22048. // scaling factor for v_prev to intersection point
  22049. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  22050. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  22051. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22052. // vector from inPt to intersection point
  22053. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  22054. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  22055. // Don't normalize!, otherwise sharp corners become ugly
  22056. // but prevent crazy spikes
  22057. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  22058. if ( v_trans_lensq <= 2 ) {
  22059. return new Vector2( v_trans_x, v_trans_y );
  22060. } else {
  22061. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  22062. }
  22063. } else {
  22064. // handle special case of collinear edges
  22065. let direction_eq = false; // assumes: opposite
  22066. if ( v_prev_x > Number.EPSILON ) {
  22067. if ( v_next_x > Number.EPSILON ) {
  22068. direction_eq = true;
  22069. }
  22070. } else {
  22071. if ( v_prev_x < - Number.EPSILON ) {
  22072. if ( v_next_x < - Number.EPSILON ) {
  22073. direction_eq = true;
  22074. }
  22075. } else {
  22076. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  22077. direction_eq = true;
  22078. }
  22079. }
  22080. }
  22081. if ( direction_eq ) {
  22082. // console.log("Warning: lines are a straight sequence");
  22083. v_trans_x = - v_prev_y;
  22084. v_trans_y = v_prev_x;
  22085. shrink_by = Math.sqrt( v_prev_lensq );
  22086. } else {
  22087. // console.log("Warning: lines are a straight spike");
  22088. v_trans_x = v_prev_x;
  22089. v_trans_y = v_prev_y;
  22090. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  22091. }
  22092. }
  22093. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  22094. }
  22095. const contourMovements = [];
  22096. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22097. if ( j === il ) j = 0;
  22098. if ( k === il ) k = 0;
  22099. // (j)---(i)---(k)
  22100. // console.log('i,j,k', i, j , k)
  22101. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  22102. }
  22103. const holesMovements = [];
  22104. let oneHoleMovements, verticesMovements = contourMovements.concat();
  22105. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22106. const ahole = holes[ h ];
  22107. oneHoleMovements = [];
  22108. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22109. if ( j === il ) j = 0;
  22110. if ( k === il ) k = 0;
  22111. // (j)---(i)---(k)
  22112. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  22113. }
  22114. holesMovements.push( oneHoleMovements );
  22115. verticesMovements = verticesMovements.concat( oneHoleMovements );
  22116. }
  22117. // Loop bevelSegments, 1 for the front, 1 for the back
  22118. for ( let b = 0; b < bevelSegments; b ++ ) {
  22119. //for ( b = bevelSegments; b > 0; b -- ) {
  22120. const t = b / bevelSegments;
  22121. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22122. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22123. // contract shape
  22124. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22125. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22126. v( vert.x, vert.y, - z );
  22127. }
  22128. // expand holes
  22129. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22130. const ahole = holes[ h ];
  22131. oneHoleMovements = holesMovements[ h ];
  22132. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22133. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22134. v( vert.x, vert.y, - z );
  22135. }
  22136. }
  22137. }
  22138. const bs = bevelSize + bevelOffset;
  22139. // Back facing vertices
  22140. for ( let i = 0; i < vlen; i ++ ) {
  22141. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22142. if ( ! extrudeByPath ) {
  22143. v( vert.x, vert.y, 0 );
  22144. } else {
  22145. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22146. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22147. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22148. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22149. v( position2.x, position2.y, position2.z );
  22150. }
  22151. }
  22152. // Add stepped vertices...
  22153. // Including front facing vertices
  22154. for ( let s = 1; s <= steps; s ++ ) {
  22155. for ( let i = 0; i < vlen; i ++ ) {
  22156. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22157. if ( ! extrudeByPath ) {
  22158. v( vert.x, vert.y, depth / steps * s );
  22159. } else {
  22160. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22161. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22162. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22163. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22164. v( position2.x, position2.y, position2.z );
  22165. }
  22166. }
  22167. }
  22168. // Add bevel segments planes
  22169. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22170. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  22171. const t = b / bevelSegments;
  22172. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22173. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22174. // contract shape
  22175. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22176. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22177. v( vert.x, vert.y, depth + z );
  22178. }
  22179. // expand holes
  22180. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22181. const ahole = holes[ h ];
  22182. oneHoleMovements = holesMovements[ h ];
  22183. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22184. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22185. if ( ! extrudeByPath ) {
  22186. v( vert.x, vert.y, depth + z );
  22187. } else {
  22188. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22189. }
  22190. }
  22191. }
  22192. }
  22193. /* Faces */
  22194. // Top and bottom faces
  22195. buildLidFaces();
  22196. // Sides faces
  22197. buildSideFaces();
  22198. ///// Internal functions
  22199. function buildLidFaces() {
  22200. const start = verticesArray.length / 3;
  22201. if ( bevelEnabled ) {
  22202. let layer = 0; // steps + 1
  22203. let offset = vlen * layer;
  22204. // Bottom faces
  22205. for ( let i = 0; i < flen; i ++ ) {
  22206. const face = faces[ i ];
  22207. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22208. }
  22209. layer = steps + bevelSegments * 2;
  22210. offset = vlen * layer;
  22211. // Top faces
  22212. for ( let i = 0; i < flen; i ++ ) {
  22213. const face = faces[ i ];
  22214. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  22215. }
  22216. } else {
  22217. // Bottom faces
  22218. for ( let i = 0; i < flen; i ++ ) {
  22219. const face = faces[ i ];
  22220. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  22221. }
  22222. // Top faces
  22223. for ( let i = 0; i < flen; i ++ ) {
  22224. const face = faces[ i ];
  22225. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  22226. }
  22227. }
  22228. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  22229. }
  22230. // Create faces for the z-sides of the shape
  22231. function buildSideFaces() {
  22232. const start = verticesArray.length / 3;
  22233. let layeroffset = 0;
  22234. sidewalls( contour, layeroffset );
  22235. layeroffset += contour.length;
  22236. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22237. const ahole = holes[ h ];
  22238. sidewalls( ahole, layeroffset );
  22239. //, true
  22240. layeroffset += ahole.length;
  22241. }
  22242. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  22243. }
  22244. function sidewalls( contour, layeroffset ) {
  22245. let i = contour.length;
  22246. while ( -- i >= 0 ) {
  22247. const j = i;
  22248. let k = i - 1;
  22249. if ( k < 0 ) k = contour.length - 1;
  22250. //console.log('b', i,j, i-1, k,vertices.length);
  22251. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  22252. const slen1 = vlen * s;
  22253. const slen2 = vlen * ( s + 1 );
  22254. const a = layeroffset + j + slen1,
  22255. b = layeroffset + k + slen1,
  22256. c = layeroffset + k + slen2,
  22257. d = layeroffset + j + slen2;
  22258. f4( a, b, c, d );
  22259. }
  22260. }
  22261. }
  22262. function v( x, y, z ) {
  22263. placeholder.push( x );
  22264. placeholder.push( y );
  22265. placeholder.push( z );
  22266. }
  22267. function f3( a, b, c ) {
  22268. addVertex( a );
  22269. addVertex( b );
  22270. addVertex( c );
  22271. const nextIndex = verticesArray.length / 3;
  22272. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22273. addUV( uvs[ 0 ] );
  22274. addUV( uvs[ 1 ] );
  22275. addUV( uvs[ 2 ] );
  22276. }
  22277. function f4( a, b, c, d ) {
  22278. addVertex( a );
  22279. addVertex( b );
  22280. addVertex( d );
  22281. addVertex( b );
  22282. addVertex( c );
  22283. addVertex( d );
  22284. const nextIndex = verticesArray.length / 3;
  22285. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22286. addUV( uvs[ 0 ] );
  22287. addUV( uvs[ 1 ] );
  22288. addUV( uvs[ 3 ] );
  22289. addUV( uvs[ 1 ] );
  22290. addUV( uvs[ 2 ] );
  22291. addUV( uvs[ 3 ] );
  22292. }
  22293. function addVertex( index ) {
  22294. verticesArray.push( placeholder[ index * 3 + 0 ] );
  22295. verticesArray.push( placeholder[ index * 3 + 1 ] );
  22296. verticesArray.push( placeholder[ index * 3 + 2 ] );
  22297. }
  22298. function addUV( vector2 ) {
  22299. uvArray.push( vector2.x );
  22300. uvArray.push( vector2.y );
  22301. }
  22302. }
  22303. }
  22304. copy( source ) {
  22305. super.copy( source );
  22306. this.parameters = Object.assign( {}, source.parameters );
  22307. return this;
  22308. }
  22309. toJSON() {
  22310. const data = super.toJSON();
  22311. const shapes = this.parameters.shapes;
  22312. const options = this.parameters.options;
  22313. return toJSON$1( shapes, options, data );
  22314. }
  22315. static fromJSON( data, shapes ) {
  22316. const geometryShapes = [];
  22317. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22318. const shape = shapes[ data.shapes[ j ] ];
  22319. geometryShapes.push( shape );
  22320. }
  22321. const extrudePath = data.options.extrudePath;
  22322. if ( extrudePath !== undefined ) {
  22323. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  22324. }
  22325. return new ExtrudeGeometry( geometryShapes, data.options );
  22326. }
  22327. }
  22328. const WorldUVGenerator = {
  22329. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  22330. const a_x = vertices[ indexA * 3 ];
  22331. const a_y = vertices[ indexA * 3 + 1 ];
  22332. const b_x = vertices[ indexB * 3 ];
  22333. const b_y = vertices[ indexB * 3 + 1 ];
  22334. const c_x = vertices[ indexC * 3 ];
  22335. const c_y = vertices[ indexC * 3 + 1 ];
  22336. return [
  22337. new Vector2( a_x, a_y ),
  22338. new Vector2( b_x, b_y ),
  22339. new Vector2( c_x, c_y )
  22340. ];
  22341. },
  22342. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  22343. const a_x = vertices[ indexA * 3 ];
  22344. const a_y = vertices[ indexA * 3 + 1 ];
  22345. const a_z = vertices[ indexA * 3 + 2 ];
  22346. const b_x = vertices[ indexB * 3 ];
  22347. const b_y = vertices[ indexB * 3 + 1 ];
  22348. const b_z = vertices[ indexB * 3 + 2 ];
  22349. const c_x = vertices[ indexC * 3 ];
  22350. const c_y = vertices[ indexC * 3 + 1 ];
  22351. const c_z = vertices[ indexC * 3 + 2 ];
  22352. const d_x = vertices[ indexD * 3 ];
  22353. const d_y = vertices[ indexD * 3 + 1 ];
  22354. const d_z = vertices[ indexD * 3 + 2 ];
  22355. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  22356. return [
  22357. new Vector2( a_x, 1 - a_z ),
  22358. new Vector2( b_x, 1 - b_z ),
  22359. new Vector2( c_x, 1 - c_z ),
  22360. new Vector2( d_x, 1 - d_z )
  22361. ];
  22362. } else {
  22363. return [
  22364. new Vector2( a_y, 1 - a_z ),
  22365. new Vector2( b_y, 1 - b_z ),
  22366. new Vector2( c_y, 1 - c_z ),
  22367. new Vector2( d_y, 1 - d_z )
  22368. ];
  22369. }
  22370. }
  22371. };
  22372. function toJSON$1( shapes, options, data ) {
  22373. data.shapes = [];
  22374. if ( Array.isArray( shapes ) ) {
  22375. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22376. const shape = shapes[ i ];
  22377. data.shapes.push( shape.uuid );
  22378. }
  22379. } else {
  22380. data.shapes.push( shapes.uuid );
  22381. }
  22382. data.options = Object.assign( {}, options );
  22383. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  22384. return data;
  22385. }
  22386. class IcosahedronGeometry extends PolyhedronGeometry {
  22387. constructor( radius = 1, detail = 0 ) {
  22388. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22389. const vertices = [
  22390. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22391. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22392. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22393. ];
  22394. const indices = [
  22395. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22396. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22397. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22398. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22399. ];
  22400. super( vertices, indices, radius, detail );
  22401. this.type = 'IcosahedronGeometry';
  22402. this.parameters = {
  22403. radius: radius,
  22404. detail: detail
  22405. };
  22406. }
  22407. static fromJSON( data ) {
  22408. return new IcosahedronGeometry( data.radius, data.detail );
  22409. }
  22410. }
  22411. class OctahedronGeometry extends PolyhedronGeometry {
  22412. constructor( radius = 1, detail = 0 ) {
  22413. const vertices = [
  22414. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  22415. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22416. ];
  22417. const indices = [
  22418. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  22419. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  22420. 1, 3, 4, 1, 4, 2
  22421. ];
  22422. super( vertices, indices, radius, detail );
  22423. this.type = 'OctahedronGeometry';
  22424. this.parameters = {
  22425. radius: radius,
  22426. detail: detail
  22427. };
  22428. }
  22429. static fromJSON( data ) {
  22430. return new OctahedronGeometry( data.radius, data.detail );
  22431. }
  22432. }
  22433. class RingGeometry extends BufferGeometry {
  22434. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22435. super();
  22436. this.type = 'RingGeometry';
  22437. this.parameters = {
  22438. innerRadius: innerRadius,
  22439. outerRadius: outerRadius,
  22440. thetaSegments: thetaSegments,
  22441. phiSegments: phiSegments,
  22442. thetaStart: thetaStart,
  22443. thetaLength: thetaLength
  22444. };
  22445. thetaSegments = Math.max( 3, thetaSegments );
  22446. phiSegments = Math.max( 1, phiSegments );
  22447. // buffers
  22448. const indices = [];
  22449. const vertices = [];
  22450. const normals = [];
  22451. const uvs = [];
  22452. // some helper variables
  22453. let radius = innerRadius;
  22454. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22455. const vertex = new Vector3();
  22456. const uv = new Vector2();
  22457. // generate vertices, normals and uvs
  22458. for ( let j = 0; j <= phiSegments; j ++ ) {
  22459. for ( let i = 0; i <= thetaSegments; i ++ ) {
  22460. // values are generate from the inside of the ring to the outside
  22461. const segment = thetaStart + i / thetaSegments * thetaLength;
  22462. // vertex
  22463. vertex.x = radius * Math.cos( segment );
  22464. vertex.y = radius * Math.sin( segment );
  22465. vertices.push( vertex.x, vertex.y, vertex.z );
  22466. // normal
  22467. normals.push( 0, 0, 1 );
  22468. // uv
  22469. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22470. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22471. uvs.push( uv.x, uv.y );
  22472. }
  22473. // increase the radius for next row of vertices
  22474. radius += radiusStep;
  22475. }
  22476. // indices
  22477. for ( let j = 0; j < phiSegments; j ++ ) {
  22478. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  22479. for ( let i = 0; i < thetaSegments; i ++ ) {
  22480. const segment = i + thetaSegmentLevel;
  22481. const a = segment;
  22482. const b = segment + thetaSegments + 1;
  22483. const c = segment + thetaSegments + 2;
  22484. const d = segment + 1;
  22485. // faces
  22486. indices.push( a, b, d );
  22487. indices.push( b, c, d );
  22488. }
  22489. }
  22490. // build geometry
  22491. this.setIndex( indices );
  22492. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22493. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22494. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22495. }
  22496. copy( source ) {
  22497. super.copy( source );
  22498. this.parameters = Object.assign( {}, source.parameters );
  22499. return this;
  22500. }
  22501. static fromJSON( data ) {
  22502. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  22503. }
  22504. }
  22505. class ShapeGeometry extends BufferGeometry {
  22506. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  22507. super();
  22508. this.type = 'ShapeGeometry';
  22509. this.parameters = {
  22510. shapes: shapes,
  22511. curveSegments: curveSegments
  22512. };
  22513. // buffers
  22514. const indices = [];
  22515. const vertices = [];
  22516. const normals = [];
  22517. const uvs = [];
  22518. // helper variables
  22519. let groupStart = 0;
  22520. let groupCount = 0;
  22521. // allow single and array values for "shapes" parameter
  22522. if ( Array.isArray( shapes ) === false ) {
  22523. addShape( shapes );
  22524. } else {
  22525. for ( let i = 0; i < shapes.length; i ++ ) {
  22526. addShape( shapes[ i ] );
  22527. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  22528. groupStart += groupCount;
  22529. groupCount = 0;
  22530. }
  22531. }
  22532. // build geometry
  22533. this.setIndex( indices );
  22534. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22535. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22536. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22537. // helper functions
  22538. function addShape( shape ) {
  22539. const indexOffset = vertices.length / 3;
  22540. const points = shape.extractPoints( curveSegments );
  22541. let shapeVertices = points.shape;
  22542. const shapeHoles = points.holes;
  22543. // check direction of vertices
  22544. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  22545. shapeVertices = shapeVertices.reverse();
  22546. }
  22547. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22548. const shapeHole = shapeHoles[ i ];
  22549. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  22550. shapeHoles[ i ] = shapeHole.reverse();
  22551. }
  22552. }
  22553. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  22554. // join vertices of inner and outer paths to a single array
  22555. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22556. const shapeHole = shapeHoles[ i ];
  22557. shapeVertices = shapeVertices.concat( shapeHole );
  22558. }
  22559. // vertices, normals, uvs
  22560. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  22561. const vertex = shapeVertices[ i ];
  22562. vertices.push( vertex.x, vertex.y, 0 );
  22563. normals.push( 0, 0, 1 );
  22564. uvs.push( vertex.x, vertex.y ); // world uvs
  22565. }
  22566. // indices
  22567. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  22568. const face = faces[ i ];
  22569. const a = face[ 0 ] + indexOffset;
  22570. const b = face[ 1 ] + indexOffset;
  22571. const c = face[ 2 ] + indexOffset;
  22572. indices.push( a, b, c );
  22573. groupCount += 3;
  22574. }
  22575. }
  22576. }
  22577. copy( source ) {
  22578. super.copy( source );
  22579. this.parameters = Object.assign( {}, source.parameters );
  22580. return this;
  22581. }
  22582. toJSON() {
  22583. const data = super.toJSON();
  22584. const shapes = this.parameters.shapes;
  22585. return toJSON( shapes, data );
  22586. }
  22587. static fromJSON( data, shapes ) {
  22588. const geometryShapes = [];
  22589. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22590. const shape = shapes[ data.shapes[ j ] ];
  22591. geometryShapes.push( shape );
  22592. }
  22593. return new ShapeGeometry( geometryShapes, data.curveSegments );
  22594. }
  22595. }
  22596. function toJSON( shapes, data ) {
  22597. data.shapes = [];
  22598. if ( Array.isArray( shapes ) ) {
  22599. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22600. const shape = shapes[ i ];
  22601. data.shapes.push( shape.uuid );
  22602. }
  22603. } else {
  22604. data.shapes.push( shapes.uuid );
  22605. }
  22606. return data;
  22607. }
  22608. class SphereGeometry extends BufferGeometry {
  22609. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  22610. super();
  22611. this.type = 'SphereGeometry';
  22612. this.parameters = {
  22613. radius: radius,
  22614. widthSegments: widthSegments,
  22615. heightSegments: heightSegments,
  22616. phiStart: phiStart,
  22617. phiLength: phiLength,
  22618. thetaStart: thetaStart,
  22619. thetaLength: thetaLength
  22620. };
  22621. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  22622. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  22623. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22624. let index = 0;
  22625. const grid = [];
  22626. const vertex = new Vector3();
  22627. const normal = new Vector3();
  22628. // buffers
  22629. const indices = [];
  22630. const vertices = [];
  22631. const normals = [];
  22632. const uvs = [];
  22633. // generate vertices, normals and uvs
  22634. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22635. const verticesRow = [];
  22636. const v = iy / heightSegments;
  22637. // special case for the poles
  22638. let uOffset = 0;
  22639. if ( iy === 0 && thetaStart === 0 ) {
  22640. uOffset = 0.5 / widthSegments;
  22641. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22642. uOffset = - 0.5 / widthSegments;
  22643. }
  22644. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22645. const u = ix / widthSegments;
  22646. // vertex
  22647. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22648. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22649. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22650. vertices.push( vertex.x, vertex.y, vertex.z );
  22651. // normal
  22652. normal.copy( vertex ).normalize();
  22653. normals.push( normal.x, normal.y, normal.z );
  22654. // uv
  22655. uvs.push( u + uOffset, 1 - v );
  22656. verticesRow.push( index ++ );
  22657. }
  22658. grid.push( verticesRow );
  22659. }
  22660. // indices
  22661. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22662. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22663. const a = grid[ iy ][ ix + 1 ];
  22664. const b = grid[ iy ][ ix ];
  22665. const c = grid[ iy + 1 ][ ix ];
  22666. const d = grid[ iy + 1 ][ ix + 1 ];
  22667. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22668. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22669. }
  22670. }
  22671. // build geometry
  22672. this.setIndex( indices );
  22673. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22674. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22675. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22676. }
  22677. copy( source ) {
  22678. super.copy( source );
  22679. this.parameters = Object.assign( {}, source.parameters );
  22680. return this;
  22681. }
  22682. static fromJSON( data ) {
  22683. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22684. }
  22685. }
  22686. class TetrahedronGeometry extends PolyhedronGeometry {
  22687. constructor( radius = 1, detail = 0 ) {
  22688. const vertices = [
  22689. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22690. ];
  22691. const indices = [
  22692. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22693. ];
  22694. super( vertices, indices, radius, detail );
  22695. this.type = 'TetrahedronGeometry';
  22696. this.parameters = {
  22697. radius: radius,
  22698. detail: detail
  22699. };
  22700. }
  22701. static fromJSON( data ) {
  22702. return new TetrahedronGeometry( data.radius, data.detail );
  22703. }
  22704. }
  22705. class TorusGeometry extends BufferGeometry {
  22706. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22707. super();
  22708. this.type = 'TorusGeometry';
  22709. this.parameters = {
  22710. radius: radius,
  22711. tube: tube,
  22712. radialSegments: radialSegments,
  22713. tubularSegments: tubularSegments,
  22714. arc: arc
  22715. };
  22716. radialSegments = Math.floor( radialSegments );
  22717. tubularSegments = Math.floor( tubularSegments );
  22718. // buffers
  22719. const indices = [];
  22720. const vertices = [];
  22721. const normals = [];
  22722. const uvs = [];
  22723. // helper variables
  22724. const center = new Vector3();
  22725. const vertex = new Vector3();
  22726. const normal = new Vector3();
  22727. // generate vertices, normals and uvs
  22728. for ( let j = 0; j <= radialSegments; j ++ ) {
  22729. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22730. const u = i / tubularSegments * arc;
  22731. const v = j / radialSegments * Math.PI * 2;
  22732. // vertex
  22733. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22734. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22735. vertex.z = tube * Math.sin( v );
  22736. vertices.push( vertex.x, vertex.y, vertex.z );
  22737. // normal
  22738. center.x = radius * Math.cos( u );
  22739. center.y = radius * Math.sin( u );
  22740. normal.subVectors( vertex, center ).normalize();
  22741. normals.push( normal.x, normal.y, normal.z );
  22742. // uv
  22743. uvs.push( i / tubularSegments );
  22744. uvs.push( j / radialSegments );
  22745. }
  22746. }
  22747. // generate indices
  22748. for ( let j = 1; j <= radialSegments; j ++ ) {
  22749. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22750. // indices
  22751. const a = ( tubularSegments + 1 ) * j + i - 1;
  22752. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22753. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22754. const d = ( tubularSegments + 1 ) * j + i;
  22755. // faces
  22756. indices.push( a, b, d );
  22757. indices.push( b, c, d );
  22758. }
  22759. }
  22760. // build geometry
  22761. this.setIndex( indices );
  22762. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22763. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22764. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22765. }
  22766. copy( source ) {
  22767. super.copy( source );
  22768. this.parameters = Object.assign( {}, source.parameters );
  22769. return this;
  22770. }
  22771. static fromJSON( data ) {
  22772. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22773. }
  22774. }
  22775. class TorusKnotGeometry extends BufferGeometry {
  22776. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22777. super();
  22778. this.type = 'TorusKnotGeometry';
  22779. this.parameters = {
  22780. radius: radius,
  22781. tube: tube,
  22782. tubularSegments: tubularSegments,
  22783. radialSegments: radialSegments,
  22784. p: p,
  22785. q: q
  22786. };
  22787. tubularSegments = Math.floor( tubularSegments );
  22788. radialSegments = Math.floor( radialSegments );
  22789. // buffers
  22790. const indices = [];
  22791. const vertices = [];
  22792. const normals = [];
  22793. const uvs = [];
  22794. // helper variables
  22795. const vertex = new Vector3();
  22796. const normal = new Vector3();
  22797. const P1 = new Vector3();
  22798. const P2 = new Vector3();
  22799. const B = new Vector3();
  22800. const T = new Vector3();
  22801. const N = new Vector3();
  22802. // generate vertices, normals and uvs
  22803. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22804. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22805. const u = i / tubularSegments * p * Math.PI * 2;
  22806. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22807. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22808. calculatePositionOnCurve( u, p, q, radius, P1 );
  22809. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22810. // calculate orthonormal basis
  22811. T.subVectors( P2, P1 );
  22812. N.addVectors( P2, P1 );
  22813. B.crossVectors( T, N );
  22814. N.crossVectors( B, T );
  22815. // normalize B, N. T can be ignored, we don't use it
  22816. B.normalize();
  22817. N.normalize();
  22818. for ( let j = 0; j <= radialSegments; ++ j ) {
  22819. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22820. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22821. const v = j / radialSegments * Math.PI * 2;
  22822. const cx = - tube * Math.cos( v );
  22823. const cy = tube * Math.sin( v );
  22824. // now calculate the final vertex position.
  22825. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22826. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22827. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22828. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22829. vertices.push( vertex.x, vertex.y, vertex.z );
  22830. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22831. normal.subVectors( vertex, P1 ).normalize();
  22832. normals.push( normal.x, normal.y, normal.z );
  22833. // uv
  22834. uvs.push( i / tubularSegments );
  22835. uvs.push( j / radialSegments );
  22836. }
  22837. }
  22838. // generate indices
  22839. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22840. for ( let i = 1; i <= radialSegments; i ++ ) {
  22841. // indices
  22842. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22843. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22844. const c = ( radialSegments + 1 ) * j + i;
  22845. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22846. // faces
  22847. indices.push( a, b, d );
  22848. indices.push( b, c, d );
  22849. }
  22850. }
  22851. // build geometry
  22852. this.setIndex( indices );
  22853. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22854. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22855. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22856. // this function calculates the current position on the torus curve
  22857. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22858. const cu = Math.cos( u );
  22859. const su = Math.sin( u );
  22860. const quOverP = q / p * u;
  22861. const cs = Math.cos( quOverP );
  22862. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22863. position.y = radius * ( 2 + cs ) * su * 0.5;
  22864. position.z = radius * Math.sin( quOverP ) * 0.5;
  22865. }
  22866. }
  22867. copy( source ) {
  22868. super.copy( source );
  22869. this.parameters = Object.assign( {}, source.parameters );
  22870. return this;
  22871. }
  22872. static fromJSON( data ) {
  22873. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22874. }
  22875. }
  22876. class TubeGeometry extends BufferGeometry {
  22877. 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 ) {
  22878. super();
  22879. this.type = 'TubeGeometry';
  22880. this.parameters = {
  22881. path: path,
  22882. tubularSegments: tubularSegments,
  22883. radius: radius,
  22884. radialSegments: radialSegments,
  22885. closed: closed
  22886. };
  22887. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22888. // expose internals
  22889. this.tangents = frames.tangents;
  22890. this.normals = frames.normals;
  22891. this.binormals = frames.binormals;
  22892. // helper variables
  22893. const vertex = new Vector3();
  22894. const normal = new Vector3();
  22895. const uv = new Vector2();
  22896. let P = new Vector3();
  22897. // buffer
  22898. const vertices = [];
  22899. const normals = [];
  22900. const uvs = [];
  22901. const indices = [];
  22902. // create buffer data
  22903. generateBufferData();
  22904. // build geometry
  22905. this.setIndex( indices );
  22906. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22907. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22908. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22909. // functions
  22910. function generateBufferData() {
  22911. for ( let i = 0; i < tubularSegments; i ++ ) {
  22912. generateSegment( i );
  22913. }
  22914. // if the geometry is not closed, generate the last row of vertices and normals
  22915. // at the regular position on the given path
  22916. //
  22917. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22918. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22919. // uvs are generated in a separate function.
  22920. // this makes it easy compute correct values for closed geometries
  22921. generateUVs();
  22922. // finally create faces
  22923. generateIndices();
  22924. }
  22925. function generateSegment( i ) {
  22926. // we use getPointAt to sample evenly distributed points from the given path
  22927. P = path.getPointAt( i / tubularSegments, P );
  22928. // retrieve corresponding normal and binormal
  22929. const N = frames.normals[ i ];
  22930. const B = frames.binormals[ i ];
  22931. // generate normals and vertices for the current segment
  22932. for ( let j = 0; j <= radialSegments; j ++ ) {
  22933. const v = j / radialSegments * Math.PI * 2;
  22934. const sin = Math.sin( v );
  22935. const cos = - Math.cos( v );
  22936. // normal
  22937. normal.x = ( cos * N.x + sin * B.x );
  22938. normal.y = ( cos * N.y + sin * B.y );
  22939. normal.z = ( cos * N.z + sin * B.z );
  22940. normal.normalize();
  22941. normals.push( normal.x, normal.y, normal.z );
  22942. // vertex
  22943. vertex.x = P.x + radius * normal.x;
  22944. vertex.y = P.y + radius * normal.y;
  22945. vertex.z = P.z + radius * normal.z;
  22946. vertices.push( vertex.x, vertex.y, vertex.z );
  22947. }
  22948. }
  22949. function generateIndices() {
  22950. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22951. for ( let i = 1; i <= radialSegments; i ++ ) {
  22952. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22953. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22954. const c = ( radialSegments + 1 ) * j + i;
  22955. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22956. // faces
  22957. indices.push( a, b, d );
  22958. indices.push( b, c, d );
  22959. }
  22960. }
  22961. }
  22962. function generateUVs() {
  22963. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22964. for ( let j = 0; j <= radialSegments; j ++ ) {
  22965. uv.x = i / tubularSegments;
  22966. uv.y = j / radialSegments;
  22967. uvs.push( uv.x, uv.y );
  22968. }
  22969. }
  22970. }
  22971. }
  22972. copy( source ) {
  22973. super.copy( source );
  22974. this.parameters = Object.assign( {}, source.parameters );
  22975. return this;
  22976. }
  22977. toJSON() {
  22978. const data = super.toJSON();
  22979. data.path = this.parameters.path.toJSON();
  22980. return data;
  22981. }
  22982. static fromJSON( data ) {
  22983. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22984. // User defined curves or instances of CurvePath will not be deserialized.
  22985. return new TubeGeometry(
  22986. new Curves[ data.path.type ]().fromJSON( data.path ),
  22987. data.tubularSegments,
  22988. data.radius,
  22989. data.radialSegments,
  22990. data.closed
  22991. );
  22992. }
  22993. }
  22994. class WireframeGeometry extends BufferGeometry {
  22995. constructor( geometry = null ) {
  22996. super();
  22997. this.type = 'WireframeGeometry';
  22998. this.parameters = {
  22999. geometry: geometry
  23000. };
  23001. if ( geometry !== null ) {
  23002. // buffer
  23003. const vertices = [];
  23004. const edges = new Set();
  23005. // helper variables
  23006. const start = new Vector3();
  23007. const end = new Vector3();
  23008. if ( geometry.index !== null ) {
  23009. // indexed BufferGeometry
  23010. const position = geometry.attributes.position;
  23011. const indices = geometry.index;
  23012. let groups = geometry.groups;
  23013. if ( groups.length === 0 ) {
  23014. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  23015. }
  23016. // create a data structure that contains all edges without duplicates
  23017. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  23018. const group = groups[ o ];
  23019. const groupStart = group.start;
  23020. const groupCount = group.count;
  23021. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  23022. for ( let j = 0; j < 3; j ++ ) {
  23023. const index1 = indices.getX( i + j );
  23024. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  23025. start.fromBufferAttribute( position, index1 );
  23026. end.fromBufferAttribute( position, index2 );
  23027. if ( isUniqueEdge( start, end, edges ) === true ) {
  23028. vertices.push( start.x, start.y, start.z );
  23029. vertices.push( end.x, end.y, end.z );
  23030. }
  23031. }
  23032. }
  23033. }
  23034. } else {
  23035. // non-indexed BufferGeometry
  23036. const position = geometry.attributes.position;
  23037. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  23038. for ( let j = 0; j < 3; j ++ ) {
  23039. // three edges per triangle, an edge is represented as (index1, index2)
  23040. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  23041. const index1 = 3 * i + j;
  23042. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  23043. start.fromBufferAttribute( position, index1 );
  23044. end.fromBufferAttribute( position, index2 );
  23045. if ( isUniqueEdge( start, end, edges ) === true ) {
  23046. vertices.push( start.x, start.y, start.z );
  23047. vertices.push( end.x, end.y, end.z );
  23048. }
  23049. }
  23050. }
  23051. }
  23052. // build geometry
  23053. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23054. }
  23055. }
  23056. copy( source ) {
  23057. super.copy( source );
  23058. this.parameters = Object.assign( {}, source.parameters );
  23059. return this;
  23060. }
  23061. }
  23062. function isUniqueEdge( start, end, edges ) {
  23063. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  23064. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  23065. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  23066. return false;
  23067. } else {
  23068. edges.add( hash1 );
  23069. edges.add( hash2 );
  23070. return true;
  23071. }
  23072. }
  23073. var Geometries = /*#__PURE__*/Object.freeze({
  23074. __proto__: null,
  23075. BoxGeometry: BoxGeometry,
  23076. CapsuleGeometry: CapsuleGeometry,
  23077. CircleGeometry: CircleGeometry,
  23078. ConeGeometry: ConeGeometry,
  23079. CylinderGeometry: CylinderGeometry,
  23080. DodecahedronGeometry: DodecahedronGeometry,
  23081. EdgesGeometry: EdgesGeometry,
  23082. ExtrudeGeometry: ExtrudeGeometry,
  23083. IcosahedronGeometry: IcosahedronGeometry,
  23084. LatheGeometry: LatheGeometry,
  23085. OctahedronGeometry: OctahedronGeometry,
  23086. PlaneGeometry: PlaneGeometry,
  23087. PolyhedronGeometry: PolyhedronGeometry,
  23088. RingGeometry: RingGeometry,
  23089. ShapeGeometry: ShapeGeometry,
  23090. SphereGeometry: SphereGeometry,
  23091. TetrahedronGeometry: TetrahedronGeometry,
  23092. TorusGeometry: TorusGeometry,
  23093. TorusKnotGeometry: TorusKnotGeometry,
  23094. TubeGeometry: TubeGeometry,
  23095. WireframeGeometry: WireframeGeometry
  23096. });
  23097. class ShadowMaterial extends Material {
  23098. constructor( parameters ) {
  23099. super();
  23100. this.isShadowMaterial = true;
  23101. this.type = 'ShadowMaterial';
  23102. this.color = new Color( 0x000000 );
  23103. this.transparent = true;
  23104. this.fog = true;
  23105. this.setValues( parameters );
  23106. }
  23107. copy( source ) {
  23108. super.copy( source );
  23109. this.color.copy( source.color );
  23110. this.fog = source.fog;
  23111. return this;
  23112. }
  23113. }
  23114. class RawShaderMaterial extends ShaderMaterial {
  23115. constructor( parameters ) {
  23116. super( parameters );
  23117. this.isRawShaderMaterial = true;
  23118. this.type = 'RawShaderMaterial';
  23119. }
  23120. }
  23121. class MeshStandardMaterial extends Material {
  23122. constructor( parameters ) {
  23123. super();
  23124. this.isMeshStandardMaterial = true;
  23125. this.defines = { 'STANDARD': '' };
  23126. this.type = 'MeshStandardMaterial';
  23127. this.color = new Color( 0xffffff ); // diffuse
  23128. this.roughness = 1.0;
  23129. this.metalness = 0.0;
  23130. this.map = null;
  23131. this.lightMap = null;
  23132. this.lightMapIntensity = 1.0;
  23133. this.aoMap = null;
  23134. this.aoMapIntensity = 1.0;
  23135. this.emissive = new Color( 0x000000 );
  23136. this.emissiveIntensity = 1.0;
  23137. this.emissiveMap = null;
  23138. this.bumpMap = null;
  23139. this.bumpScale = 1;
  23140. this.normalMap = null;
  23141. this.normalMapType = TangentSpaceNormalMap;
  23142. this.normalScale = new Vector2( 1, 1 );
  23143. this.displacementMap = null;
  23144. this.displacementScale = 1;
  23145. this.displacementBias = 0;
  23146. this.roughnessMap = null;
  23147. this.metalnessMap = null;
  23148. this.alphaMap = null;
  23149. this.envMap = null;
  23150. this.envMapIntensity = 1.0;
  23151. this.wireframe = false;
  23152. this.wireframeLinewidth = 1;
  23153. this.wireframeLinecap = 'round';
  23154. this.wireframeLinejoin = 'round';
  23155. this.flatShading = false;
  23156. this.fog = true;
  23157. this.setValues( parameters );
  23158. }
  23159. copy( source ) {
  23160. super.copy( source );
  23161. this.defines = { 'STANDARD': '' };
  23162. this.color.copy( source.color );
  23163. this.roughness = source.roughness;
  23164. this.metalness = source.metalness;
  23165. this.map = source.map;
  23166. this.lightMap = source.lightMap;
  23167. this.lightMapIntensity = source.lightMapIntensity;
  23168. this.aoMap = source.aoMap;
  23169. this.aoMapIntensity = source.aoMapIntensity;
  23170. this.emissive.copy( source.emissive );
  23171. this.emissiveMap = source.emissiveMap;
  23172. this.emissiveIntensity = source.emissiveIntensity;
  23173. this.bumpMap = source.bumpMap;
  23174. this.bumpScale = source.bumpScale;
  23175. this.normalMap = source.normalMap;
  23176. this.normalMapType = source.normalMapType;
  23177. this.normalScale.copy( source.normalScale );
  23178. this.displacementMap = source.displacementMap;
  23179. this.displacementScale = source.displacementScale;
  23180. this.displacementBias = source.displacementBias;
  23181. this.roughnessMap = source.roughnessMap;
  23182. this.metalnessMap = source.metalnessMap;
  23183. this.alphaMap = source.alphaMap;
  23184. this.envMap = source.envMap;
  23185. this.envMapIntensity = source.envMapIntensity;
  23186. this.wireframe = source.wireframe;
  23187. this.wireframeLinewidth = source.wireframeLinewidth;
  23188. this.wireframeLinecap = source.wireframeLinecap;
  23189. this.wireframeLinejoin = source.wireframeLinejoin;
  23190. this.flatShading = source.flatShading;
  23191. this.fog = source.fog;
  23192. return this;
  23193. }
  23194. }
  23195. class MeshPhysicalMaterial extends MeshStandardMaterial {
  23196. constructor( parameters ) {
  23197. super();
  23198. this.isMeshPhysicalMaterial = true;
  23199. this.defines = {
  23200. 'STANDARD': '',
  23201. 'PHYSICAL': ''
  23202. };
  23203. this.type = 'MeshPhysicalMaterial';
  23204. this.anisotropyRotation = 0;
  23205. this.anisotropyMap = null;
  23206. this.clearcoatMap = null;
  23207. this.clearcoatRoughness = 0.0;
  23208. this.clearcoatRoughnessMap = null;
  23209. this.clearcoatNormalScale = new Vector2( 1, 1 );
  23210. this.clearcoatNormalMap = null;
  23211. this.ior = 1.5;
  23212. Object.defineProperty( this, 'reflectivity', {
  23213. get: function () {
  23214. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  23215. },
  23216. set: function ( reflectivity ) {
  23217. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  23218. }
  23219. } );
  23220. this.iridescenceMap = null;
  23221. this.iridescenceIOR = 1.3;
  23222. this.iridescenceThicknessRange = [ 100, 400 ];
  23223. this.iridescenceThicknessMap = null;
  23224. this.sheenColor = new Color( 0x000000 );
  23225. this.sheenColorMap = null;
  23226. this.sheenRoughness = 1.0;
  23227. this.sheenRoughnessMap = null;
  23228. this.transmissionMap = null;
  23229. this.thickness = 0;
  23230. this.thicknessMap = null;
  23231. this.attenuationDistance = Infinity;
  23232. this.attenuationColor = new Color( 1, 1, 1 );
  23233. this.specularIntensity = 1.0;
  23234. this.specularIntensityMap = null;
  23235. this.specularColor = new Color( 1, 1, 1 );
  23236. this.specularColorMap = null;
  23237. this._anisotropy = 0;
  23238. this._clearcoat = 0;
  23239. this._iridescence = 0;
  23240. this._sheen = 0.0;
  23241. this._transmission = 0;
  23242. this.setValues( parameters );
  23243. }
  23244. get anisotropy() {
  23245. return this._anisotropy;
  23246. }
  23247. set anisotropy( value ) {
  23248. if ( this._anisotropy > 0 !== value > 0 ) {
  23249. this.version ++;
  23250. }
  23251. this._anisotropy = value;
  23252. }
  23253. get clearcoat() {
  23254. return this._clearcoat;
  23255. }
  23256. set clearcoat( value ) {
  23257. if ( this._clearcoat > 0 !== value > 0 ) {
  23258. this.version ++;
  23259. }
  23260. this._clearcoat = value;
  23261. }
  23262. get iridescence() {
  23263. return this._iridescence;
  23264. }
  23265. set iridescence( value ) {
  23266. if ( this._iridescence > 0 !== value > 0 ) {
  23267. this.version ++;
  23268. }
  23269. this._iridescence = value;
  23270. }
  23271. get sheen() {
  23272. return this._sheen;
  23273. }
  23274. set sheen( value ) {
  23275. if ( this._sheen > 0 !== value > 0 ) {
  23276. this.version ++;
  23277. }
  23278. this._sheen = value;
  23279. }
  23280. get transmission() {
  23281. return this._transmission;
  23282. }
  23283. set transmission( value ) {
  23284. if ( this._transmission > 0 !== value > 0 ) {
  23285. this.version ++;
  23286. }
  23287. this._transmission = value;
  23288. }
  23289. copy( source ) {
  23290. super.copy( source );
  23291. this.defines = {
  23292. 'STANDARD': '',
  23293. 'PHYSICAL': ''
  23294. };
  23295. this.anisotropy = source.anisotropy;
  23296. this.anisotropyRotation = source.anisotropyRotation;
  23297. this.anisotropyMap = source.anisotropyMap;
  23298. this.clearcoat = source.clearcoat;
  23299. this.clearcoatMap = source.clearcoatMap;
  23300. this.clearcoatRoughness = source.clearcoatRoughness;
  23301. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  23302. this.clearcoatNormalMap = source.clearcoatNormalMap;
  23303. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  23304. this.ior = source.ior;
  23305. this.iridescence = source.iridescence;
  23306. this.iridescenceMap = source.iridescenceMap;
  23307. this.iridescenceIOR = source.iridescenceIOR;
  23308. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  23309. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  23310. this.sheen = source.sheen;
  23311. this.sheenColor.copy( source.sheenColor );
  23312. this.sheenColorMap = source.sheenColorMap;
  23313. this.sheenRoughness = source.sheenRoughness;
  23314. this.sheenRoughnessMap = source.sheenRoughnessMap;
  23315. this.transmission = source.transmission;
  23316. this.transmissionMap = source.transmissionMap;
  23317. this.thickness = source.thickness;
  23318. this.thicknessMap = source.thicknessMap;
  23319. this.attenuationDistance = source.attenuationDistance;
  23320. this.attenuationColor.copy( source.attenuationColor );
  23321. this.specularIntensity = source.specularIntensity;
  23322. this.specularIntensityMap = source.specularIntensityMap;
  23323. this.specularColor.copy( source.specularColor );
  23324. this.specularColorMap = source.specularColorMap;
  23325. return this;
  23326. }
  23327. }
  23328. class MeshPhongMaterial extends Material {
  23329. constructor( parameters ) {
  23330. super();
  23331. this.isMeshPhongMaterial = true;
  23332. this.type = 'MeshPhongMaterial';
  23333. this.color = new Color( 0xffffff ); // diffuse
  23334. this.specular = new Color( 0x111111 );
  23335. this.shininess = 30;
  23336. this.map = null;
  23337. this.lightMap = null;
  23338. this.lightMapIntensity = 1.0;
  23339. this.aoMap = null;
  23340. this.aoMapIntensity = 1.0;
  23341. this.emissive = new Color( 0x000000 );
  23342. this.emissiveIntensity = 1.0;
  23343. this.emissiveMap = null;
  23344. this.bumpMap = null;
  23345. this.bumpScale = 1;
  23346. this.normalMap = null;
  23347. this.normalMapType = TangentSpaceNormalMap;
  23348. this.normalScale = new Vector2( 1, 1 );
  23349. this.displacementMap = null;
  23350. this.displacementScale = 1;
  23351. this.displacementBias = 0;
  23352. this.specularMap = null;
  23353. this.alphaMap = null;
  23354. this.envMap = null;
  23355. this.combine = MultiplyOperation;
  23356. this.reflectivity = 1;
  23357. this.refractionRatio = 0.98;
  23358. this.wireframe = false;
  23359. this.wireframeLinewidth = 1;
  23360. this.wireframeLinecap = 'round';
  23361. this.wireframeLinejoin = 'round';
  23362. this.flatShading = false;
  23363. this.fog = true;
  23364. this.setValues( parameters );
  23365. }
  23366. copy( source ) {
  23367. super.copy( source );
  23368. this.color.copy( source.color );
  23369. this.specular.copy( source.specular );
  23370. this.shininess = source.shininess;
  23371. this.map = source.map;
  23372. this.lightMap = source.lightMap;
  23373. this.lightMapIntensity = source.lightMapIntensity;
  23374. this.aoMap = source.aoMap;
  23375. this.aoMapIntensity = source.aoMapIntensity;
  23376. this.emissive.copy( source.emissive );
  23377. this.emissiveMap = source.emissiveMap;
  23378. this.emissiveIntensity = source.emissiveIntensity;
  23379. this.bumpMap = source.bumpMap;
  23380. this.bumpScale = source.bumpScale;
  23381. this.normalMap = source.normalMap;
  23382. this.normalMapType = source.normalMapType;
  23383. this.normalScale.copy( source.normalScale );
  23384. this.displacementMap = source.displacementMap;
  23385. this.displacementScale = source.displacementScale;
  23386. this.displacementBias = source.displacementBias;
  23387. this.specularMap = source.specularMap;
  23388. this.alphaMap = source.alphaMap;
  23389. this.envMap = source.envMap;
  23390. this.combine = source.combine;
  23391. this.reflectivity = source.reflectivity;
  23392. this.refractionRatio = source.refractionRatio;
  23393. this.wireframe = source.wireframe;
  23394. this.wireframeLinewidth = source.wireframeLinewidth;
  23395. this.wireframeLinecap = source.wireframeLinecap;
  23396. this.wireframeLinejoin = source.wireframeLinejoin;
  23397. this.flatShading = source.flatShading;
  23398. this.fog = source.fog;
  23399. return this;
  23400. }
  23401. }
  23402. class MeshToonMaterial extends Material {
  23403. constructor( parameters ) {
  23404. super();
  23405. this.isMeshToonMaterial = true;
  23406. this.defines = { 'TOON': '' };
  23407. this.type = 'MeshToonMaterial';
  23408. this.color = new Color( 0xffffff );
  23409. this.map = null;
  23410. this.gradientMap = null;
  23411. this.lightMap = null;
  23412. this.lightMapIntensity = 1.0;
  23413. this.aoMap = null;
  23414. this.aoMapIntensity = 1.0;
  23415. this.emissive = new Color( 0x000000 );
  23416. this.emissiveIntensity = 1.0;
  23417. this.emissiveMap = null;
  23418. this.bumpMap = null;
  23419. this.bumpScale = 1;
  23420. this.normalMap = null;
  23421. this.normalMapType = TangentSpaceNormalMap;
  23422. this.normalScale = new Vector2( 1, 1 );
  23423. this.displacementMap = null;
  23424. this.displacementScale = 1;
  23425. this.displacementBias = 0;
  23426. this.alphaMap = null;
  23427. this.wireframe = false;
  23428. this.wireframeLinewidth = 1;
  23429. this.wireframeLinecap = 'round';
  23430. this.wireframeLinejoin = 'round';
  23431. this.fog = true;
  23432. this.setValues( parameters );
  23433. }
  23434. copy( source ) {
  23435. super.copy( source );
  23436. this.color.copy( source.color );
  23437. this.map = source.map;
  23438. this.gradientMap = source.gradientMap;
  23439. this.lightMap = source.lightMap;
  23440. this.lightMapIntensity = source.lightMapIntensity;
  23441. this.aoMap = source.aoMap;
  23442. this.aoMapIntensity = source.aoMapIntensity;
  23443. this.emissive.copy( source.emissive );
  23444. this.emissiveMap = source.emissiveMap;
  23445. this.emissiveIntensity = source.emissiveIntensity;
  23446. this.bumpMap = source.bumpMap;
  23447. this.bumpScale = source.bumpScale;
  23448. this.normalMap = source.normalMap;
  23449. this.normalMapType = source.normalMapType;
  23450. this.normalScale.copy( source.normalScale );
  23451. this.displacementMap = source.displacementMap;
  23452. this.displacementScale = source.displacementScale;
  23453. this.displacementBias = source.displacementBias;
  23454. this.alphaMap = source.alphaMap;
  23455. this.wireframe = source.wireframe;
  23456. this.wireframeLinewidth = source.wireframeLinewidth;
  23457. this.wireframeLinecap = source.wireframeLinecap;
  23458. this.wireframeLinejoin = source.wireframeLinejoin;
  23459. this.fog = source.fog;
  23460. return this;
  23461. }
  23462. }
  23463. class MeshNormalMaterial extends Material {
  23464. constructor( parameters ) {
  23465. super();
  23466. this.isMeshNormalMaterial = true;
  23467. this.type = 'MeshNormalMaterial';
  23468. this.bumpMap = null;
  23469. this.bumpScale = 1;
  23470. this.normalMap = null;
  23471. this.normalMapType = TangentSpaceNormalMap;
  23472. this.normalScale = new Vector2( 1, 1 );
  23473. this.displacementMap = null;
  23474. this.displacementScale = 1;
  23475. this.displacementBias = 0;
  23476. this.wireframe = false;
  23477. this.wireframeLinewidth = 1;
  23478. this.flatShading = false;
  23479. this.setValues( parameters );
  23480. }
  23481. copy( source ) {
  23482. super.copy( source );
  23483. this.bumpMap = source.bumpMap;
  23484. this.bumpScale = source.bumpScale;
  23485. this.normalMap = source.normalMap;
  23486. this.normalMapType = source.normalMapType;
  23487. this.normalScale.copy( source.normalScale );
  23488. this.displacementMap = source.displacementMap;
  23489. this.displacementScale = source.displacementScale;
  23490. this.displacementBias = source.displacementBias;
  23491. this.wireframe = source.wireframe;
  23492. this.wireframeLinewidth = source.wireframeLinewidth;
  23493. this.flatShading = source.flatShading;
  23494. return this;
  23495. }
  23496. }
  23497. class MeshLambertMaterial extends Material {
  23498. constructor( parameters ) {
  23499. super();
  23500. this.isMeshLambertMaterial = true;
  23501. this.type = 'MeshLambertMaterial';
  23502. this.color = new Color( 0xffffff ); // diffuse
  23503. this.map = null;
  23504. this.lightMap = null;
  23505. this.lightMapIntensity = 1.0;
  23506. this.aoMap = null;
  23507. this.aoMapIntensity = 1.0;
  23508. this.emissive = new Color( 0x000000 );
  23509. this.emissiveIntensity = 1.0;
  23510. this.emissiveMap = null;
  23511. this.bumpMap = null;
  23512. this.bumpScale = 1;
  23513. this.normalMap = null;
  23514. this.normalMapType = TangentSpaceNormalMap;
  23515. this.normalScale = new Vector2( 1, 1 );
  23516. this.displacementMap = null;
  23517. this.displacementScale = 1;
  23518. this.displacementBias = 0;
  23519. this.specularMap = null;
  23520. this.alphaMap = null;
  23521. this.envMap = null;
  23522. this.combine = MultiplyOperation;
  23523. this.reflectivity = 1;
  23524. this.refractionRatio = 0.98;
  23525. this.wireframe = false;
  23526. this.wireframeLinewidth = 1;
  23527. this.wireframeLinecap = 'round';
  23528. this.wireframeLinejoin = 'round';
  23529. this.flatShading = false;
  23530. this.fog = true;
  23531. this.setValues( parameters );
  23532. }
  23533. copy( source ) {
  23534. super.copy( source );
  23535. this.color.copy( source.color );
  23536. this.map = source.map;
  23537. this.lightMap = source.lightMap;
  23538. this.lightMapIntensity = source.lightMapIntensity;
  23539. this.aoMap = source.aoMap;
  23540. this.aoMapIntensity = source.aoMapIntensity;
  23541. this.emissive.copy( source.emissive );
  23542. this.emissiveMap = source.emissiveMap;
  23543. this.emissiveIntensity = source.emissiveIntensity;
  23544. this.bumpMap = source.bumpMap;
  23545. this.bumpScale = source.bumpScale;
  23546. this.normalMap = source.normalMap;
  23547. this.normalMapType = source.normalMapType;
  23548. this.normalScale.copy( source.normalScale );
  23549. this.displacementMap = source.displacementMap;
  23550. this.displacementScale = source.displacementScale;
  23551. this.displacementBias = source.displacementBias;
  23552. this.specularMap = source.specularMap;
  23553. this.alphaMap = source.alphaMap;
  23554. this.envMap = source.envMap;
  23555. this.combine = source.combine;
  23556. this.reflectivity = source.reflectivity;
  23557. this.refractionRatio = source.refractionRatio;
  23558. this.wireframe = source.wireframe;
  23559. this.wireframeLinewidth = source.wireframeLinewidth;
  23560. this.wireframeLinecap = source.wireframeLinecap;
  23561. this.wireframeLinejoin = source.wireframeLinejoin;
  23562. this.flatShading = source.flatShading;
  23563. this.fog = source.fog;
  23564. return this;
  23565. }
  23566. }
  23567. class MeshMatcapMaterial extends Material {
  23568. constructor( parameters ) {
  23569. super();
  23570. this.isMeshMatcapMaterial = true;
  23571. this.defines = { 'MATCAP': '' };
  23572. this.type = 'MeshMatcapMaterial';
  23573. this.color = new Color( 0xffffff ); // diffuse
  23574. this.matcap = null;
  23575. this.map = null;
  23576. this.bumpMap = null;
  23577. this.bumpScale = 1;
  23578. this.normalMap = null;
  23579. this.normalMapType = TangentSpaceNormalMap;
  23580. this.normalScale = new Vector2( 1, 1 );
  23581. this.displacementMap = null;
  23582. this.displacementScale = 1;
  23583. this.displacementBias = 0;
  23584. this.alphaMap = null;
  23585. this.flatShading = false;
  23586. this.fog = true;
  23587. this.setValues( parameters );
  23588. }
  23589. copy( source ) {
  23590. super.copy( source );
  23591. this.defines = { 'MATCAP': '' };
  23592. this.color.copy( source.color );
  23593. this.matcap = source.matcap;
  23594. this.map = source.map;
  23595. this.bumpMap = source.bumpMap;
  23596. this.bumpScale = source.bumpScale;
  23597. this.normalMap = source.normalMap;
  23598. this.normalMapType = source.normalMapType;
  23599. this.normalScale.copy( source.normalScale );
  23600. this.displacementMap = source.displacementMap;
  23601. this.displacementScale = source.displacementScale;
  23602. this.displacementBias = source.displacementBias;
  23603. this.alphaMap = source.alphaMap;
  23604. this.flatShading = source.flatShading;
  23605. this.fog = source.fog;
  23606. return this;
  23607. }
  23608. }
  23609. class LineDashedMaterial extends LineBasicMaterial {
  23610. constructor( parameters ) {
  23611. super();
  23612. this.isLineDashedMaterial = true;
  23613. this.type = 'LineDashedMaterial';
  23614. this.scale = 1;
  23615. this.dashSize = 3;
  23616. this.gapSize = 1;
  23617. this.setValues( parameters );
  23618. }
  23619. copy( source ) {
  23620. super.copy( source );
  23621. this.scale = source.scale;
  23622. this.dashSize = source.dashSize;
  23623. this.gapSize = source.gapSize;
  23624. return this;
  23625. }
  23626. }
  23627. // converts an array to a specific type
  23628. function convertArray( array, type, forceClone ) {
  23629. if ( ! array || // let 'undefined' and 'null' pass
  23630. ! forceClone && array.constructor === type ) return array;
  23631. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23632. return new type( array ); // create typed array
  23633. }
  23634. return Array.prototype.slice.call( array ); // create Array
  23635. }
  23636. function isTypedArray( object ) {
  23637. return ArrayBuffer.isView( object ) &&
  23638. ! ( object instanceof DataView );
  23639. }
  23640. // returns an array by which times and values can be sorted
  23641. function getKeyframeOrder( times ) {
  23642. function compareTime( i, j ) {
  23643. return times[ i ] - times[ j ];
  23644. }
  23645. const n = times.length;
  23646. const result = new Array( n );
  23647. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23648. result.sort( compareTime );
  23649. return result;
  23650. }
  23651. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23652. function sortedArray( values, stride, order ) {
  23653. const nValues = values.length;
  23654. const result = new values.constructor( nValues );
  23655. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23656. const srcOffset = order[ i ] * stride;
  23657. for ( let j = 0; j !== stride; ++ j ) {
  23658. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23659. }
  23660. }
  23661. return result;
  23662. }
  23663. // function for parsing AOS keyframe formats
  23664. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23665. let i = 1, key = jsonKeys[ 0 ];
  23666. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23667. key = jsonKeys[ i ++ ];
  23668. }
  23669. if ( key === undefined ) return; // no data
  23670. let value = key[ valuePropertyName ];
  23671. if ( value === undefined ) return; // no data
  23672. if ( Array.isArray( value ) ) {
  23673. do {
  23674. value = key[ valuePropertyName ];
  23675. if ( value !== undefined ) {
  23676. times.push( key.time );
  23677. values.push.apply( values, value ); // push all elements
  23678. }
  23679. key = jsonKeys[ i ++ ];
  23680. } while ( key !== undefined );
  23681. } else if ( value.toArray !== undefined ) {
  23682. // ...assume THREE.Math-ish
  23683. do {
  23684. value = key[ valuePropertyName ];
  23685. if ( value !== undefined ) {
  23686. times.push( key.time );
  23687. value.toArray( values, values.length );
  23688. }
  23689. key = jsonKeys[ i ++ ];
  23690. } while ( key !== undefined );
  23691. } else {
  23692. // otherwise push as-is
  23693. do {
  23694. value = key[ valuePropertyName ];
  23695. if ( value !== undefined ) {
  23696. times.push( key.time );
  23697. values.push( value );
  23698. }
  23699. key = jsonKeys[ i ++ ];
  23700. } while ( key !== undefined );
  23701. }
  23702. }
  23703. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23704. const clip = sourceClip.clone();
  23705. clip.name = name;
  23706. const tracks = [];
  23707. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23708. const track = clip.tracks[ i ];
  23709. const valueSize = track.getValueSize();
  23710. const times = [];
  23711. const values = [];
  23712. for ( let j = 0; j < track.times.length; ++ j ) {
  23713. const frame = track.times[ j ] * fps;
  23714. if ( frame < startFrame || frame >= endFrame ) continue;
  23715. times.push( track.times[ j ] );
  23716. for ( let k = 0; k < valueSize; ++ k ) {
  23717. values.push( track.values[ j * valueSize + k ] );
  23718. }
  23719. }
  23720. if ( times.length === 0 ) continue;
  23721. track.times = convertArray( times, track.times.constructor );
  23722. track.values = convertArray( values, track.values.constructor );
  23723. tracks.push( track );
  23724. }
  23725. clip.tracks = tracks;
  23726. // find minimum .times value across all tracks in the trimmed clip
  23727. let minStartTime = Infinity;
  23728. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23729. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23730. minStartTime = clip.tracks[ i ].times[ 0 ];
  23731. }
  23732. }
  23733. // shift all tracks such that clip begins at t=0
  23734. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23735. clip.tracks[ i ].shift( - 1 * minStartTime );
  23736. }
  23737. clip.resetDuration();
  23738. return clip;
  23739. }
  23740. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23741. if ( fps <= 0 ) fps = 30;
  23742. const numTracks = referenceClip.tracks.length;
  23743. const referenceTime = referenceFrame / fps;
  23744. // Make each track's values relative to the values at the reference frame
  23745. for ( let i = 0; i < numTracks; ++ i ) {
  23746. const referenceTrack = referenceClip.tracks[ i ];
  23747. const referenceTrackType = referenceTrack.ValueTypeName;
  23748. // Skip this track if it's non-numeric
  23749. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23750. // Find the track in the target clip whose name and type matches the reference track
  23751. const targetTrack = targetClip.tracks.find( function ( track ) {
  23752. return track.name === referenceTrack.name
  23753. && track.ValueTypeName === referenceTrackType;
  23754. } );
  23755. if ( targetTrack === undefined ) continue;
  23756. let referenceOffset = 0;
  23757. const referenceValueSize = referenceTrack.getValueSize();
  23758. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23759. referenceOffset = referenceValueSize / 3;
  23760. }
  23761. let targetOffset = 0;
  23762. const targetValueSize = targetTrack.getValueSize();
  23763. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23764. targetOffset = targetValueSize / 3;
  23765. }
  23766. const lastIndex = referenceTrack.times.length - 1;
  23767. let referenceValue;
  23768. // Find the value to subtract out of the track
  23769. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23770. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23771. const startIndex = referenceOffset;
  23772. const endIndex = referenceValueSize - referenceOffset;
  23773. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  23774. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23775. // Reference frame is after the last keyframe, so just use the last keyframe
  23776. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23777. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23778. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  23779. } else {
  23780. // Interpolate to the reference value
  23781. const interpolant = referenceTrack.createInterpolant();
  23782. const startIndex = referenceOffset;
  23783. const endIndex = referenceValueSize - referenceOffset;
  23784. interpolant.evaluate( referenceTime );
  23785. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  23786. }
  23787. // Conjugate the quaternion
  23788. if ( referenceTrackType === 'quaternion' ) {
  23789. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23790. referenceQuat.toArray( referenceValue );
  23791. }
  23792. // Subtract the reference value from all of the track values
  23793. const numTimes = targetTrack.times.length;
  23794. for ( let j = 0; j < numTimes; ++ j ) {
  23795. const valueStart = j * targetValueSize + targetOffset;
  23796. if ( referenceTrackType === 'quaternion' ) {
  23797. // Multiply the conjugate for quaternion track types
  23798. Quaternion.multiplyQuaternionsFlat(
  23799. targetTrack.values,
  23800. valueStart,
  23801. referenceValue,
  23802. 0,
  23803. targetTrack.values,
  23804. valueStart
  23805. );
  23806. } else {
  23807. const valueEnd = targetValueSize - targetOffset * 2;
  23808. // Subtract each value for all other numeric track types
  23809. for ( let k = 0; k < valueEnd; ++ k ) {
  23810. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23811. }
  23812. }
  23813. }
  23814. }
  23815. targetClip.blendMode = AdditiveAnimationBlendMode;
  23816. return targetClip;
  23817. }
  23818. const AnimationUtils = {
  23819. convertArray: convertArray,
  23820. isTypedArray: isTypedArray,
  23821. getKeyframeOrder: getKeyframeOrder,
  23822. sortedArray: sortedArray,
  23823. flattenJSON: flattenJSON,
  23824. subclip: subclip,
  23825. makeClipAdditive: makeClipAdditive
  23826. };
  23827. /**
  23828. * Abstract base class of interpolants over parametric samples.
  23829. *
  23830. * The parameter domain is one dimensional, typically the time or a path
  23831. * along a curve defined by the data.
  23832. *
  23833. * The sample values can have any dimensionality and derived classes may
  23834. * apply special interpretations to the data.
  23835. *
  23836. * This class provides the interval seek in a Template Method, deferring
  23837. * the actual interpolation to derived classes.
  23838. *
  23839. * Time complexity is O(1) for linear access crossing at most two points
  23840. * and O(log N) for random access, where N is the number of positions.
  23841. *
  23842. * References:
  23843. *
  23844. * http://www.oodesign.com/template-method-pattern.html
  23845. *
  23846. */
  23847. class Interpolant {
  23848. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23849. this.parameterPositions = parameterPositions;
  23850. this._cachedIndex = 0;
  23851. this.resultBuffer = resultBuffer !== undefined ?
  23852. resultBuffer : new sampleValues.constructor( sampleSize );
  23853. this.sampleValues = sampleValues;
  23854. this.valueSize = sampleSize;
  23855. this.settings = null;
  23856. this.DefaultSettings_ = {};
  23857. }
  23858. evaluate( t ) {
  23859. const pp = this.parameterPositions;
  23860. let i1 = this._cachedIndex,
  23861. t1 = pp[ i1 ],
  23862. t0 = pp[ i1 - 1 ];
  23863. validate_interval: {
  23864. seek: {
  23865. let right;
  23866. linear_scan: {
  23867. //- See http://jsperf.com/comparison-to-undefined/3
  23868. //- slower code:
  23869. //-
  23870. //- if ( t >= t1 || t1 === undefined ) {
  23871. forward_scan: if ( ! ( t < t1 ) ) {
  23872. for ( let giveUpAt = i1 + 2; ; ) {
  23873. if ( t1 === undefined ) {
  23874. if ( t < t0 ) break forward_scan;
  23875. // after end
  23876. i1 = pp.length;
  23877. this._cachedIndex = i1;
  23878. return this.copySampleValue_( i1 - 1 );
  23879. }
  23880. if ( i1 === giveUpAt ) break; // this loop
  23881. t0 = t1;
  23882. t1 = pp[ ++ i1 ];
  23883. if ( t < t1 ) {
  23884. // we have arrived at the sought interval
  23885. break seek;
  23886. }
  23887. }
  23888. // prepare binary search on the right side of the index
  23889. right = pp.length;
  23890. break linear_scan;
  23891. }
  23892. //- slower code:
  23893. //- if ( t < t0 || t0 === undefined ) {
  23894. if ( ! ( t >= t0 ) ) {
  23895. // looping?
  23896. const t1global = pp[ 1 ];
  23897. if ( t < t1global ) {
  23898. i1 = 2; // + 1, using the scan for the details
  23899. t0 = t1global;
  23900. }
  23901. // linear reverse scan
  23902. for ( let giveUpAt = i1 - 2; ; ) {
  23903. if ( t0 === undefined ) {
  23904. // before start
  23905. this._cachedIndex = 0;
  23906. return this.copySampleValue_( 0 );
  23907. }
  23908. if ( i1 === giveUpAt ) break; // this loop
  23909. t1 = t0;
  23910. t0 = pp[ -- i1 - 1 ];
  23911. if ( t >= t0 ) {
  23912. // we have arrived at the sought interval
  23913. break seek;
  23914. }
  23915. }
  23916. // prepare binary search on the left side of the index
  23917. right = i1;
  23918. i1 = 0;
  23919. break linear_scan;
  23920. }
  23921. // the interval is valid
  23922. break validate_interval;
  23923. } // linear scan
  23924. // binary search
  23925. while ( i1 < right ) {
  23926. const mid = ( i1 + right ) >>> 1;
  23927. if ( t < pp[ mid ] ) {
  23928. right = mid;
  23929. } else {
  23930. i1 = mid + 1;
  23931. }
  23932. }
  23933. t1 = pp[ i1 ];
  23934. t0 = pp[ i1 - 1 ];
  23935. // check boundary cases, again
  23936. if ( t0 === undefined ) {
  23937. this._cachedIndex = 0;
  23938. return this.copySampleValue_( 0 );
  23939. }
  23940. if ( t1 === undefined ) {
  23941. i1 = pp.length;
  23942. this._cachedIndex = i1;
  23943. return this.copySampleValue_( i1 - 1 );
  23944. }
  23945. } // seek
  23946. this._cachedIndex = i1;
  23947. this.intervalChanged_( i1, t0, t1 );
  23948. } // validate_interval
  23949. return this.interpolate_( i1, t0, t, t1 );
  23950. }
  23951. getSettings_() {
  23952. return this.settings || this.DefaultSettings_;
  23953. }
  23954. copySampleValue_( index ) {
  23955. // copies a sample value to the result buffer
  23956. const result = this.resultBuffer,
  23957. values = this.sampleValues,
  23958. stride = this.valueSize,
  23959. offset = index * stride;
  23960. for ( let i = 0; i !== stride; ++ i ) {
  23961. result[ i ] = values[ offset + i ];
  23962. }
  23963. return result;
  23964. }
  23965. // Template methods for derived classes:
  23966. interpolate_( /* i1, t0, t, t1 */ ) {
  23967. throw new Error( 'call to abstract method' );
  23968. // implementations shall return this.resultBuffer
  23969. }
  23970. intervalChanged_( /* i1, t0, t1 */ ) {
  23971. // empty
  23972. }
  23973. }
  23974. /**
  23975. * Fast and simple cubic spline interpolant.
  23976. *
  23977. * It was derived from a Hermitian construction setting the first derivative
  23978. * at each sample position to the linear slope between neighboring positions
  23979. * over their parameter interval.
  23980. */
  23981. class CubicInterpolant extends Interpolant {
  23982. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23983. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23984. this._weightPrev = - 0;
  23985. this._offsetPrev = - 0;
  23986. this._weightNext = - 0;
  23987. this._offsetNext = - 0;
  23988. this.DefaultSettings_ = {
  23989. endingStart: ZeroCurvatureEnding,
  23990. endingEnd: ZeroCurvatureEnding
  23991. };
  23992. }
  23993. intervalChanged_( i1, t0, t1 ) {
  23994. const pp = this.parameterPositions;
  23995. let iPrev = i1 - 2,
  23996. iNext = i1 + 1,
  23997. tPrev = pp[ iPrev ],
  23998. tNext = pp[ iNext ];
  23999. if ( tPrev === undefined ) {
  24000. switch ( this.getSettings_().endingStart ) {
  24001. case ZeroSlopeEnding:
  24002. // f'(t0) = 0
  24003. iPrev = i1;
  24004. tPrev = 2 * t0 - t1;
  24005. break;
  24006. case WrapAroundEnding:
  24007. // use the other end of the curve
  24008. iPrev = pp.length - 2;
  24009. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24010. break;
  24011. default: // ZeroCurvatureEnding
  24012. // f''(t0) = 0 a.k.a. Natural Spline
  24013. iPrev = i1;
  24014. tPrev = t1;
  24015. }
  24016. }
  24017. if ( tNext === undefined ) {
  24018. switch ( this.getSettings_().endingEnd ) {
  24019. case ZeroSlopeEnding:
  24020. // f'(tN) = 0
  24021. iNext = i1;
  24022. tNext = 2 * t1 - t0;
  24023. break;
  24024. case WrapAroundEnding:
  24025. // use the other end of the curve
  24026. iNext = 1;
  24027. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24028. break;
  24029. default: // ZeroCurvatureEnding
  24030. // f''(tN) = 0, a.k.a. Natural Spline
  24031. iNext = i1 - 1;
  24032. tNext = t0;
  24033. }
  24034. }
  24035. const halfDt = ( t1 - t0 ) * 0.5,
  24036. stride = this.valueSize;
  24037. this._weightPrev = halfDt / ( t0 - tPrev );
  24038. this._weightNext = halfDt / ( tNext - t1 );
  24039. this._offsetPrev = iPrev * stride;
  24040. this._offsetNext = iNext * stride;
  24041. }
  24042. interpolate_( i1, t0, t, t1 ) {
  24043. const result = this.resultBuffer,
  24044. values = this.sampleValues,
  24045. stride = this.valueSize,
  24046. o1 = i1 * stride, o0 = o1 - stride,
  24047. oP = this._offsetPrev, oN = this._offsetNext,
  24048. wP = this._weightPrev, wN = this._weightNext,
  24049. p = ( t - t0 ) / ( t1 - t0 ),
  24050. pp = p * p,
  24051. ppp = pp * p;
  24052. // evaluate polynomials
  24053. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  24054. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24055. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24056. const sN = wN * ppp - wN * pp;
  24057. // combine data linearly
  24058. for ( let i = 0; i !== stride; ++ i ) {
  24059. result[ i ] =
  24060. sP * values[ oP + i ] +
  24061. s0 * values[ o0 + i ] +
  24062. s1 * values[ o1 + i ] +
  24063. sN * values[ oN + i ];
  24064. }
  24065. return result;
  24066. }
  24067. }
  24068. class LinearInterpolant extends Interpolant {
  24069. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24070. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24071. }
  24072. interpolate_( i1, t0, t, t1 ) {
  24073. const result = this.resultBuffer,
  24074. values = this.sampleValues,
  24075. stride = this.valueSize,
  24076. offset1 = i1 * stride,
  24077. offset0 = offset1 - stride,
  24078. weight1 = ( t - t0 ) / ( t1 - t0 ),
  24079. weight0 = 1 - weight1;
  24080. for ( let i = 0; i !== stride; ++ i ) {
  24081. result[ i ] =
  24082. values[ offset0 + i ] * weight0 +
  24083. values[ offset1 + i ] * weight1;
  24084. }
  24085. return result;
  24086. }
  24087. }
  24088. /**
  24089. *
  24090. * Interpolant that evaluates to the sample value at the position preceding
  24091. * the parameter.
  24092. */
  24093. class DiscreteInterpolant extends Interpolant {
  24094. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24095. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24096. }
  24097. interpolate_( i1 /*, t0, t, t1 */ ) {
  24098. return this.copySampleValue_( i1 - 1 );
  24099. }
  24100. }
  24101. class KeyframeTrack {
  24102. constructor( name, times, values, interpolation ) {
  24103. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  24104. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  24105. this.name = name;
  24106. this.times = convertArray( times, this.TimeBufferType );
  24107. this.values = convertArray( values, this.ValueBufferType );
  24108. this.setInterpolation( interpolation || this.DefaultInterpolation );
  24109. }
  24110. // Serialization (in static context, because of constructor invocation
  24111. // and automatic invocation of .toJSON):
  24112. static toJSON( track ) {
  24113. const trackType = track.constructor;
  24114. let json;
  24115. // derived classes can define a static toJSON method
  24116. if ( trackType.toJSON !== this.toJSON ) {
  24117. json = trackType.toJSON( track );
  24118. } else {
  24119. // by default, we assume the data can be serialized as-is
  24120. json = {
  24121. 'name': track.name,
  24122. 'times': convertArray( track.times, Array ),
  24123. 'values': convertArray( track.values, Array )
  24124. };
  24125. const interpolation = track.getInterpolation();
  24126. if ( interpolation !== track.DefaultInterpolation ) {
  24127. json.interpolation = interpolation;
  24128. }
  24129. }
  24130. json.type = track.ValueTypeName; // mandatory
  24131. return json;
  24132. }
  24133. InterpolantFactoryMethodDiscrete( result ) {
  24134. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  24135. }
  24136. InterpolantFactoryMethodLinear( result ) {
  24137. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24138. }
  24139. InterpolantFactoryMethodSmooth( result ) {
  24140. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  24141. }
  24142. setInterpolation( interpolation ) {
  24143. let factoryMethod;
  24144. switch ( interpolation ) {
  24145. case InterpolateDiscrete:
  24146. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  24147. break;
  24148. case InterpolateLinear:
  24149. factoryMethod = this.InterpolantFactoryMethodLinear;
  24150. break;
  24151. case InterpolateSmooth:
  24152. factoryMethod = this.InterpolantFactoryMethodSmooth;
  24153. break;
  24154. }
  24155. if ( factoryMethod === undefined ) {
  24156. const message = 'unsupported interpolation for ' +
  24157. this.ValueTypeName + ' keyframe track named ' + this.name;
  24158. if ( this.createInterpolant === undefined ) {
  24159. // fall back to default, unless the default itself is messed up
  24160. if ( interpolation !== this.DefaultInterpolation ) {
  24161. this.setInterpolation( this.DefaultInterpolation );
  24162. } else {
  24163. throw new Error( message ); // fatal, in this case
  24164. }
  24165. }
  24166. console.warn( 'THREE.KeyframeTrack:', message );
  24167. return this;
  24168. }
  24169. this.createInterpolant = factoryMethod;
  24170. return this;
  24171. }
  24172. getInterpolation() {
  24173. switch ( this.createInterpolant ) {
  24174. case this.InterpolantFactoryMethodDiscrete:
  24175. return InterpolateDiscrete;
  24176. case this.InterpolantFactoryMethodLinear:
  24177. return InterpolateLinear;
  24178. case this.InterpolantFactoryMethodSmooth:
  24179. return InterpolateSmooth;
  24180. }
  24181. }
  24182. getValueSize() {
  24183. return this.values.length / this.times.length;
  24184. }
  24185. // move all keyframes either forwards or backwards in time
  24186. shift( timeOffset ) {
  24187. if ( timeOffset !== 0.0 ) {
  24188. const times = this.times;
  24189. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24190. times[ i ] += timeOffset;
  24191. }
  24192. }
  24193. return this;
  24194. }
  24195. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  24196. scale( timeScale ) {
  24197. if ( timeScale !== 1.0 ) {
  24198. const times = this.times;
  24199. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24200. times[ i ] *= timeScale;
  24201. }
  24202. }
  24203. return this;
  24204. }
  24205. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  24206. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  24207. trim( startTime, endTime ) {
  24208. const times = this.times,
  24209. nKeys = times.length;
  24210. let from = 0,
  24211. to = nKeys - 1;
  24212. while ( from !== nKeys && times[ from ] < startTime ) {
  24213. ++ from;
  24214. }
  24215. while ( to !== - 1 && times[ to ] > endTime ) {
  24216. -- to;
  24217. }
  24218. ++ to; // inclusive -> exclusive bound
  24219. if ( from !== 0 || to !== nKeys ) {
  24220. // empty tracks are forbidden, so keep at least one keyframe
  24221. if ( from >= to ) {
  24222. to = Math.max( to, 1 );
  24223. from = to - 1;
  24224. }
  24225. const stride = this.getValueSize();
  24226. this.times = times.slice( from, to );
  24227. this.values = this.values.slice( from * stride, to * stride );
  24228. }
  24229. return this;
  24230. }
  24231. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  24232. validate() {
  24233. let valid = true;
  24234. const valueSize = this.getValueSize();
  24235. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  24236. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  24237. valid = false;
  24238. }
  24239. const times = this.times,
  24240. values = this.values,
  24241. nKeys = times.length;
  24242. if ( nKeys === 0 ) {
  24243. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  24244. valid = false;
  24245. }
  24246. let prevTime = null;
  24247. for ( let i = 0; i !== nKeys; i ++ ) {
  24248. const currTime = times[ i ];
  24249. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  24250. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  24251. valid = false;
  24252. break;
  24253. }
  24254. if ( prevTime !== null && prevTime > currTime ) {
  24255. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  24256. valid = false;
  24257. break;
  24258. }
  24259. prevTime = currTime;
  24260. }
  24261. if ( values !== undefined ) {
  24262. if ( isTypedArray( values ) ) {
  24263. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  24264. const value = values[ i ];
  24265. if ( isNaN( value ) ) {
  24266. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  24267. valid = false;
  24268. break;
  24269. }
  24270. }
  24271. }
  24272. }
  24273. return valid;
  24274. }
  24275. // removes equivalent sequential keys as common in morph target sequences
  24276. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  24277. optimize() {
  24278. // times or values may be shared with other tracks, so overwriting is unsafe
  24279. const times = this.times.slice(),
  24280. values = this.values.slice(),
  24281. stride = this.getValueSize(),
  24282. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  24283. lastIndex = times.length - 1;
  24284. let writeIndex = 1;
  24285. for ( let i = 1; i < lastIndex; ++ i ) {
  24286. let keep = false;
  24287. const time = times[ i ];
  24288. const timeNext = times[ i + 1 ];
  24289. // remove adjacent keyframes scheduled at the same time
  24290. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  24291. if ( ! smoothInterpolation ) {
  24292. // remove unnecessary keyframes same as their neighbors
  24293. const offset = i * stride,
  24294. offsetP = offset - stride,
  24295. offsetN = offset + stride;
  24296. for ( let j = 0; j !== stride; ++ j ) {
  24297. const value = values[ offset + j ];
  24298. if ( value !== values[ offsetP + j ] ||
  24299. value !== values[ offsetN + j ] ) {
  24300. keep = true;
  24301. break;
  24302. }
  24303. }
  24304. } else {
  24305. keep = true;
  24306. }
  24307. }
  24308. // in-place compaction
  24309. if ( keep ) {
  24310. if ( i !== writeIndex ) {
  24311. times[ writeIndex ] = times[ i ];
  24312. const readOffset = i * stride,
  24313. writeOffset = writeIndex * stride;
  24314. for ( let j = 0; j !== stride; ++ j ) {
  24315. values[ writeOffset + j ] = values[ readOffset + j ];
  24316. }
  24317. }
  24318. ++ writeIndex;
  24319. }
  24320. }
  24321. // flush last keyframe (compaction looks ahead)
  24322. if ( lastIndex > 0 ) {
  24323. times[ writeIndex ] = times[ lastIndex ];
  24324. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  24325. values[ writeOffset + j ] = values[ readOffset + j ];
  24326. }
  24327. ++ writeIndex;
  24328. }
  24329. if ( writeIndex !== times.length ) {
  24330. this.times = times.slice( 0, writeIndex );
  24331. this.values = values.slice( 0, writeIndex * stride );
  24332. } else {
  24333. this.times = times;
  24334. this.values = values;
  24335. }
  24336. return this;
  24337. }
  24338. clone() {
  24339. const times = this.times.slice();
  24340. const values = this.values.slice();
  24341. const TypedKeyframeTrack = this.constructor;
  24342. const track = new TypedKeyframeTrack( this.name, times, values );
  24343. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  24344. track.createInterpolant = this.createInterpolant;
  24345. return track;
  24346. }
  24347. }
  24348. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  24349. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  24350. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24351. /**
  24352. * A Track of Boolean keyframe values.
  24353. */
  24354. class BooleanKeyframeTrack extends KeyframeTrack {}
  24355. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  24356. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  24357. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24358. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24359. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24360. /**
  24361. * A Track of keyframe values that represent color.
  24362. */
  24363. class ColorKeyframeTrack extends KeyframeTrack {}
  24364. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  24365. /**
  24366. * A Track of numeric keyframe values.
  24367. */
  24368. class NumberKeyframeTrack extends KeyframeTrack {}
  24369. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  24370. /**
  24371. * Spherical linear unit quaternion interpolant.
  24372. */
  24373. class QuaternionLinearInterpolant extends Interpolant {
  24374. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24375. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24376. }
  24377. interpolate_( i1, t0, t, t1 ) {
  24378. const result = this.resultBuffer,
  24379. values = this.sampleValues,
  24380. stride = this.valueSize,
  24381. alpha = ( t - t0 ) / ( t1 - t0 );
  24382. let offset = i1 * stride;
  24383. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  24384. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24385. }
  24386. return result;
  24387. }
  24388. }
  24389. /**
  24390. * A Track of quaternion keyframe values.
  24391. */
  24392. class QuaternionKeyframeTrack extends KeyframeTrack {
  24393. InterpolantFactoryMethodLinear( result ) {
  24394. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24395. }
  24396. }
  24397. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  24398. // ValueBufferType is inherited
  24399. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24400. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24401. /**
  24402. * A Track that interpolates Strings
  24403. */
  24404. class StringKeyframeTrack extends KeyframeTrack {}
  24405. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  24406. StringKeyframeTrack.prototype.ValueBufferType = Array;
  24407. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24408. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24409. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24410. /**
  24411. * A Track of vectored keyframe values.
  24412. */
  24413. class VectorKeyframeTrack extends KeyframeTrack {}
  24414. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  24415. class AnimationClip {
  24416. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  24417. this.name = name;
  24418. this.tracks = tracks;
  24419. this.duration = duration;
  24420. this.blendMode = blendMode;
  24421. this.uuid = generateUUID();
  24422. // this means it should figure out its duration by scanning the tracks
  24423. if ( this.duration < 0 ) {
  24424. this.resetDuration();
  24425. }
  24426. }
  24427. static parse( json ) {
  24428. const tracks = [],
  24429. jsonTracks = json.tracks,
  24430. frameTime = 1.0 / ( json.fps || 1.0 );
  24431. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  24432. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  24433. }
  24434. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  24435. clip.uuid = json.uuid;
  24436. return clip;
  24437. }
  24438. static toJSON( clip ) {
  24439. const tracks = [],
  24440. clipTracks = clip.tracks;
  24441. const json = {
  24442. 'name': clip.name,
  24443. 'duration': clip.duration,
  24444. 'tracks': tracks,
  24445. 'uuid': clip.uuid,
  24446. 'blendMode': clip.blendMode
  24447. };
  24448. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  24449. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  24450. }
  24451. return json;
  24452. }
  24453. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  24454. const numMorphTargets = morphTargetSequence.length;
  24455. const tracks = [];
  24456. for ( let i = 0; i < numMorphTargets; i ++ ) {
  24457. let times = [];
  24458. let values = [];
  24459. times.push(
  24460. ( i + numMorphTargets - 1 ) % numMorphTargets,
  24461. i,
  24462. ( i + 1 ) % numMorphTargets );
  24463. values.push( 0, 1, 0 );
  24464. const order = getKeyframeOrder( times );
  24465. times = sortedArray( times, 1, order );
  24466. values = sortedArray( values, 1, order );
  24467. // if there is a key at the first frame, duplicate it as the
  24468. // last frame as well for perfect loop.
  24469. if ( ! noLoop && times[ 0 ] === 0 ) {
  24470. times.push( numMorphTargets );
  24471. values.push( values[ 0 ] );
  24472. }
  24473. tracks.push(
  24474. new NumberKeyframeTrack(
  24475. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  24476. times, values
  24477. ).scale( 1.0 / fps ) );
  24478. }
  24479. return new this( name, - 1, tracks );
  24480. }
  24481. static findByName( objectOrClipArray, name ) {
  24482. let clipArray = objectOrClipArray;
  24483. if ( ! Array.isArray( objectOrClipArray ) ) {
  24484. const o = objectOrClipArray;
  24485. clipArray = o.geometry && o.geometry.animations || o.animations;
  24486. }
  24487. for ( let i = 0; i < clipArray.length; i ++ ) {
  24488. if ( clipArray[ i ].name === name ) {
  24489. return clipArray[ i ];
  24490. }
  24491. }
  24492. return null;
  24493. }
  24494. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  24495. const animationToMorphTargets = {};
  24496. // tested with https://regex101.com/ on trick sequences
  24497. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24498. const pattern = /^([\w-]*?)([\d]+)$/;
  24499. // sort morph target names into animation groups based
  24500. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24501. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24502. const morphTarget = morphTargets[ i ];
  24503. const parts = morphTarget.name.match( pattern );
  24504. if ( parts && parts.length > 1 ) {
  24505. const name = parts[ 1 ];
  24506. let animationMorphTargets = animationToMorphTargets[ name ];
  24507. if ( ! animationMorphTargets ) {
  24508. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24509. }
  24510. animationMorphTargets.push( morphTarget );
  24511. }
  24512. }
  24513. const clips = [];
  24514. for ( const name in animationToMorphTargets ) {
  24515. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24516. }
  24517. return clips;
  24518. }
  24519. // parse the animation.hierarchy format
  24520. static parseAnimation( animation, bones ) {
  24521. if ( ! animation ) {
  24522. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24523. return null;
  24524. }
  24525. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24526. // only return track if there are actually keys.
  24527. if ( animationKeys.length !== 0 ) {
  24528. const times = [];
  24529. const values = [];
  24530. flattenJSON( animationKeys, times, values, propertyName );
  24531. // empty keys are filtered out, so check again
  24532. if ( times.length !== 0 ) {
  24533. destTracks.push( new trackType( trackName, times, values ) );
  24534. }
  24535. }
  24536. };
  24537. const tracks = [];
  24538. const clipName = animation.name || 'default';
  24539. const fps = animation.fps || 30;
  24540. const blendMode = animation.blendMode;
  24541. // automatic length determination in AnimationClip.
  24542. let duration = animation.length || - 1;
  24543. const hierarchyTracks = animation.hierarchy || [];
  24544. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24545. const animationKeys = hierarchyTracks[ h ].keys;
  24546. // skip empty tracks
  24547. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24548. // process morph targets
  24549. if ( animationKeys[ 0 ].morphTargets ) {
  24550. // figure out all morph targets used in this track
  24551. const morphTargetNames = {};
  24552. let k;
  24553. for ( k = 0; k < animationKeys.length; k ++ ) {
  24554. if ( animationKeys[ k ].morphTargets ) {
  24555. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24556. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  24557. }
  24558. }
  24559. }
  24560. // create a track for each morph target with all zero
  24561. // morphTargetInfluences except for the keys in which
  24562. // the morphTarget is named.
  24563. for ( const morphTargetName in morphTargetNames ) {
  24564. const times = [];
  24565. const values = [];
  24566. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24567. const animationKey = animationKeys[ k ];
  24568. times.push( animationKey.time );
  24569. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24570. }
  24571. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24572. }
  24573. duration = morphTargetNames.length * fps;
  24574. } else {
  24575. // ...assume skeletal animation
  24576. const boneName = '.bones[' + bones[ h ].name + ']';
  24577. addNonemptyTrack(
  24578. VectorKeyframeTrack, boneName + '.position',
  24579. animationKeys, 'pos', tracks );
  24580. addNonemptyTrack(
  24581. QuaternionKeyframeTrack, boneName + '.quaternion',
  24582. animationKeys, 'rot', tracks );
  24583. addNonemptyTrack(
  24584. VectorKeyframeTrack, boneName + '.scale',
  24585. animationKeys, 'scl', tracks );
  24586. }
  24587. }
  24588. if ( tracks.length === 0 ) {
  24589. return null;
  24590. }
  24591. const clip = new this( clipName, duration, tracks, blendMode );
  24592. return clip;
  24593. }
  24594. resetDuration() {
  24595. const tracks = this.tracks;
  24596. let duration = 0;
  24597. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24598. const track = this.tracks[ i ];
  24599. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24600. }
  24601. this.duration = duration;
  24602. return this;
  24603. }
  24604. trim() {
  24605. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24606. this.tracks[ i ].trim( 0, this.duration );
  24607. }
  24608. return this;
  24609. }
  24610. validate() {
  24611. let valid = true;
  24612. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24613. valid = valid && this.tracks[ i ].validate();
  24614. }
  24615. return valid;
  24616. }
  24617. optimize() {
  24618. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24619. this.tracks[ i ].optimize();
  24620. }
  24621. return this;
  24622. }
  24623. clone() {
  24624. const tracks = [];
  24625. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24626. tracks.push( this.tracks[ i ].clone() );
  24627. }
  24628. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24629. }
  24630. toJSON() {
  24631. return this.constructor.toJSON( this );
  24632. }
  24633. }
  24634. function getTrackTypeForValueTypeName( typeName ) {
  24635. switch ( typeName.toLowerCase() ) {
  24636. case 'scalar':
  24637. case 'double':
  24638. case 'float':
  24639. case 'number':
  24640. case 'integer':
  24641. return NumberKeyframeTrack;
  24642. case 'vector':
  24643. case 'vector2':
  24644. case 'vector3':
  24645. case 'vector4':
  24646. return VectorKeyframeTrack;
  24647. case 'color':
  24648. return ColorKeyframeTrack;
  24649. case 'quaternion':
  24650. return QuaternionKeyframeTrack;
  24651. case 'bool':
  24652. case 'boolean':
  24653. return BooleanKeyframeTrack;
  24654. case 'string':
  24655. return StringKeyframeTrack;
  24656. }
  24657. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24658. }
  24659. function parseKeyframeTrack( json ) {
  24660. if ( json.type === undefined ) {
  24661. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24662. }
  24663. const trackType = getTrackTypeForValueTypeName( json.type );
  24664. if ( json.times === undefined ) {
  24665. const times = [], values = [];
  24666. flattenJSON( json.keys, times, values, 'value' );
  24667. json.times = times;
  24668. json.values = values;
  24669. }
  24670. // derived classes can define a static parse method
  24671. if ( trackType.parse !== undefined ) {
  24672. return trackType.parse( json );
  24673. } else {
  24674. // by default, we assume a constructor compatible with the base
  24675. return new trackType( json.name, json.times, json.values, json.interpolation );
  24676. }
  24677. }
  24678. const Cache = {
  24679. enabled: false,
  24680. files: {},
  24681. add: function ( key, file ) {
  24682. if ( this.enabled === false ) return;
  24683. // console.log( 'THREE.Cache', 'Adding key:', key );
  24684. this.files[ key ] = file;
  24685. },
  24686. get: function ( key ) {
  24687. if ( this.enabled === false ) return;
  24688. // console.log( 'THREE.Cache', 'Checking key:', key );
  24689. return this.files[ key ];
  24690. },
  24691. remove: function ( key ) {
  24692. delete this.files[ key ];
  24693. },
  24694. clear: function () {
  24695. this.files = {};
  24696. }
  24697. };
  24698. class LoadingManager {
  24699. constructor( onLoad, onProgress, onError ) {
  24700. const scope = this;
  24701. let isLoading = false;
  24702. let itemsLoaded = 0;
  24703. let itemsTotal = 0;
  24704. let urlModifier = undefined;
  24705. const handlers = [];
  24706. // Refer to #5689 for the reason why we don't set .onStart
  24707. // in the constructor
  24708. this.onStart = undefined;
  24709. this.onLoad = onLoad;
  24710. this.onProgress = onProgress;
  24711. this.onError = onError;
  24712. this.itemStart = function ( url ) {
  24713. itemsTotal ++;
  24714. if ( isLoading === false ) {
  24715. if ( scope.onStart !== undefined ) {
  24716. scope.onStart( url, itemsLoaded, itemsTotal );
  24717. }
  24718. }
  24719. isLoading = true;
  24720. };
  24721. this.itemEnd = function ( url ) {
  24722. itemsLoaded ++;
  24723. if ( scope.onProgress !== undefined ) {
  24724. scope.onProgress( url, itemsLoaded, itemsTotal );
  24725. }
  24726. if ( itemsLoaded === itemsTotal ) {
  24727. isLoading = false;
  24728. if ( scope.onLoad !== undefined ) {
  24729. scope.onLoad();
  24730. }
  24731. }
  24732. };
  24733. this.itemError = function ( url ) {
  24734. if ( scope.onError !== undefined ) {
  24735. scope.onError( url );
  24736. }
  24737. };
  24738. this.resolveURL = function ( url ) {
  24739. if ( urlModifier ) {
  24740. return urlModifier( url );
  24741. }
  24742. return url;
  24743. };
  24744. this.setURLModifier = function ( transform ) {
  24745. urlModifier = transform;
  24746. return this;
  24747. };
  24748. this.addHandler = function ( regex, loader ) {
  24749. handlers.push( regex, loader );
  24750. return this;
  24751. };
  24752. this.removeHandler = function ( regex ) {
  24753. const index = handlers.indexOf( regex );
  24754. if ( index !== - 1 ) {
  24755. handlers.splice( index, 2 );
  24756. }
  24757. return this;
  24758. };
  24759. this.getHandler = function ( file ) {
  24760. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24761. const regex = handlers[ i ];
  24762. const loader = handlers[ i + 1 ];
  24763. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24764. if ( regex.test( file ) ) {
  24765. return loader;
  24766. }
  24767. }
  24768. return null;
  24769. };
  24770. }
  24771. }
  24772. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24773. class Loader {
  24774. constructor( manager ) {
  24775. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24776. this.crossOrigin = 'anonymous';
  24777. this.withCredentials = false;
  24778. this.path = '';
  24779. this.resourcePath = '';
  24780. this.requestHeader = {};
  24781. }
  24782. load( /* url, onLoad, onProgress, onError */ ) {}
  24783. loadAsync( url, onProgress ) {
  24784. const scope = this;
  24785. return new Promise( function ( resolve, reject ) {
  24786. scope.load( url, resolve, onProgress, reject );
  24787. } );
  24788. }
  24789. parse( /* data */ ) {}
  24790. setCrossOrigin( crossOrigin ) {
  24791. this.crossOrigin = crossOrigin;
  24792. return this;
  24793. }
  24794. setWithCredentials( value ) {
  24795. this.withCredentials = value;
  24796. return this;
  24797. }
  24798. setPath( path ) {
  24799. this.path = path;
  24800. return this;
  24801. }
  24802. setResourcePath( resourcePath ) {
  24803. this.resourcePath = resourcePath;
  24804. return this;
  24805. }
  24806. setRequestHeader( requestHeader ) {
  24807. this.requestHeader = requestHeader;
  24808. return this;
  24809. }
  24810. }
  24811. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  24812. const loading = {};
  24813. class HttpError extends Error {
  24814. constructor( message, response ) {
  24815. super( message );
  24816. this.response = response;
  24817. }
  24818. }
  24819. class FileLoader extends Loader {
  24820. constructor( manager ) {
  24821. super( manager );
  24822. }
  24823. load( url, onLoad, onProgress, onError ) {
  24824. if ( url === undefined ) url = '';
  24825. if ( this.path !== undefined ) url = this.path + url;
  24826. url = this.manager.resolveURL( url );
  24827. const cached = Cache.get( url );
  24828. if ( cached !== undefined ) {
  24829. this.manager.itemStart( url );
  24830. setTimeout( () => {
  24831. if ( onLoad ) onLoad( cached );
  24832. this.manager.itemEnd( url );
  24833. }, 0 );
  24834. return cached;
  24835. }
  24836. // Check if request is duplicate
  24837. if ( loading[ url ] !== undefined ) {
  24838. loading[ url ].push( {
  24839. onLoad: onLoad,
  24840. onProgress: onProgress,
  24841. onError: onError
  24842. } );
  24843. return;
  24844. }
  24845. // Initialise array for duplicate requests
  24846. loading[ url ] = [];
  24847. loading[ url ].push( {
  24848. onLoad: onLoad,
  24849. onProgress: onProgress,
  24850. onError: onError,
  24851. } );
  24852. // create request
  24853. const req = new Request( url, {
  24854. headers: new Headers( this.requestHeader ),
  24855. credentials: this.withCredentials ? 'include' : 'same-origin',
  24856. // An abort controller could be added within a future PR
  24857. } );
  24858. // record states ( avoid data race )
  24859. const mimeType = this.mimeType;
  24860. const responseType = this.responseType;
  24861. // start the fetch
  24862. fetch( req )
  24863. .then( response => {
  24864. if ( response.status === 200 || response.status === 0 ) {
  24865. // Some browsers return HTTP Status 0 when using non-http protocol
  24866. // e.g. 'file://' or 'data://'. Handle as success.
  24867. if ( response.status === 0 ) {
  24868. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24869. }
  24870. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24871. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24872. return response;
  24873. }
  24874. const callbacks = loading[ url ];
  24875. const reader = response.body.getReader();
  24876. // Nginx needs X-File-Size check
  24877. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24878. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24879. const total = contentLength ? parseInt( contentLength ) : 0;
  24880. const lengthComputable = total !== 0;
  24881. let loaded = 0;
  24882. // periodically read data into the new stream tracking while download progress
  24883. const stream = new ReadableStream( {
  24884. start( controller ) {
  24885. readData();
  24886. function readData() {
  24887. reader.read().then( ( { done, value } ) => {
  24888. if ( done ) {
  24889. controller.close();
  24890. } else {
  24891. loaded += value.byteLength;
  24892. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24893. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24894. const callback = callbacks[ i ];
  24895. if ( callback.onProgress ) callback.onProgress( event );
  24896. }
  24897. controller.enqueue( value );
  24898. readData();
  24899. }
  24900. } );
  24901. }
  24902. }
  24903. } );
  24904. return new Response( stream );
  24905. } else {
  24906. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24907. }
  24908. } )
  24909. .then( response => {
  24910. switch ( responseType ) {
  24911. case 'arraybuffer':
  24912. return response.arrayBuffer();
  24913. case 'blob':
  24914. return response.blob();
  24915. case 'document':
  24916. return response.text()
  24917. .then( text => {
  24918. const parser = new DOMParser();
  24919. return parser.parseFromString( text, mimeType );
  24920. } );
  24921. case 'json':
  24922. return response.json();
  24923. default:
  24924. if ( mimeType === undefined ) {
  24925. return response.text();
  24926. } else {
  24927. // sniff encoding
  24928. const re = /charset="?([^;"\s]*)"?/i;
  24929. const exec = re.exec( mimeType );
  24930. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24931. const decoder = new TextDecoder( label );
  24932. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24933. }
  24934. }
  24935. } )
  24936. .then( data => {
  24937. // Add to cache only on HTTP success, so that we do not cache
  24938. // error response bodies as proper responses to requests.
  24939. Cache.add( url, data );
  24940. const callbacks = loading[ url ];
  24941. delete loading[ url ];
  24942. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24943. const callback = callbacks[ i ];
  24944. if ( callback.onLoad ) callback.onLoad( data );
  24945. }
  24946. } )
  24947. .catch( err => {
  24948. // Abort errors and other errors are handled the same
  24949. const callbacks = loading[ url ];
  24950. if ( callbacks === undefined ) {
  24951. // When onLoad was called and url was deleted in `loading`
  24952. this.manager.itemError( url );
  24953. throw err;
  24954. }
  24955. delete loading[ url ];
  24956. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24957. const callback = callbacks[ i ];
  24958. if ( callback.onError ) callback.onError( err );
  24959. }
  24960. this.manager.itemError( url );
  24961. } )
  24962. .finally( () => {
  24963. this.manager.itemEnd( url );
  24964. } );
  24965. this.manager.itemStart( url );
  24966. }
  24967. setResponseType( value ) {
  24968. this.responseType = value;
  24969. return this;
  24970. }
  24971. setMimeType( value ) {
  24972. this.mimeType = value;
  24973. return this;
  24974. }
  24975. }
  24976. class AnimationLoader extends Loader {
  24977. constructor( manager ) {
  24978. super( manager );
  24979. }
  24980. load( url, onLoad, onProgress, onError ) {
  24981. const scope = this;
  24982. const loader = new FileLoader( this.manager );
  24983. loader.setPath( this.path );
  24984. loader.setRequestHeader( this.requestHeader );
  24985. loader.setWithCredentials( this.withCredentials );
  24986. loader.load( url, function ( text ) {
  24987. try {
  24988. onLoad( scope.parse( JSON.parse( text ) ) );
  24989. } catch ( e ) {
  24990. if ( onError ) {
  24991. onError( e );
  24992. } else {
  24993. console.error( e );
  24994. }
  24995. scope.manager.itemError( url );
  24996. }
  24997. }, onProgress, onError );
  24998. }
  24999. parse( json ) {
  25000. const animations = [];
  25001. for ( let i = 0; i < json.length; i ++ ) {
  25002. const clip = AnimationClip.parse( json[ i ] );
  25003. animations.push( clip );
  25004. }
  25005. return animations;
  25006. }
  25007. }
  25008. /**
  25009. * Abstract Base class to block based textures loader (dds, pvr, ...)
  25010. *
  25011. * Sub classes have to implement the parse() method which will be used in load().
  25012. */
  25013. class CompressedTextureLoader extends Loader {
  25014. constructor( manager ) {
  25015. super( manager );
  25016. }
  25017. load( url, onLoad, onProgress, onError ) {
  25018. const scope = this;
  25019. const images = [];
  25020. const texture = new CompressedTexture();
  25021. const loader = new FileLoader( this.manager );
  25022. loader.setPath( this.path );
  25023. loader.setResponseType( 'arraybuffer' );
  25024. loader.setRequestHeader( this.requestHeader );
  25025. loader.setWithCredentials( scope.withCredentials );
  25026. let loaded = 0;
  25027. function loadTexture( i ) {
  25028. loader.load( url[ i ], function ( buffer ) {
  25029. const texDatas = scope.parse( buffer, true );
  25030. images[ i ] = {
  25031. width: texDatas.width,
  25032. height: texDatas.height,
  25033. format: texDatas.format,
  25034. mipmaps: texDatas.mipmaps
  25035. };
  25036. loaded += 1;
  25037. if ( loaded === 6 ) {
  25038. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  25039. texture.image = images;
  25040. texture.format = texDatas.format;
  25041. texture.needsUpdate = true;
  25042. if ( onLoad ) onLoad( texture );
  25043. }
  25044. }, onProgress, onError );
  25045. }
  25046. if ( Array.isArray( url ) ) {
  25047. for ( let i = 0, il = url.length; i < il; ++ i ) {
  25048. loadTexture( i );
  25049. }
  25050. } else {
  25051. // compressed cubemap texture stored in a single DDS file
  25052. loader.load( url, function ( buffer ) {
  25053. const texDatas = scope.parse( buffer, true );
  25054. if ( texDatas.isCubemap ) {
  25055. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  25056. for ( let f = 0; f < faces; f ++ ) {
  25057. images[ f ] = { mipmaps: [] };
  25058. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  25059. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  25060. images[ f ].format = texDatas.format;
  25061. images[ f ].width = texDatas.width;
  25062. images[ f ].height = texDatas.height;
  25063. }
  25064. }
  25065. texture.image = images;
  25066. } else {
  25067. texture.image.width = texDatas.width;
  25068. texture.image.height = texDatas.height;
  25069. texture.mipmaps = texDatas.mipmaps;
  25070. }
  25071. if ( texDatas.mipmapCount === 1 ) {
  25072. texture.minFilter = LinearFilter;
  25073. }
  25074. texture.format = texDatas.format;
  25075. texture.needsUpdate = true;
  25076. if ( onLoad ) onLoad( texture );
  25077. }, onProgress, onError );
  25078. }
  25079. return texture;
  25080. }
  25081. }
  25082. class ImageLoader extends Loader {
  25083. constructor( manager ) {
  25084. super( manager );
  25085. }
  25086. load( url, onLoad, onProgress, onError ) {
  25087. if ( this.path !== undefined ) url = this.path + url;
  25088. url = this.manager.resolveURL( url );
  25089. const scope = this;
  25090. const cached = Cache.get( url );
  25091. if ( cached !== undefined ) {
  25092. scope.manager.itemStart( url );
  25093. setTimeout( function () {
  25094. if ( onLoad ) onLoad( cached );
  25095. scope.manager.itemEnd( url );
  25096. }, 0 );
  25097. return cached;
  25098. }
  25099. const image = createElementNS( 'img' );
  25100. function onImageLoad() {
  25101. removeEventListeners();
  25102. Cache.add( url, this );
  25103. if ( onLoad ) onLoad( this );
  25104. scope.manager.itemEnd( url );
  25105. }
  25106. function onImageError( event ) {
  25107. removeEventListeners();
  25108. if ( onError ) onError( event );
  25109. scope.manager.itemError( url );
  25110. scope.manager.itemEnd( url );
  25111. }
  25112. function removeEventListeners() {
  25113. image.removeEventListener( 'load', onImageLoad, false );
  25114. image.removeEventListener( 'error', onImageError, false );
  25115. }
  25116. image.addEventListener( 'load', onImageLoad, false );
  25117. image.addEventListener( 'error', onImageError, false );
  25118. if ( url.slice( 0, 5 ) !== 'data:' ) {
  25119. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  25120. }
  25121. scope.manager.itemStart( url );
  25122. image.src = url;
  25123. return image;
  25124. }
  25125. }
  25126. class CubeTextureLoader extends Loader {
  25127. constructor( manager ) {
  25128. super( manager );
  25129. }
  25130. load( urls, onLoad, onProgress, onError ) {
  25131. const texture = new CubeTexture();
  25132. texture.colorSpace = SRGBColorSpace;
  25133. const loader = new ImageLoader( this.manager );
  25134. loader.setCrossOrigin( this.crossOrigin );
  25135. loader.setPath( this.path );
  25136. let loaded = 0;
  25137. function loadTexture( i ) {
  25138. loader.load( urls[ i ], function ( image ) {
  25139. texture.images[ i ] = image;
  25140. loaded ++;
  25141. if ( loaded === 6 ) {
  25142. texture.needsUpdate = true;
  25143. if ( onLoad ) onLoad( texture );
  25144. }
  25145. }, undefined, onError );
  25146. }
  25147. for ( let i = 0; i < urls.length; ++ i ) {
  25148. loadTexture( i );
  25149. }
  25150. return texture;
  25151. }
  25152. }
  25153. /**
  25154. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25155. *
  25156. * Sub classes have to implement the parse() method which will be used in load().
  25157. */
  25158. class DataTextureLoader extends Loader {
  25159. constructor( manager ) {
  25160. super( manager );
  25161. }
  25162. load( url, onLoad, onProgress, onError ) {
  25163. const scope = this;
  25164. const texture = new DataTexture();
  25165. const loader = new FileLoader( this.manager );
  25166. loader.setResponseType( 'arraybuffer' );
  25167. loader.setRequestHeader( this.requestHeader );
  25168. loader.setPath( this.path );
  25169. loader.setWithCredentials( scope.withCredentials );
  25170. loader.load( url, function ( buffer ) {
  25171. let texData;
  25172. try {
  25173. texData = scope.parse( buffer );
  25174. } catch ( error ) {
  25175. if ( onError !== undefined ) {
  25176. onError( error );
  25177. } else {
  25178. console.error( error );
  25179. return;
  25180. }
  25181. }
  25182. if ( texData.image !== undefined ) {
  25183. texture.image = texData.image;
  25184. } else if ( texData.data !== undefined ) {
  25185. texture.image.width = texData.width;
  25186. texture.image.height = texData.height;
  25187. texture.image.data = texData.data;
  25188. }
  25189. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25190. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25191. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25192. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  25193. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25194. if ( texData.colorSpace !== undefined ) {
  25195. texture.colorSpace = texData.colorSpace;
  25196. } else if ( texData.encoding !== undefined ) { // @deprecated, r152
  25197. texture.encoding = texData.encoding;
  25198. }
  25199. if ( texData.flipY !== undefined ) {
  25200. texture.flipY = texData.flipY;
  25201. }
  25202. if ( texData.format !== undefined ) {
  25203. texture.format = texData.format;
  25204. }
  25205. if ( texData.type !== undefined ) {
  25206. texture.type = texData.type;
  25207. }
  25208. if ( texData.mipmaps !== undefined ) {
  25209. texture.mipmaps = texData.mipmaps;
  25210. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  25211. }
  25212. if ( texData.mipmapCount === 1 ) {
  25213. texture.minFilter = LinearFilter;
  25214. }
  25215. if ( texData.generateMipmaps !== undefined ) {
  25216. texture.generateMipmaps = texData.generateMipmaps;
  25217. }
  25218. texture.needsUpdate = true;
  25219. if ( onLoad ) onLoad( texture, texData );
  25220. }, onProgress, onError );
  25221. return texture;
  25222. }
  25223. }
  25224. class TextureLoader extends Loader {
  25225. constructor( manager ) {
  25226. super( manager );
  25227. }
  25228. load( url, onLoad, onProgress, onError ) {
  25229. const texture = new Texture();
  25230. const loader = new ImageLoader( this.manager );
  25231. loader.setCrossOrigin( this.crossOrigin );
  25232. loader.setPath( this.path );
  25233. loader.load( url, function ( image ) {
  25234. texture.image = image;
  25235. texture.needsUpdate = true;
  25236. if ( onLoad !== undefined ) {
  25237. onLoad( texture );
  25238. }
  25239. }, onProgress, onError );
  25240. return texture;
  25241. }
  25242. }
  25243. class Light extends Object3D {
  25244. constructor( color, intensity = 1 ) {
  25245. super();
  25246. this.isLight = true;
  25247. this.type = 'Light';
  25248. this.color = new Color( color );
  25249. this.intensity = intensity;
  25250. }
  25251. dispose() {
  25252. // Empty here in base class; some subclasses override.
  25253. }
  25254. copy( source, recursive ) {
  25255. super.copy( source, recursive );
  25256. this.color.copy( source.color );
  25257. this.intensity = source.intensity;
  25258. return this;
  25259. }
  25260. toJSON( meta ) {
  25261. const data = super.toJSON( meta );
  25262. data.object.color = this.color.getHex();
  25263. data.object.intensity = this.intensity;
  25264. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  25265. if ( this.distance !== undefined ) data.object.distance = this.distance;
  25266. if ( this.angle !== undefined ) data.object.angle = this.angle;
  25267. if ( this.decay !== undefined ) data.object.decay = this.decay;
  25268. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  25269. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  25270. return data;
  25271. }
  25272. }
  25273. class HemisphereLight extends Light {
  25274. constructor( skyColor, groundColor, intensity ) {
  25275. super( skyColor, intensity );
  25276. this.isHemisphereLight = true;
  25277. this.type = 'HemisphereLight';
  25278. this.position.copy( Object3D.DEFAULT_UP );
  25279. this.updateMatrix();
  25280. this.groundColor = new Color( groundColor );
  25281. }
  25282. copy( source, recursive ) {
  25283. super.copy( source, recursive );
  25284. this.groundColor.copy( source.groundColor );
  25285. return this;
  25286. }
  25287. }
  25288. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  25289. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  25290. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  25291. class LightShadow {
  25292. constructor( camera ) {
  25293. this.camera = camera;
  25294. this.bias = 0;
  25295. this.normalBias = 0;
  25296. this.radius = 1;
  25297. this.blurSamples = 8;
  25298. this.mapSize = new Vector2( 512, 512 );
  25299. this.map = null;
  25300. this.mapPass = null;
  25301. this.matrix = new Matrix4();
  25302. this.autoUpdate = true;
  25303. this.needsUpdate = false;
  25304. this._frustum = new Frustum();
  25305. this._frameExtents = new Vector2( 1, 1 );
  25306. this._viewportCount = 1;
  25307. this._viewports = [
  25308. new Vector4( 0, 0, 1, 1 )
  25309. ];
  25310. }
  25311. getViewportCount() {
  25312. return this._viewportCount;
  25313. }
  25314. getFrustum() {
  25315. return this._frustum;
  25316. }
  25317. updateMatrices( light ) {
  25318. const shadowCamera = this.camera;
  25319. const shadowMatrix = this.matrix;
  25320. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  25321. shadowCamera.position.copy( _lightPositionWorld$1 );
  25322. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  25323. shadowCamera.lookAt( _lookTarget$1 );
  25324. shadowCamera.updateMatrixWorld();
  25325. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  25326. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  25327. shadowMatrix.set(
  25328. 0.5, 0.0, 0.0, 0.5,
  25329. 0.0, 0.5, 0.0, 0.5,
  25330. 0.0, 0.0, 0.5, 0.5,
  25331. 0.0, 0.0, 0.0, 1.0
  25332. );
  25333. shadowMatrix.multiply( _projScreenMatrix$1 );
  25334. }
  25335. getViewport( viewportIndex ) {
  25336. return this._viewports[ viewportIndex ];
  25337. }
  25338. getFrameExtents() {
  25339. return this._frameExtents;
  25340. }
  25341. dispose() {
  25342. if ( this.map ) {
  25343. this.map.dispose();
  25344. }
  25345. if ( this.mapPass ) {
  25346. this.mapPass.dispose();
  25347. }
  25348. }
  25349. copy( source ) {
  25350. this.camera = source.camera.clone();
  25351. this.bias = source.bias;
  25352. this.radius = source.radius;
  25353. this.mapSize.copy( source.mapSize );
  25354. return this;
  25355. }
  25356. clone() {
  25357. return new this.constructor().copy( this );
  25358. }
  25359. toJSON() {
  25360. const object = {};
  25361. if ( this.bias !== 0 ) object.bias = this.bias;
  25362. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  25363. if ( this.radius !== 1 ) object.radius = this.radius;
  25364. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  25365. object.camera = this.camera.toJSON( false ).object;
  25366. delete object.camera.matrix;
  25367. return object;
  25368. }
  25369. }
  25370. class SpotLightShadow extends LightShadow {
  25371. constructor() {
  25372. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  25373. this.isSpotLightShadow = true;
  25374. this.focus = 1;
  25375. }
  25376. updateMatrices( light ) {
  25377. const camera = this.camera;
  25378. const fov = RAD2DEG * 2 * light.angle * this.focus;
  25379. const aspect = this.mapSize.width / this.mapSize.height;
  25380. const far = light.distance || camera.far;
  25381. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  25382. camera.fov = fov;
  25383. camera.aspect = aspect;
  25384. camera.far = far;
  25385. camera.updateProjectionMatrix();
  25386. }
  25387. super.updateMatrices( light );
  25388. }
  25389. copy( source ) {
  25390. super.copy( source );
  25391. this.focus = source.focus;
  25392. return this;
  25393. }
  25394. }
  25395. class SpotLight extends Light {
  25396. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  25397. super( color, intensity );
  25398. this.isSpotLight = true;
  25399. this.type = 'SpotLight';
  25400. this.position.copy( Object3D.DEFAULT_UP );
  25401. this.updateMatrix();
  25402. this.target = new Object3D();
  25403. this.distance = distance;
  25404. this.angle = angle;
  25405. this.penumbra = penumbra;
  25406. this.decay = decay;
  25407. this.map = null;
  25408. this.shadow = new SpotLightShadow();
  25409. }
  25410. get power() {
  25411. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25412. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  25413. return this.intensity * Math.PI;
  25414. }
  25415. set power( power ) {
  25416. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25417. this.intensity = power / Math.PI;
  25418. }
  25419. dispose() {
  25420. this.shadow.dispose();
  25421. }
  25422. copy( source, recursive ) {
  25423. super.copy( source, recursive );
  25424. this.distance = source.distance;
  25425. this.angle = source.angle;
  25426. this.penumbra = source.penumbra;
  25427. this.decay = source.decay;
  25428. this.target = source.target.clone();
  25429. this.shadow = source.shadow.clone();
  25430. return this;
  25431. }
  25432. }
  25433. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  25434. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  25435. const _lookTarget = /*@__PURE__*/ new Vector3();
  25436. class PointLightShadow extends LightShadow {
  25437. constructor() {
  25438. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25439. this.isPointLightShadow = true;
  25440. this._frameExtents = new Vector2( 4, 2 );
  25441. this._viewportCount = 6;
  25442. this._viewports = [
  25443. // These viewports map a cube-map onto a 2D texture with the
  25444. // following orientation:
  25445. //
  25446. // xzXZ
  25447. // y Y
  25448. //
  25449. // X - Positive x direction
  25450. // x - Negative x direction
  25451. // Y - Positive y direction
  25452. // y - Negative y direction
  25453. // Z - Positive z direction
  25454. // z - Negative z direction
  25455. // positive X
  25456. new Vector4( 2, 1, 1, 1 ),
  25457. // negative X
  25458. new Vector4( 0, 1, 1, 1 ),
  25459. // positive Z
  25460. new Vector4( 3, 1, 1, 1 ),
  25461. // negative Z
  25462. new Vector4( 1, 1, 1, 1 ),
  25463. // positive Y
  25464. new Vector4( 3, 0, 1, 1 ),
  25465. // negative Y
  25466. new Vector4( 1, 0, 1, 1 )
  25467. ];
  25468. this._cubeDirections = [
  25469. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  25470. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  25471. ];
  25472. this._cubeUps = [
  25473. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  25474. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  25475. ];
  25476. }
  25477. updateMatrices( light, viewportIndex = 0 ) {
  25478. const camera = this.camera;
  25479. const shadowMatrix = this.matrix;
  25480. const far = light.distance || camera.far;
  25481. if ( far !== camera.far ) {
  25482. camera.far = far;
  25483. camera.updateProjectionMatrix();
  25484. }
  25485. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  25486. camera.position.copy( _lightPositionWorld );
  25487. _lookTarget.copy( camera.position );
  25488. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  25489. camera.up.copy( this._cubeUps[ viewportIndex ] );
  25490. camera.lookAt( _lookTarget );
  25491. camera.updateMatrixWorld();
  25492. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  25493. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  25494. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  25495. }
  25496. }
  25497. class PointLight extends Light {
  25498. constructor( color, intensity, distance = 0, decay = 2 ) {
  25499. super( color, intensity );
  25500. this.isPointLight = true;
  25501. this.type = 'PointLight';
  25502. this.distance = distance;
  25503. this.decay = decay;
  25504. this.shadow = new PointLightShadow();
  25505. }
  25506. get power() {
  25507. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25508. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25509. return this.intensity * 4 * Math.PI;
  25510. }
  25511. set power( power ) {
  25512. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25513. this.intensity = power / ( 4 * Math.PI );
  25514. }
  25515. dispose() {
  25516. this.shadow.dispose();
  25517. }
  25518. copy( source, recursive ) {
  25519. super.copy( source, recursive );
  25520. this.distance = source.distance;
  25521. this.decay = source.decay;
  25522. this.shadow = source.shadow.clone();
  25523. return this;
  25524. }
  25525. }
  25526. class DirectionalLightShadow extends LightShadow {
  25527. constructor() {
  25528. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25529. this.isDirectionalLightShadow = true;
  25530. }
  25531. }
  25532. class DirectionalLight extends Light {
  25533. constructor( color, intensity ) {
  25534. super( color, intensity );
  25535. this.isDirectionalLight = true;
  25536. this.type = 'DirectionalLight';
  25537. this.position.copy( Object3D.DEFAULT_UP );
  25538. this.updateMatrix();
  25539. this.target = new Object3D();
  25540. this.shadow = new DirectionalLightShadow();
  25541. }
  25542. dispose() {
  25543. this.shadow.dispose();
  25544. }
  25545. copy( source ) {
  25546. super.copy( source );
  25547. this.target = source.target.clone();
  25548. this.shadow = source.shadow.clone();
  25549. return this;
  25550. }
  25551. }
  25552. class AmbientLight extends Light {
  25553. constructor( color, intensity ) {
  25554. super( color, intensity );
  25555. this.isAmbientLight = true;
  25556. this.type = 'AmbientLight';
  25557. }
  25558. }
  25559. class RectAreaLight extends Light {
  25560. constructor( color, intensity, width = 10, height = 10 ) {
  25561. super( color, intensity );
  25562. this.isRectAreaLight = true;
  25563. this.type = 'RectAreaLight';
  25564. this.width = width;
  25565. this.height = height;
  25566. }
  25567. get power() {
  25568. // compute the light's luminous power (in lumens) from its intensity (in nits)
  25569. return this.intensity * this.width * this.height * Math.PI;
  25570. }
  25571. set power( power ) {
  25572. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  25573. this.intensity = power / ( this.width * this.height * Math.PI );
  25574. }
  25575. copy( source ) {
  25576. super.copy( source );
  25577. this.width = source.width;
  25578. this.height = source.height;
  25579. return this;
  25580. }
  25581. toJSON( meta ) {
  25582. const data = super.toJSON( meta );
  25583. data.object.width = this.width;
  25584. data.object.height = this.height;
  25585. return data;
  25586. }
  25587. }
  25588. /**
  25589. * Primary reference:
  25590. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25591. *
  25592. * Secondary reference:
  25593. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25594. */
  25595. // 3-band SH defined by 9 coefficients
  25596. class SphericalHarmonics3 {
  25597. constructor() {
  25598. this.isSphericalHarmonics3 = true;
  25599. this.coefficients = [];
  25600. for ( let i = 0; i < 9; i ++ ) {
  25601. this.coefficients.push( new Vector3() );
  25602. }
  25603. }
  25604. set( coefficients ) {
  25605. for ( let i = 0; i < 9; i ++ ) {
  25606. this.coefficients[ i ].copy( coefficients[ i ] );
  25607. }
  25608. return this;
  25609. }
  25610. zero() {
  25611. for ( let i = 0; i < 9; i ++ ) {
  25612. this.coefficients[ i ].set( 0, 0, 0 );
  25613. }
  25614. return this;
  25615. }
  25616. // get the radiance in the direction of the normal
  25617. // target is a Vector3
  25618. getAt( normal, target ) {
  25619. // normal is assumed to be unit length
  25620. const x = normal.x, y = normal.y, z = normal.z;
  25621. const coeff = this.coefficients;
  25622. // band 0
  25623. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25624. // band 1
  25625. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25626. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25627. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25628. // band 2
  25629. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25630. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25631. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25632. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25633. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25634. return target;
  25635. }
  25636. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25637. // target is a Vector3
  25638. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25639. getIrradianceAt( normal, target ) {
  25640. // normal is assumed to be unit length
  25641. const x = normal.x, y = normal.y, z = normal.z;
  25642. const coeff = this.coefficients;
  25643. // band 0
  25644. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25645. // band 1
  25646. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25647. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25648. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25649. // band 2
  25650. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25651. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25652. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25653. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25654. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25655. return target;
  25656. }
  25657. add( sh ) {
  25658. for ( let i = 0; i < 9; i ++ ) {
  25659. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25660. }
  25661. return this;
  25662. }
  25663. addScaledSH( sh, s ) {
  25664. for ( let i = 0; i < 9; i ++ ) {
  25665. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25666. }
  25667. return this;
  25668. }
  25669. scale( s ) {
  25670. for ( let i = 0; i < 9; i ++ ) {
  25671. this.coefficients[ i ].multiplyScalar( s );
  25672. }
  25673. return this;
  25674. }
  25675. lerp( sh, alpha ) {
  25676. for ( let i = 0; i < 9; i ++ ) {
  25677. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25678. }
  25679. return this;
  25680. }
  25681. equals( sh ) {
  25682. for ( let i = 0; i < 9; i ++ ) {
  25683. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25684. return false;
  25685. }
  25686. }
  25687. return true;
  25688. }
  25689. copy( sh ) {
  25690. return this.set( sh.coefficients );
  25691. }
  25692. clone() {
  25693. return new this.constructor().copy( this );
  25694. }
  25695. fromArray( array, offset = 0 ) {
  25696. const coefficients = this.coefficients;
  25697. for ( let i = 0; i < 9; i ++ ) {
  25698. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25699. }
  25700. return this;
  25701. }
  25702. toArray( array = [], offset = 0 ) {
  25703. const coefficients = this.coefficients;
  25704. for ( let i = 0; i < 9; i ++ ) {
  25705. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25706. }
  25707. return array;
  25708. }
  25709. // evaluate the basis functions
  25710. // shBasis is an Array[ 9 ]
  25711. static getBasisAt( normal, shBasis ) {
  25712. // normal is assumed to be unit length
  25713. const x = normal.x, y = normal.y, z = normal.z;
  25714. // band 0
  25715. shBasis[ 0 ] = 0.282095;
  25716. // band 1
  25717. shBasis[ 1 ] = 0.488603 * y;
  25718. shBasis[ 2 ] = 0.488603 * z;
  25719. shBasis[ 3 ] = 0.488603 * x;
  25720. // band 2
  25721. shBasis[ 4 ] = 1.092548 * x * y;
  25722. shBasis[ 5 ] = 1.092548 * y * z;
  25723. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25724. shBasis[ 7 ] = 1.092548 * x * z;
  25725. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25726. }
  25727. }
  25728. class LightProbe extends Light {
  25729. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25730. super( undefined, intensity );
  25731. this.isLightProbe = true;
  25732. this.sh = sh;
  25733. }
  25734. copy( source ) {
  25735. super.copy( source );
  25736. this.sh.copy( source.sh );
  25737. return this;
  25738. }
  25739. fromJSON( json ) {
  25740. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25741. this.sh.fromArray( json.sh );
  25742. return this;
  25743. }
  25744. toJSON( meta ) {
  25745. const data = super.toJSON( meta );
  25746. data.object.sh = this.sh.toArray();
  25747. return data;
  25748. }
  25749. }
  25750. class MaterialLoader extends Loader {
  25751. constructor( manager ) {
  25752. super( manager );
  25753. this.textures = {};
  25754. }
  25755. load( url, onLoad, onProgress, onError ) {
  25756. const scope = this;
  25757. const loader = new FileLoader( scope.manager );
  25758. loader.setPath( scope.path );
  25759. loader.setRequestHeader( scope.requestHeader );
  25760. loader.setWithCredentials( scope.withCredentials );
  25761. loader.load( url, function ( text ) {
  25762. try {
  25763. onLoad( scope.parse( JSON.parse( text ) ) );
  25764. } catch ( e ) {
  25765. if ( onError ) {
  25766. onError( e );
  25767. } else {
  25768. console.error( e );
  25769. }
  25770. scope.manager.itemError( url );
  25771. }
  25772. }, onProgress, onError );
  25773. }
  25774. parse( json ) {
  25775. const textures = this.textures;
  25776. function getTexture( name ) {
  25777. if ( textures[ name ] === undefined ) {
  25778. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25779. }
  25780. return textures[ name ];
  25781. }
  25782. const material = MaterialLoader.createMaterialFromType( json.type );
  25783. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25784. if ( json.name !== undefined ) material.name = json.name;
  25785. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25786. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25787. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25788. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25789. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25790. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25791. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25792. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25793. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25794. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25795. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25796. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25797. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25798. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25799. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25800. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25801. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25802. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25803. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25804. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25805. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  25806. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  25807. if ( json.fog !== undefined ) material.fog = json.fog;
  25808. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25809. if ( json.blending !== undefined ) material.blending = json.blending;
  25810. if ( json.combine !== undefined ) material.combine = json.combine;
  25811. if ( json.side !== undefined ) material.side = json.side;
  25812. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25813. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25814. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25815. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25816. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  25817. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25818. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25819. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25820. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25821. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25822. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25823. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25824. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25825. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25826. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25827. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25828. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25829. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25830. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25831. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25832. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25833. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  25834. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25835. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25836. if ( json.scale !== undefined ) material.scale = json.scale;
  25837. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25838. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25839. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25840. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25841. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25842. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25843. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25844. if ( json.visible !== undefined ) material.visible = json.visible;
  25845. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25846. if ( json.userData !== undefined ) material.userData = json.userData;
  25847. if ( json.vertexColors !== undefined ) {
  25848. if ( typeof json.vertexColors === 'number' ) {
  25849. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25850. } else {
  25851. material.vertexColors = json.vertexColors;
  25852. }
  25853. }
  25854. // Shader Material
  25855. if ( json.uniforms !== undefined ) {
  25856. for ( const name in json.uniforms ) {
  25857. const uniform = json.uniforms[ name ];
  25858. material.uniforms[ name ] = {};
  25859. switch ( uniform.type ) {
  25860. case 't':
  25861. material.uniforms[ name ].value = getTexture( uniform.value );
  25862. break;
  25863. case 'c':
  25864. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25865. break;
  25866. case 'v2':
  25867. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25868. break;
  25869. case 'v3':
  25870. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25871. break;
  25872. case 'v4':
  25873. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25874. break;
  25875. case 'm3':
  25876. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25877. break;
  25878. case 'm4':
  25879. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25880. break;
  25881. default:
  25882. material.uniforms[ name ].value = uniform.value;
  25883. }
  25884. }
  25885. }
  25886. if ( json.defines !== undefined ) material.defines = json.defines;
  25887. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25888. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25889. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25890. if ( json.extensions !== undefined ) {
  25891. for ( const key in json.extensions ) {
  25892. material.extensions[ key ] = json.extensions[ key ];
  25893. }
  25894. }
  25895. if ( json.lights !== undefined ) material.lights = json.lights;
  25896. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  25897. // for PointsMaterial
  25898. if ( json.size !== undefined ) material.size = json.size;
  25899. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25900. // maps
  25901. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25902. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25903. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25904. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25905. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25906. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25907. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25908. if ( json.normalScale !== undefined ) {
  25909. let normalScale = json.normalScale;
  25910. if ( Array.isArray( normalScale ) === false ) {
  25911. // Blender exporter used to export a scalar. See #7459
  25912. normalScale = [ normalScale, normalScale ];
  25913. }
  25914. material.normalScale = new Vector2().fromArray( normalScale );
  25915. }
  25916. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25917. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25918. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25919. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25920. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25921. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25922. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25923. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25924. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25925. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25926. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25927. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25928. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25929. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25930. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25931. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25932. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25933. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25934. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25935. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25936. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25937. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25938. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25939. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25940. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25941. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25942. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25943. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  25944. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25945. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25946. return material;
  25947. }
  25948. setTextures( value ) {
  25949. this.textures = value;
  25950. return this;
  25951. }
  25952. static createMaterialFromType( type ) {
  25953. const materialLib = {
  25954. ShadowMaterial,
  25955. SpriteMaterial,
  25956. RawShaderMaterial,
  25957. ShaderMaterial,
  25958. PointsMaterial,
  25959. MeshPhysicalMaterial,
  25960. MeshStandardMaterial,
  25961. MeshPhongMaterial,
  25962. MeshToonMaterial,
  25963. MeshNormalMaterial,
  25964. MeshLambertMaterial,
  25965. MeshDepthMaterial,
  25966. MeshDistanceMaterial,
  25967. MeshBasicMaterial,
  25968. MeshMatcapMaterial,
  25969. LineDashedMaterial,
  25970. LineBasicMaterial,
  25971. Material
  25972. };
  25973. return new materialLib[ type ]();
  25974. }
  25975. }
  25976. class LoaderUtils {
  25977. static decodeText( array ) {
  25978. if ( typeof TextDecoder !== 'undefined' ) {
  25979. return new TextDecoder().decode( array );
  25980. }
  25981. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25982. // throws a "maximum call stack size exceeded" error for large arrays.
  25983. let s = '';
  25984. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25985. // Implicitly assumes little-endian.
  25986. s += String.fromCharCode( array[ i ] );
  25987. }
  25988. try {
  25989. // merges multi-byte utf-8 characters.
  25990. return decodeURIComponent( escape( s ) );
  25991. } catch ( e ) { // see #16358
  25992. return s;
  25993. }
  25994. }
  25995. static extractUrlBase( url ) {
  25996. const index = url.lastIndexOf( '/' );
  25997. if ( index === - 1 ) return './';
  25998. return url.slice( 0, index + 1 );
  25999. }
  26000. static resolveURL( url, path ) {
  26001. // Invalid URL
  26002. if ( typeof url !== 'string' || url === '' ) return '';
  26003. // Host Relative URL
  26004. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  26005. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  26006. }
  26007. // Absolute URL http://,https://,//
  26008. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  26009. // Data URI
  26010. if ( /^data:.*,.*$/i.test( url ) ) return url;
  26011. // Blob URL
  26012. if ( /^blob:.*$/i.test( url ) ) return url;
  26013. // Relative URL
  26014. return path + url;
  26015. }
  26016. }
  26017. class InstancedBufferGeometry extends BufferGeometry {
  26018. constructor() {
  26019. super();
  26020. this.isInstancedBufferGeometry = true;
  26021. this.type = 'InstancedBufferGeometry';
  26022. this.instanceCount = Infinity;
  26023. }
  26024. copy( source ) {
  26025. super.copy( source );
  26026. this.instanceCount = source.instanceCount;
  26027. return this;
  26028. }
  26029. toJSON() {
  26030. const data = super.toJSON();
  26031. data.instanceCount = this.instanceCount;
  26032. data.isInstancedBufferGeometry = true;
  26033. return data;
  26034. }
  26035. }
  26036. class BufferGeometryLoader extends Loader {
  26037. constructor( manager ) {
  26038. super( manager );
  26039. }
  26040. load( url, onLoad, onProgress, onError ) {
  26041. const scope = this;
  26042. const loader = new FileLoader( scope.manager );
  26043. loader.setPath( scope.path );
  26044. loader.setRequestHeader( scope.requestHeader );
  26045. loader.setWithCredentials( scope.withCredentials );
  26046. loader.load( url, function ( text ) {
  26047. try {
  26048. onLoad( scope.parse( JSON.parse( text ) ) );
  26049. } catch ( e ) {
  26050. if ( onError ) {
  26051. onError( e );
  26052. } else {
  26053. console.error( e );
  26054. }
  26055. scope.manager.itemError( url );
  26056. }
  26057. }, onProgress, onError );
  26058. }
  26059. parse( json ) {
  26060. const interleavedBufferMap = {};
  26061. const arrayBufferMap = {};
  26062. function getInterleavedBuffer( json, uuid ) {
  26063. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  26064. const interleavedBuffers = json.interleavedBuffers;
  26065. const interleavedBuffer = interleavedBuffers[ uuid ];
  26066. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  26067. const array = getTypedArray( interleavedBuffer.type, buffer );
  26068. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  26069. ib.uuid = interleavedBuffer.uuid;
  26070. interleavedBufferMap[ uuid ] = ib;
  26071. return ib;
  26072. }
  26073. function getArrayBuffer( json, uuid ) {
  26074. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  26075. const arrayBuffers = json.arrayBuffers;
  26076. const arrayBuffer = arrayBuffers[ uuid ];
  26077. const ab = new Uint32Array( arrayBuffer ).buffer;
  26078. arrayBufferMap[ uuid ] = ab;
  26079. return ab;
  26080. }
  26081. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  26082. const index = json.data.index;
  26083. if ( index !== undefined ) {
  26084. const typedArray = getTypedArray( index.type, index.array );
  26085. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  26086. }
  26087. const attributes = json.data.attributes;
  26088. for ( const key in attributes ) {
  26089. const attribute = attributes[ key ];
  26090. let bufferAttribute;
  26091. if ( attribute.isInterleavedBufferAttribute ) {
  26092. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26093. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26094. } else {
  26095. const typedArray = getTypedArray( attribute.type, attribute.array );
  26096. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  26097. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  26098. }
  26099. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26100. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  26101. if ( attribute.updateRange !== undefined ) {
  26102. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  26103. bufferAttribute.updateRange.count = attribute.updateRange.count;
  26104. }
  26105. geometry.setAttribute( key, bufferAttribute );
  26106. }
  26107. const morphAttributes = json.data.morphAttributes;
  26108. if ( morphAttributes ) {
  26109. for ( const key in morphAttributes ) {
  26110. const attributeArray = morphAttributes[ key ];
  26111. const array = [];
  26112. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  26113. const attribute = attributeArray[ i ];
  26114. let bufferAttribute;
  26115. if ( attribute.isInterleavedBufferAttribute ) {
  26116. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  26117. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  26118. } else {
  26119. const typedArray = getTypedArray( attribute.type, attribute.array );
  26120. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  26121. }
  26122. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  26123. array.push( bufferAttribute );
  26124. }
  26125. geometry.morphAttributes[ key ] = array;
  26126. }
  26127. }
  26128. const morphTargetsRelative = json.data.morphTargetsRelative;
  26129. if ( morphTargetsRelative ) {
  26130. geometry.morphTargetsRelative = true;
  26131. }
  26132. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  26133. if ( groups !== undefined ) {
  26134. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  26135. const group = groups[ i ];
  26136. geometry.addGroup( group.start, group.count, group.materialIndex );
  26137. }
  26138. }
  26139. const boundingSphere = json.data.boundingSphere;
  26140. if ( boundingSphere !== undefined ) {
  26141. const center = new Vector3();
  26142. if ( boundingSphere.center !== undefined ) {
  26143. center.fromArray( boundingSphere.center );
  26144. }
  26145. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  26146. }
  26147. if ( json.name ) geometry.name = json.name;
  26148. if ( json.userData ) geometry.userData = json.userData;
  26149. return geometry;
  26150. }
  26151. }
  26152. class ObjectLoader extends Loader {
  26153. constructor( manager ) {
  26154. super( manager );
  26155. }
  26156. load( url, onLoad, onProgress, onError ) {
  26157. const scope = this;
  26158. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26159. this.resourcePath = this.resourcePath || path;
  26160. const loader = new FileLoader( this.manager );
  26161. loader.setPath( this.path );
  26162. loader.setRequestHeader( this.requestHeader );
  26163. loader.setWithCredentials( this.withCredentials );
  26164. loader.load( url, function ( text ) {
  26165. let json = null;
  26166. try {
  26167. json = JSON.parse( text );
  26168. } catch ( error ) {
  26169. if ( onError !== undefined ) onError( error );
  26170. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26171. return;
  26172. }
  26173. const metadata = json.metadata;
  26174. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26175. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  26176. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26177. return;
  26178. }
  26179. scope.parse( json, onLoad );
  26180. }, onProgress, onError );
  26181. }
  26182. async loadAsync( url, onProgress ) {
  26183. const scope = this;
  26184. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26185. this.resourcePath = this.resourcePath || path;
  26186. const loader = new FileLoader( this.manager );
  26187. loader.setPath( this.path );
  26188. loader.setRequestHeader( this.requestHeader );
  26189. loader.setWithCredentials( this.withCredentials );
  26190. const text = await loader.loadAsync( url, onProgress );
  26191. const json = JSON.parse( text );
  26192. const metadata = json.metadata;
  26193. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26194. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26195. }
  26196. return await scope.parseAsync( json );
  26197. }
  26198. parse( json, onLoad ) {
  26199. const animations = this.parseAnimations( json.animations );
  26200. const shapes = this.parseShapes( json.shapes );
  26201. const geometries = this.parseGeometries( json.geometries, shapes );
  26202. const images = this.parseImages( json.images, function () {
  26203. if ( onLoad !== undefined ) onLoad( object );
  26204. } );
  26205. const textures = this.parseTextures( json.textures, images );
  26206. const materials = this.parseMaterials( json.materials, textures );
  26207. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  26208. const skeletons = this.parseSkeletons( json.skeletons, object );
  26209. this.bindSkeletons( object, skeletons );
  26210. //
  26211. if ( onLoad !== undefined ) {
  26212. let hasImages = false;
  26213. for ( const uuid in images ) {
  26214. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  26215. hasImages = true;
  26216. break;
  26217. }
  26218. }
  26219. if ( hasImages === false ) onLoad( object );
  26220. }
  26221. return object;
  26222. }
  26223. async parseAsync( json ) {
  26224. const animations = this.parseAnimations( json.animations );
  26225. const shapes = this.parseShapes( json.shapes );
  26226. const geometries = this.parseGeometries( json.geometries, shapes );
  26227. const images = await this.parseImagesAsync( json.images );
  26228. const textures = this.parseTextures( json.textures, images );
  26229. const materials = this.parseMaterials( json.materials, textures );
  26230. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  26231. const skeletons = this.parseSkeletons( json.skeletons, object );
  26232. this.bindSkeletons( object, skeletons );
  26233. return object;
  26234. }
  26235. parseShapes( json ) {
  26236. const shapes = {};
  26237. if ( json !== undefined ) {
  26238. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26239. const shape = new Shape().fromJSON( json[ i ] );
  26240. shapes[ shape.uuid ] = shape;
  26241. }
  26242. }
  26243. return shapes;
  26244. }
  26245. parseSkeletons( json, object ) {
  26246. const skeletons = {};
  26247. const bones = {};
  26248. // generate bone lookup table
  26249. object.traverse( function ( child ) {
  26250. if ( child.isBone ) bones[ child.uuid ] = child;
  26251. } );
  26252. // create skeletons
  26253. if ( json !== undefined ) {
  26254. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26255. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  26256. skeletons[ skeleton.uuid ] = skeleton;
  26257. }
  26258. }
  26259. return skeletons;
  26260. }
  26261. parseGeometries( json, shapes ) {
  26262. const geometries = {};
  26263. if ( json !== undefined ) {
  26264. const bufferGeometryLoader = new BufferGeometryLoader();
  26265. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26266. let geometry;
  26267. const data = json[ i ];
  26268. switch ( data.type ) {
  26269. case 'BufferGeometry':
  26270. case 'InstancedBufferGeometry':
  26271. geometry = bufferGeometryLoader.parse( data );
  26272. break;
  26273. default:
  26274. if ( data.type in Geometries ) {
  26275. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  26276. } else {
  26277. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  26278. }
  26279. }
  26280. geometry.uuid = data.uuid;
  26281. if ( data.name !== undefined ) geometry.name = data.name;
  26282. if ( data.userData !== undefined ) geometry.userData = data.userData;
  26283. geometries[ data.uuid ] = geometry;
  26284. }
  26285. }
  26286. return geometries;
  26287. }
  26288. parseMaterials( json, textures ) {
  26289. const cache = {}; // MultiMaterial
  26290. const materials = {};
  26291. if ( json !== undefined ) {
  26292. const loader = new MaterialLoader();
  26293. loader.setTextures( textures );
  26294. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26295. const data = json[ i ];
  26296. if ( cache[ data.uuid ] === undefined ) {
  26297. cache[ data.uuid ] = loader.parse( data );
  26298. }
  26299. materials[ data.uuid ] = cache[ data.uuid ];
  26300. }
  26301. }
  26302. return materials;
  26303. }
  26304. parseAnimations( json ) {
  26305. const animations = {};
  26306. if ( json !== undefined ) {
  26307. for ( let i = 0; i < json.length; i ++ ) {
  26308. const data = json[ i ];
  26309. const clip = AnimationClip.parse( data );
  26310. animations[ clip.uuid ] = clip;
  26311. }
  26312. }
  26313. return animations;
  26314. }
  26315. parseImages( json, onLoad ) {
  26316. const scope = this;
  26317. const images = {};
  26318. let loader;
  26319. function loadImage( url ) {
  26320. scope.manager.itemStart( url );
  26321. return loader.load( url, function () {
  26322. scope.manager.itemEnd( url );
  26323. }, undefined, function () {
  26324. scope.manager.itemError( url );
  26325. scope.manager.itemEnd( url );
  26326. } );
  26327. }
  26328. function deserializeImage( image ) {
  26329. if ( typeof image === 'string' ) {
  26330. const url = image;
  26331. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  26332. return loadImage( path );
  26333. } else {
  26334. if ( image.data ) {
  26335. return {
  26336. data: getTypedArray( image.type, image.data ),
  26337. width: image.width,
  26338. height: image.height
  26339. };
  26340. } else {
  26341. return null;
  26342. }
  26343. }
  26344. }
  26345. if ( json !== undefined && json.length > 0 ) {
  26346. const manager = new LoadingManager( onLoad );
  26347. loader = new ImageLoader( manager );
  26348. loader.setCrossOrigin( this.crossOrigin );
  26349. for ( let i = 0, il = json.length; i < il; i ++ ) {
  26350. const image = json[ i ];
  26351. const url = image.url;
  26352. if ( Array.isArray( url ) ) {
  26353. // load array of images e.g CubeTexture
  26354. const imageArray = [];
  26355. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  26356. const currentUrl = url[ j ];
  26357. const deserializedImage = deserializeImage( currentUrl );
  26358. if ( deserializedImage !== null ) {
  26359. if ( deserializedImage instanceof HTMLImageElement ) {
  26360. imageArray.push( deserializedImage );
  26361. } else {
  26362. // special case: handle array of data textures for cube textures
  26363. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  26364. }
  26365. }
  26366. }
  26367. images[ image.uuid ] = new Source( imageArray );
  26368. } else {
  26369. // load single image
  26370. const deserializedImage = deserializeImage( image.url );
  26371. images[ image.uuid ] = new Source( deserializedImage );
  26372. }
  26373. }
  26374. }
  26375. return images;
  26376. }
  26377. async parseImagesAsync( json ) {
  26378. const scope = this;
  26379. const images = {};
  26380. let loader;
  26381. async function deserializeImage( image ) {
  26382. if ( typeof image === 'string' ) {
  26383. const url = image;
  26384. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  26385. return await loader.loadAsync( path );
  26386. } else {
  26387. if ( image.data ) {
  26388. return {
  26389. data: getTypedArray( image.type, image.data ),
  26390. width: image.width,
  26391. height: image.height
  26392. };
  26393. } else {
  26394. return null;
  26395. }
  26396. }
  26397. }
  26398. if ( json !== undefined && json.length > 0 ) {
  26399. loader = new ImageLoader( this.manager );
  26400. loader.setCrossOrigin( this.crossOrigin );
  26401. for ( let i = 0, il = json.length; i < il; i ++ ) {
  26402. const image = json[ i ];
  26403. const url = image.url;
  26404. if ( Array.isArray( url ) ) {
  26405. // load array of images e.g CubeTexture
  26406. const imageArray = [];
  26407. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  26408. const currentUrl = url[ j ];
  26409. const deserializedImage = await deserializeImage( currentUrl );
  26410. if ( deserializedImage !== null ) {
  26411. if ( deserializedImage instanceof HTMLImageElement ) {
  26412. imageArray.push( deserializedImage );
  26413. } else {
  26414. // special case: handle array of data textures for cube textures
  26415. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  26416. }
  26417. }
  26418. }
  26419. images[ image.uuid ] = new Source( imageArray );
  26420. } else {
  26421. // load single image
  26422. const deserializedImage = await deserializeImage( image.url );
  26423. images[ image.uuid ] = new Source( deserializedImage );
  26424. }
  26425. }
  26426. }
  26427. return images;
  26428. }
  26429. parseTextures( json, images ) {
  26430. function parseConstant( value, type ) {
  26431. if ( typeof value === 'number' ) return value;
  26432. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  26433. return type[ value ];
  26434. }
  26435. const textures = {};
  26436. if ( json !== undefined ) {
  26437. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26438. const data = json[ i ];
  26439. if ( data.image === undefined ) {
  26440. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  26441. }
  26442. if ( images[ data.image ] === undefined ) {
  26443. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  26444. }
  26445. const source = images[ data.image ];
  26446. const image = source.data;
  26447. let texture;
  26448. if ( Array.isArray( image ) ) {
  26449. texture = new CubeTexture();
  26450. if ( image.length === 6 ) texture.needsUpdate = true;
  26451. } else {
  26452. if ( image && image.data ) {
  26453. texture = new DataTexture();
  26454. } else {
  26455. texture = new Texture();
  26456. }
  26457. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  26458. }
  26459. texture.source = source;
  26460. texture.uuid = data.uuid;
  26461. if ( data.name !== undefined ) texture.name = data.name;
  26462. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  26463. if ( data.channel !== undefined ) texture.channel = data.channel;
  26464. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  26465. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  26466. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  26467. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  26468. if ( data.wrap !== undefined ) {
  26469. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  26470. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  26471. }
  26472. if ( data.format !== undefined ) texture.format = data.format;
  26473. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  26474. if ( data.type !== undefined ) texture.type = data.type;
  26475. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  26476. if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152
  26477. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  26478. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  26479. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  26480. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  26481. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  26482. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  26483. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  26484. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  26485. if ( data.userData !== undefined ) texture.userData = data.userData;
  26486. textures[ data.uuid ] = texture;
  26487. }
  26488. }
  26489. return textures;
  26490. }
  26491. parseObject( data, geometries, materials, textures, animations ) {
  26492. let object;
  26493. function getGeometry( name ) {
  26494. if ( geometries[ name ] === undefined ) {
  26495. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  26496. }
  26497. return geometries[ name ];
  26498. }
  26499. function getMaterial( name ) {
  26500. if ( name === undefined ) return undefined;
  26501. if ( Array.isArray( name ) ) {
  26502. const array = [];
  26503. for ( let i = 0, l = name.length; i < l; i ++ ) {
  26504. const uuid = name[ i ];
  26505. if ( materials[ uuid ] === undefined ) {
  26506. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  26507. }
  26508. array.push( materials[ uuid ] );
  26509. }
  26510. return array;
  26511. }
  26512. if ( materials[ name ] === undefined ) {
  26513. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26514. }
  26515. return materials[ name ];
  26516. }
  26517. function getTexture( uuid ) {
  26518. if ( textures[ uuid ] === undefined ) {
  26519. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  26520. }
  26521. return textures[ uuid ];
  26522. }
  26523. let geometry, material;
  26524. switch ( data.type ) {
  26525. case 'Scene':
  26526. object = new Scene();
  26527. if ( data.background !== undefined ) {
  26528. if ( Number.isInteger( data.background ) ) {
  26529. object.background = new Color( data.background );
  26530. } else {
  26531. object.background = getTexture( data.background );
  26532. }
  26533. }
  26534. if ( data.environment !== undefined ) {
  26535. object.environment = getTexture( data.environment );
  26536. }
  26537. if ( data.fog !== undefined ) {
  26538. if ( data.fog.type === 'Fog' ) {
  26539. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26540. } else if ( data.fog.type === 'FogExp2' ) {
  26541. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26542. }
  26543. if ( data.fog.name !== '' ) {
  26544. object.fog.name = data.fog.name;
  26545. }
  26546. }
  26547. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  26548. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  26549. break;
  26550. case 'PerspectiveCamera':
  26551. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26552. if ( data.focus !== undefined ) object.focus = data.focus;
  26553. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26554. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26555. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26556. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26557. break;
  26558. case 'OrthographicCamera':
  26559. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26560. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26561. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26562. break;
  26563. case 'AmbientLight':
  26564. object = new AmbientLight( data.color, data.intensity );
  26565. break;
  26566. case 'DirectionalLight':
  26567. object = new DirectionalLight( data.color, data.intensity );
  26568. break;
  26569. case 'PointLight':
  26570. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26571. break;
  26572. case 'RectAreaLight':
  26573. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26574. break;
  26575. case 'SpotLight':
  26576. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26577. break;
  26578. case 'HemisphereLight':
  26579. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26580. break;
  26581. case 'LightProbe':
  26582. object = new LightProbe().fromJSON( data );
  26583. break;
  26584. case 'SkinnedMesh':
  26585. geometry = getGeometry( data.geometry );
  26586. material = getMaterial( data.material );
  26587. object = new SkinnedMesh( geometry, material );
  26588. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  26589. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  26590. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  26591. break;
  26592. case 'Mesh':
  26593. geometry = getGeometry( data.geometry );
  26594. material = getMaterial( data.material );
  26595. object = new Mesh( geometry, material );
  26596. break;
  26597. case 'InstancedMesh':
  26598. geometry = getGeometry( data.geometry );
  26599. material = getMaterial( data.material );
  26600. const count = data.count;
  26601. const instanceMatrix = data.instanceMatrix;
  26602. const instanceColor = data.instanceColor;
  26603. object = new InstancedMesh( geometry, material, count );
  26604. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  26605. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  26606. break;
  26607. case 'LOD':
  26608. object = new LOD();
  26609. break;
  26610. case 'Line':
  26611. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  26612. break;
  26613. case 'LineLoop':
  26614. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26615. break;
  26616. case 'LineSegments':
  26617. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26618. break;
  26619. case 'PointCloud':
  26620. case 'Points':
  26621. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26622. break;
  26623. case 'Sprite':
  26624. object = new Sprite( getMaterial( data.material ) );
  26625. break;
  26626. case 'Group':
  26627. object = new Group();
  26628. break;
  26629. case 'Bone':
  26630. object = new Bone();
  26631. break;
  26632. default:
  26633. object = new Object3D();
  26634. }
  26635. object.uuid = data.uuid;
  26636. if ( data.name !== undefined ) object.name = data.name;
  26637. if ( data.matrix !== undefined ) {
  26638. object.matrix.fromArray( data.matrix );
  26639. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26640. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26641. } else {
  26642. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26643. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26644. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26645. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26646. }
  26647. if ( data.up !== undefined ) object.up.fromArray( data.up );
  26648. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26649. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26650. if ( data.shadow ) {
  26651. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26652. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26653. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26654. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26655. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26656. }
  26657. if ( data.visible !== undefined ) object.visible = data.visible;
  26658. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26659. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26660. if ( data.userData !== undefined ) object.userData = data.userData;
  26661. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26662. if ( data.children !== undefined ) {
  26663. const children = data.children;
  26664. for ( let i = 0; i < children.length; i ++ ) {
  26665. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26666. }
  26667. }
  26668. if ( data.animations !== undefined ) {
  26669. const objectAnimations = data.animations;
  26670. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26671. const uuid = objectAnimations[ i ];
  26672. object.animations.push( animations[ uuid ] );
  26673. }
  26674. }
  26675. if ( data.type === 'LOD' ) {
  26676. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26677. const levels = data.levels;
  26678. for ( let l = 0; l < levels.length; l ++ ) {
  26679. const level = levels[ l ];
  26680. const child = object.getObjectByProperty( 'uuid', level.object );
  26681. if ( child !== undefined ) {
  26682. object.addLevel( child, level.distance, level.hysteresis );
  26683. }
  26684. }
  26685. }
  26686. return object;
  26687. }
  26688. bindSkeletons( object, skeletons ) {
  26689. if ( Object.keys( skeletons ).length === 0 ) return;
  26690. object.traverse( function ( child ) {
  26691. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26692. const skeleton = skeletons[ child.skeleton ];
  26693. if ( skeleton === undefined ) {
  26694. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26695. } else {
  26696. child.bind( skeleton, child.bindMatrix );
  26697. }
  26698. }
  26699. } );
  26700. }
  26701. }
  26702. const TEXTURE_MAPPING = {
  26703. UVMapping: UVMapping,
  26704. CubeReflectionMapping: CubeReflectionMapping,
  26705. CubeRefractionMapping: CubeRefractionMapping,
  26706. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26707. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26708. CubeUVReflectionMapping: CubeUVReflectionMapping
  26709. };
  26710. const TEXTURE_WRAPPING = {
  26711. RepeatWrapping: RepeatWrapping,
  26712. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26713. MirroredRepeatWrapping: MirroredRepeatWrapping
  26714. };
  26715. const TEXTURE_FILTER = {
  26716. NearestFilter: NearestFilter,
  26717. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26718. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26719. LinearFilter: LinearFilter,
  26720. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26721. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26722. };
  26723. class ImageBitmapLoader extends Loader {
  26724. constructor( manager ) {
  26725. super( manager );
  26726. this.isImageBitmapLoader = true;
  26727. if ( typeof createImageBitmap === 'undefined' ) {
  26728. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26729. }
  26730. if ( typeof fetch === 'undefined' ) {
  26731. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26732. }
  26733. this.options = { premultiplyAlpha: 'none' };
  26734. }
  26735. setOptions( options ) {
  26736. this.options = options;
  26737. return this;
  26738. }
  26739. load( url, onLoad, onProgress, onError ) {
  26740. if ( url === undefined ) url = '';
  26741. if ( this.path !== undefined ) url = this.path + url;
  26742. url = this.manager.resolveURL( url );
  26743. const scope = this;
  26744. const cached = Cache.get( url );
  26745. if ( cached !== undefined ) {
  26746. scope.manager.itemStart( url );
  26747. setTimeout( function () {
  26748. if ( onLoad ) onLoad( cached );
  26749. scope.manager.itemEnd( url );
  26750. }, 0 );
  26751. return cached;
  26752. }
  26753. const fetchOptions = {};
  26754. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26755. fetchOptions.headers = this.requestHeader;
  26756. fetch( url, fetchOptions ).then( function ( res ) {
  26757. return res.blob();
  26758. } ).then( function ( blob ) {
  26759. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26760. } ).then( function ( imageBitmap ) {
  26761. Cache.add( url, imageBitmap );
  26762. if ( onLoad ) onLoad( imageBitmap );
  26763. scope.manager.itemEnd( url );
  26764. } ).catch( function ( e ) {
  26765. if ( onError ) onError( e );
  26766. scope.manager.itemError( url );
  26767. scope.manager.itemEnd( url );
  26768. } );
  26769. scope.manager.itemStart( url );
  26770. }
  26771. }
  26772. let _context;
  26773. class AudioContext {
  26774. static getContext() {
  26775. if ( _context === undefined ) {
  26776. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26777. }
  26778. return _context;
  26779. }
  26780. static setContext( value ) {
  26781. _context = value;
  26782. }
  26783. }
  26784. class AudioLoader extends Loader {
  26785. constructor( manager ) {
  26786. super( manager );
  26787. }
  26788. load( url, onLoad, onProgress, onError ) {
  26789. const scope = this;
  26790. const loader = new FileLoader( this.manager );
  26791. loader.setResponseType( 'arraybuffer' );
  26792. loader.setPath( this.path );
  26793. loader.setRequestHeader( this.requestHeader );
  26794. loader.setWithCredentials( this.withCredentials );
  26795. loader.load( url, function ( buffer ) {
  26796. try {
  26797. // Create a copy of the buffer. The `decodeAudioData` method
  26798. // detaches the buffer when complete, preventing reuse.
  26799. const bufferCopy = buffer.slice( 0 );
  26800. const context = AudioContext.getContext();
  26801. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26802. onLoad( audioBuffer );
  26803. }, handleError );
  26804. } catch ( e ) {
  26805. handleError( e );
  26806. }
  26807. }, onProgress, onError );
  26808. function handleError( e ) {
  26809. if ( onError ) {
  26810. onError( e );
  26811. } else {
  26812. console.error( e );
  26813. }
  26814. scope.manager.itemError( url );
  26815. }
  26816. }
  26817. }
  26818. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26819. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26820. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26821. class StereoCamera {
  26822. constructor() {
  26823. this.type = 'StereoCamera';
  26824. this.aspect = 1;
  26825. this.eyeSep = 0.064;
  26826. this.cameraL = new PerspectiveCamera();
  26827. this.cameraL.layers.enable( 1 );
  26828. this.cameraL.matrixAutoUpdate = false;
  26829. this.cameraR = new PerspectiveCamera();
  26830. this.cameraR.layers.enable( 2 );
  26831. this.cameraR.matrixAutoUpdate = false;
  26832. this._cache = {
  26833. focus: null,
  26834. fov: null,
  26835. aspect: null,
  26836. near: null,
  26837. far: null,
  26838. zoom: null,
  26839. eyeSep: null
  26840. };
  26841. }
  26842. update( camera ) {
  26843. const cache = this._cache;
  26844. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26845. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26846. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26847. if ( needsUpdate ) {
  26848. cache.focus = camera.focus;
  26849. cache.fov = camera.fov;
  26850. cache.aspect = camera.aspect * this.aspect;
  26851. cache.near = camera.near;
  26852. cache.far = camera.far;
  26853. cache.zoom = camera.zoom;
  26854. cache.eyeSep = this.eyeSep;
  26855. // Off-axis stereoscopic effect based on
  26856. // http://paulbourke.net/stereographics/stereorender/
  26857. _projectionMatrix.copy( camera.projectionMatrix );
  26858. const eyeSepHalf = cache.eyeSep / 2;
  26859. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26860. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26861. let xmin, xmax;
  26862. // translate xOffset
  26863. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26864. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26865. // for left eye
  26866. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26867. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26868. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26869. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26870. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26871. // for right eye
  26872. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26873. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26874. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26875. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26876. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26877. }
  26878. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26879. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26880. }
  26881. }
  26882. class Clock {
  26883. constructor( autoStart = true ) {
  26884. this.autoStart = autoStart;
  26885. this.startTime = 0;
  26886. this.oldTime = 0;
  26887. this.elapsedTime = 0;
  26888. this.running = false;
  26889. }
  26890. start() {
  26891. this.startTime = now();
  26892. this.oldTime = this.startTime;
  26893. this.elapsedTime = 0;
  26894. this.running = true;
  26895. }
  26896. stop() {
  26897. this.getElapsedTime();
  26898. this.running = false;
  26899. this.autoStart = false;
  26900. }
  26901. getElapsedTime() {
  26902. this.getDelta();
  26903. return this.elapsedTime;
  26904. }
  26905. getDelta() {
  26906. let diff = 0;
  26907. if ( this.autoStart && ! this.running ) {
  26908. this.start();
  26909. return 0;
  26910. }
  26911. if ( this.running ) {
  26912. const newTime = now();
  26913. diff = ( newTime - this.oldTime ) / 1000;
  26914. this.oldTime = newTime;
  26915. this.elapsedTime += diff;
  26916. }
  26917. return diff;
  26918. }
  26919. }
  26920. function now() {
  26921. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26922. }
  26923. const _position$1 = /*@__PURE__*/ new Vector3();
  26924. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26925. const _scale$1 = /*@__PURE__*/ new Vector3();
  26926. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26927. class AudioListener extends Object3D {
  26928. constructor() {
  26929. super();
  26930. this.type = 'AudioListener';
  26931. this.context = AudioContext.getContext();
  26932. this.gain = this.context.createGain();
  26933. this.gain.connect( this.context.destination );
  26934. this.filter = null;
  26935. this.timeDelta = 0;
  26936. // private
  26937. this._clock = new Clock();
  26938. }
  26939. getInput() {
  26940. return this.gain;
  26941. }
  26942. removeFilter() {
  26943. if ( this.filter !== null ) {
  26944. this.gain.disconnect( this.filter );
  26945. this.filter.disconnect( this.context.destination );
  26946. this.gain.connect( this.context.destination );
  26947. this.filter = null;
  26948. }
  26949. return this;
  26950. }
  26951. getFilter() {
  26952. return this.filter;
  26953. }
  26954. setFilter( value ) {
  26955. if ( this.filter !== null ) {
  26956. this.gain.disconnect( this.filter );
  26957. this.filter.disconnect( this.context.destination );
  26958. } else {
  26959. this.gain.disconnect( this.context.destination );
  26960. }
  26961. this.filter = value;
  26962. this.gain.connect( this.filter );
  26963. this.filter.connect( this.context.destination );
  26964. return this;
  26965. }
  26966. getMasterVolume() {
  26967. return this.gain.gain.value;
  26968. }
  26969. setMasterVolume( value ) {
  26970. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26971. return this;
  26972. }
  26973. updateMatrixWorld( force ) {
  26974. super.updateMatrixWorld( force );
  26975. const listener = this.context.listener;
  26976. const up = this.up;
  26977. this.timeDelta = this._clock.getDelta();
  26978. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26979. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26980. if ( listener.positionX ) {
  26981. // code path for Chrome (see #14393)
  26982. const endTime = this.context.currentTime + this.timeDelta;
  26983. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26984. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26985. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26986. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26987. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26988. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26989. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26990. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26991. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26992. } else {
  26993. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26994. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26995. }
  26996. }
  26997. }
  26998. class Audio extends Object3D {
  26999. constructor( listener ) {
  27000. super();
  27001. this.type = 'Audio';
  27002. this.listener = listener;
  27003. this.context = listener.context;
  27004. this.gain = this.context.createGain();
  27005. this.gain.connect( listener.getInput() );
  27006. this.autoplay = false;
  27007. this.buffer = null;
  27008. this.detune = 0;
  27009. this.loop = false;
  27010. this.loopStart = 0;
  27011. this.loopEnd = 0;
  27012. this.offset = 0;
  27013. this.duration = undefined;
  27014. this.playbackRate = 1;
  27015. this.isPlaying = false;
  27016. this.hasPlaybackControl = true;
  27017. this.source = null;
  27018. this.sourceType = 'empty';
  27019. this._startedAt = 0;
  27020. this._progress = 0;
  27021. this._connected = false;
  27022. this.filters = [];
  27023. }
  27024. getOutput() {
  27025. return this.gain;
  27026. }
  27027. setNodeSource( audioNode ) {
  27028. this.hasPlaybackControl = false;
  27029. this.sourceType = 'audioNode';
  27030. this.source = audioNode;
  27031. this.connect();
  27032. return this;
  27033. }
  27034. setMediaElementSource( mediaElement ) {
  27035. this.hasPlaybackControl = false;
  27036. this.sourceType = 'mediaNode';
  27037. this.source = this.context.createMediaElementSource( mediaElement );
  27038. this.connect();
  27039. return this;
  27040. }
  27041. setMediaStreamSource( mediaStream ) {
  27042. this.hasPlaybackControl = false;
  27043. this.sourceType = 'mediaStreamNode';
  27044. this.source = this.context.createMediaStreamSource( mediaStream );
  27045. this.connect();
  27046. return this;
  27047. }
  27048. setBuffer( audioBuffer ) {
  27049. this.buffer = audioBuffer;
  27050. this.sourceType = 'buffer';
  27051. if ( this.autoplay ) this.play();
  27052. return this;
  27053. }
  27054. play( delay = 0 ) {
  27055. if ( this.isPlaying === true ) {
  27056. console.warn( 'THREE.Audio: Audio is already playing.' );
  27057. return;
  27058. }
  27059. if ( this.hasPlaybackControl === false ) {
  27060. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27061. return;
  27062. }
  27063. this._startedAt = this.context.currentTime + delay;
  27064. const source = this.context.createBufferSource();
  27065. source.buffer = this.buffer;
  27066. source.loop = this.loop;
  27067. source.loopStart = this.loopStart;
  27068. source.loopEnd = this.loopEnd;
  27069. source.onended = this.onEnded.bind( this );
  27070. source.start( this._startedAt, this._progress + this.offset, this.duration );
  27071. this.isPlaying = true;
  27072. this.source = source;
  27073. this.setDetune( this.detune );
  27074. this.setPlaybackRate( this.playbackRate );
  27075. return this.connect();
  27076. }
  27077. pause() {
  27078. if ( this.hasPlaybackControl === false ) {
  27079. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27080. return;
  27081. }
  27082. if ( this.isPlaying === true ) {
  27083. // update current progress
  27084. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  27085. if ( this.loop === true ) {
  27086. // ensure _progress does not exceed duration with looped audios
  27087. this._progress = this._progress % ( this.duration || this.buffer.duration );
  27088. }
  27089. this.source.stop();
  27090. this.source.onended = null;
  27091. this.isPlaying = false;
  27092. }
  27093. return this;
  27094. }
  27095. stop() {
  27096. if ( this.hasPlaybackControl === false ) {
  27097. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27098. return;
  27099. }
  27100. this._progress = 0;
  27101. if ( this.source !== null ) {
  27102. this.source.stop();
  27103. this.source.onended = null;
  27104. }
  27105. this.isPlaying = false;
  27106. return this;
  27107. }
  27108. connect() {
  27109. if ( this.filters.length > 0 ) {
  27110. this.source.connect( this.filters[ 0 ] );
  27111. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  27112. this.filters[ i - 1 ].connect( this.filters[ i ] );
  27113. }
  27114. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  27115. } else {
  27116. this.source.connect( this.getOutput() );
  27117. }
  27118. this._connected = true;
  27119. return this;
  27120. }
  27121. disconnect() {
  27122. if ( this._connected === false ) {
  27123. return;
  27124. }
  27125. if ( this.filters.length > 0 ) {
  27126. this.source.disconnect( this.filters[ 0 ] );
  27127. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  27128. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  27129. }
  27130. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27131. } else {
  27132. this.source.disconnect( this.getOutput() );
  27133. }
  27134. this._connected = false;
  27135. return this;
  27136. }
  27137. getFilters() {
  27138. return this.filters;
  27139. }
  27140. setFilters( value ) {
  27141. if ( ! value ) value = [];
  27142. if ( this._connected === true ) {
  27143. this.disconnect();
  27144. this.filters = value.slice();
  27145. this.connect();
  27146. } else {
  27147. this.filters = value.slice();
  27148. }
  27149. return this;
  27150. }
  27151. setDetune( value ) {
  27152. this.detune = value;
  27153. if ( this.source.detune === undefined ) return; // only set detune when available
  27154. if ( this.isPlaying === true ) {
  27155. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  27156. }
  27157. return this;
  27158. }
  27159. getDetune() {
  27160. return this.detune;
  27161. }
  27162. getFilter() {
  27163. return this.getFilters()[ 0 ];
  27164. }
  27165. setFilter( filter ) {
  27166. return this.setFilters( filter ? [ filter ] : [] );
  27167. }
  27168. setPlaybackRate( value ) {
  27169. if ( this.hasPlaybackControl === false ) {
  27170. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27171. return;
  27172. }
  27173. this.playbackRate = value;
  27174. if ( this.isPlaying === true ) {
  27175. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  27176. }
  27177. return this;
  27178. }
  27179. getPlaybackRate() {
  27180. return this.playbackRate;
  27181. }
  27182. onEnded() {
  27183. this.isPlaying = false;
  27184. }
  27185. getLoop() {
  27186. if ( this.hasPlaybackControl === false ) {
  27187. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27188. return false;
  27189. }
  27190. return this.loop;
  27191. }
  27192. setLoop( value ) {
  27193. if ( this.hasPlaybackControl === false ) {
  27194. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27195. return;
  27196. }
  27197. this.loop = value;
  27198. if ( this.isPlaying === true ) {
  27199. this.source.loop = this.loop;
  27200. }
  27201. return this;
  27202. }
  27203. setLoopStart( value ) {
  27204. this.loopStart = value;
  27205. return this;
  27206. }
  27207. setLoopEnd( value ) {
  27208. this.loopEnd = value;
  27209. return this;
  27210. }
  27211. getVolume() {
  27212. return this.gain.gain.value;
  27213. }
  27214. setVolume( value ) {
  27215. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27216. return this;
  27217. }
  27218. }
  27219. const _position = /*@__PURE__*/ new Vector3();
  27220. const _quaternion = /*@__PURE__*/ new Quaternion();
  27221. const _scale = /*@__PURE__*/ new Vector3();
  27222. const _orientation = /*@__PURE__*/ new Vector3();
  27223. class PositionalAudio extends Audio {
  27224. constructor( listener ) {
  27225. super( listener );
  27226. this.panner = this.context.createPanner();
  27227. this.panner.panningModel = 'HRTF';
  27228. this.panner.connect( this.gain );
  27229. }
  27230. connect() {
  27231. super.connect();
  27232. this.panner.connect( this.gain );
  27233. }
  27234. disconnect() {
  27235. super.disconnect();
  27236. this.panner.disconnect( this.gain );
  27237. }
  27238. getOutput() {
  27239. return this.panner;
  27240. }
  27241. getRefDistance() {
  27242. return this.panner.refDistance;
  27243. }
  27244. setRefDistance( value ) {
  27245. this.panner.refDistance = value;
  27246. return this;
  27247. }
  27248. getRolloffFactor() {
  27249. return this.panner.rolloffFactor;
  27250. }
  27251. setRolloffFactor( value ) {
  27252. this.panner.rolloffFactor = value;
  27253. return this;
  27254. }
  27255. getDistanceModel() {
  27256. return this.panner.distanceModel;
  27257. }
  27258. setDistanceModel( value ) {
  27259. this.panner.distanceModel = value;
  27260. return this;
  27261. }
  27262. getMaxDistance() {
  27263. return this.panner.maxDistance;
  27264. }
  27265. setMaxDistance( value ) {
  27266. this.panner.maxDistance = value;
  27267. return this;
  27268. }
  27269. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  27270. this.panner.coneInnerAngle = coneInnerAngle;
  27271. this.panner.coneOuterAngle = coneOuterAngle;
  27272. this.panner.coneOuterGain = coneOuterGain;
  27273. return this;
  27274. }
  27275. updateMatrixWorld( force ) {
  27276. super.updateMatrixWorld( force );
  27277. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  27278. this.matrixWorld.decompose( _position, _quaternion, _scale );
  27279. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  27280. const panner = this.panner;
  27281. if ( panner.positionX ) {
  27282. // code path for Chrome and Firefox (see #14393)
  27283. const endTime = this.context.currentTime + this.listener.timeDelta;
  27284. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  27285. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  27286. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  27287. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  27288. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  27289. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  27290. } else {
  27291. panner.setPosition( _position.x, _position.y, _position.z );
  27292. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  27293. }
  27294. }
  27295. }
  27296. class AudioAnalyser {
  27297. constructor( audio, fftSize = 2048 ) {
  27298. this.analyser = audio.context.createAnalyser();
  27299. this.analyser.fftSize = fftSize;
  27300. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  27301. audio.getOutput().connect( this.analyser );
  27302. }
  27303. getFrequencyData() {
  27304. this.analyser.getByteFrequencyData( this.data );
  27305. return this.data;
  27306. }
  27307. getAverageFrequency() {
  27308. let value = 0;
  27309. const data = this.getFrequencyData();
  27310. for ( let i = 0; i < data.length; i ++ ) {
  27311. value += data[ i ];
  27312. }
  27313. return value / data.length;
  27314. }
  27315. }
  27316. class PropertyMixer {
  27317. constructor( binding, typeName, valueSize ) {
  27318. this.binding = binding;
  27319. this.valueSize = valueSize;
  27320. let mixFunction,
  27321. mixFunctionAdditive,
  27322. setIdentity;
  27323. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  27324. //
  27325. // interpolators can use .buffer as their .result
  27326. // the data then goes to 'incoming'
  27327. //
  27328. // 'accu0' and 'accu1' are used frame-interleaved for
  27329. // the cumulative result and are compared to detect
  27330. // changes
  27331. //
  27332. // 'orig' stores the original state of the property
  27333. //
  27334. // 'add' is used for additive cumulative results
  27335. //
  27336. // 'work' is optional and is only present for quaternion types. It is used
  27337. // to store intermediate quaternion multiplication results
  27338. switch ( typeName ) {
  27339. case 'quaternion':
  27340. mixFunction = this._slerp;
  27341. mixFunctionAdditive = this._slerpAdditive;
  27342. setIdentity = this._setAdditiveIdentityQuaternion;
  27343. this.buffer = new Float64Array( valueSize * 6 );
  27344. this._workIndex = 5;
  27345. break;
  27346. case 'string':
  27347. case 'bool':
  27348. mixFunction = this._select;
  27349. // Use the regular mix function and for additive on these types,
  27350. // additive is not relevant for non-numeric types
  27351. mixFunctionAdditive = this._select;
  27352. setIdentity = this._setAdditiveIdentityOther;
  27353. this.buffer = new Array( valueSize * 5 );
  27354. break;
  27355. default:
  27356. mixFunction = this._lerp;
  27357. mixFunctionAdditive = this._lerpAdditive;
  27358. setIdentity = this._setAdditiveIdentityNumeric;
  27359. this.buffer = new Float64Array( valueSize * 5 );
  27360. }
  27361. this._mixBufferRegion = mixFunction;
  27362. this._mixBufferRegionAdditive = mixFunctionAdditive;
  27363. this._setIdentity = setIdentity;
  27364. this._origIndex = 3;
  27365. this._addIndex = 4;
  27366. this.cumulativeWeight = 0;
  27367. this.cumulativeWeightAdditive = 0;
  27368. this.useCount = 0;
  27369. this.referenceCount = 0;
  27370. }
  27371. // accumulate data in the 'incoming' region into 'accu<i>'
  27372. accumulate( accuIndex, weight ) {
  27373. // note: happily accumulating nothing when weight = 0, the caller knows
  27374. // the weight and shouldn't have made the call in the first place
  27375. const buffer = this.buffer,
  27376. stride = this.valueSize,
  27377. offset = accuIndex * stride + stride;
  27378. let currentWeight = this.cumulativeWeight;
  27379. if ( currentWeight === 0 ) {
  27380. // accuN := incoming * weight
  27381. for ( let i = 0; i !== stride; ++ i ) {
  27382. buffer[ offset + i ] = buffer[ i ];
  27383. }
  27384. currentWeight = weight;
  27385. } else {
  27386. // accuN := accuN + incoming * weight
  27387. currentWeight += weight;
  27388. const mix = weight / currentWeight;
  27389. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27390. }
  27391. this.cumulativeWeight = currentWeight;
  27392. }
  27393. // accumulate data in the 'incoming' region into 'add'
  27394. accumulateAdditive( weight ) {
  27395. const buffer = this.buffer,
  27396. stride = this.valueSize,
  27397. offset = stride * this._addIndex;
  27398. if ( this.cumulativeWeightAdditive === 0 ) {
  27399. // add = identity
  27400. this._setIdentity();
  27401. }
  27402. // add := add + incoming * weight
  27403. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  27404. this.cumulativeWeightAdditive += weight;
  27405. }
  27406. // apply the state of 'accu<i>' to the binding when accus differ
  27407. apply( accuIndex ) {
  27408. const stride = this.valueSize,
  27409. buffer = this.buffer,
  27410. offset = accuIndex * stride + stride,
  27411. weight = this.cumulativeWeight,
  27412. weightAdditive = this.cumulativeWeightAdditive,
  27413. binding = this.binding;
  27414. this.cumulativeWeight = 0;
  27415. this.cumulativeWeightAdditive = 0;
  27416. if ( weight < 1 ) {
  27417. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27418. const originalValueOffset = stride * this._origIndex;
  27419. this._mixBufferRegion(
  27420. buffer, offset, originalValueOffset, 1 - weight, stride );
  27421. }
  27422. if ( weightAdditive > 0 ) {
  27423. // accuN := accuN + additive accuN
  27424. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  27425. }
  27426. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  27427. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27428. // value has changed -> update scene graph
  27429. binding.setValue( buffer, offset );
  27430. break;
  27431. }
  27432. }
  27433. }
  27434. // remember the state of the bound property and copy it to both accus
  27435. saveOriginalState() {
  27436. const binding = this.binding;
  27437. const buffer = this.buffer,
  27438. stride = this.valueSize,
  27439. originalValueOffset = stride * this._origIndex;
  27440. binding.getValue( buffer, originalValueOffset );
  27441. // accu[0..1] := orig -- initially detect changes against the original
  27442. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27443. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27444. }
  27445. // Add to identity for additive
  27446. this._setIdentity();
  27447. this.cumulativeWeight = 0;
  27448. this.cumulativeWeightAdditive = 0;
  27449. }
  27450. // apply the state previously taken via 'saveOriginalState' to the binding
  27451. restoreOriginalState() {
  27452. const originalValueOffset = this.valueSize * 3;
  27453. this.binding.setValue( this.buffer, originalValueOffset );
  27454. }
  27455. _setAdditiveIdentityNumeric() {
  27456. const startIndex = this._addIndex * this.valueSize;
  27457. const endIndex = startIndex + this.valueSize;
  27458. for ( let i = startIndex; i < endIndex; i ++ ) {
  27459. this.buffer[ i ] = 0;
  27460. }
  27461. }
  27462. _setAdditiveIdentityQuaternion() {
  27463. this._setAdditiveIdentityNumeric();
  27464. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  27465. }
  27466. _setAdditiveIdentityOther() {
  27467. const startIndex = this._origIndex * this.valueSize;
  27468. const targetIndex = this._addIndex * this.valueSize;
  27469. for ( let i = 0; i < this.valueSize; i ++ ) {
  27470. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  27471. }
  27472. }
  27473. // mix functions
  27474. _select( buffer, dstOffset, srcOffset, t, stride ) {
  27475. if ( t >= 0.5 ) {
  27476. for ( let i = 0; i !== stride; ++ i ) {
  27477. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27478. }
  27479. }
  27480. }
  27481. _slerp( buffer, dstOffset, srcOffset, t ) {
  27482. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27483. }
  27484. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27485. const workOffset = this._workIndex * stride;
  27486. // Store result in intermediate buffer offset
  27487. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  27488. // Slerp to the intermediate result
  27489. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  27490. }
  27491. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  27492. const s = 1 - t;
  27493. for ( let i = 0; i !== stride; ++ i ) {
  27494. const j = dstOffset + i;
  27495. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27496. }
  27497. }
  27498. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27499. for ( let i = 0; i !== stride; ++ i ) {
  27500. const j = dstOffset + i;
  27501. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  27502. }
  27503. }
  27504. }
  27505. // Characters [].:/ are reserved for track binding syntax.
  27506. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27507. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27508. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27509. // only latin characters, and the unicode \p{L} is not yet supported. So
  27510. // instead, we exclude reserved characters and match everything else.
  27511. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27512. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27513. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27514. // be matched to parse the rest of the track name.
  27515. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27516. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27517. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27518. // Object on target node, and accessor. May not contain reserved
  27519. // characters. Accessor may contain any character except closing bracket.
  27520. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27521. // Property and accessor. May not contain reserved characters. Accessor may
  27522. // contain any non-bracket characters.
  27523. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27524. const _trackRe = new RegExp( ''
  27525. + '^'
  27526. + _directoryRe
  27527. + _nodeRe
  27528. + _objectRe
  27529. + _propertyRe
  27530. + '$'
  27531. );
  27532. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  27533. class Composite {
  27534. constructor( targetGroup, path, optionalParsedPath ) {
  27535. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27536. this._targetGroup = targetGroup;
  27537. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27538. }
  27539. getValue( array, offset ) {
  27540. this.bind(); // bind all binding
  27541. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27542. binding = this._bindings[ firstValidIndex ];
  27543. // and only call .getValue on the first
  27544. if ( binding !== undefined ) binding.getValue( array, offset );
  27545. }
  27546. setValue( array, offset ) {
  27547. const bindings = this._bindings;
  27548. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27549. bindings[ i ].setValue( array, offset );
  27550. }
  27551. }
  27552. bind() {
  27553. const bindings = this._bindings;
  27554. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27555. bindings[ i ].bind();
  27556. }
  27557. }
  27558. unbind() {
  27559. const bindings = this._bindings;
  27560. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27561. bindings[ i ].unbind();
  27562. }
  27563. }
  27564. }
  27565. // Note: This class uses a State pattern on a per-method basis:
  27566. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27567. // prototype version of these methods with one that represents
  27568. // the bound state. When the property is not found, the methods
  27569. // become no-ops.
  27570. class PropertyBinding {
  27571. constructor( rootNode, path, parsedPath ) {
  27572. this.path = path;
  27573. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27574. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  27575. this.rootNode = rootNode;
  27576. // initial state of these methods that calls 'bind'
  27577. this.getValue = this._getValue_unbound;
  27578. this.setValue = this._setValue_unbound;
  27579. }
  27580. static create( root, path, parsedPath ) {
  27581. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27582. return new PropertyBinding( root, path, parsedPath );
  27583. } else {
  27584. return new PropertyBinding.Composite( root, path, parsedPath );
  27585. }
  27586. }
  27587. /**
  27588. * Replaces spaces with underscores and removes unsupported characters from
  27589. * node names, to ensure compatibility with parseTrackName().
  27590. *
  27591. * @param {string} name Node name to be sanitized.
  27592. * @return {string}
  27593. */
  27594. static sanitizeNodeName( name ) {
  27595. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27596. }
  27597. static parseTrackName( trackName ) {
  27598. const matches = _trackRe.exec( trackName );
  27599. if ( matches === null ) {
  27600. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27601. }
  27602. const results = {
  27603. // directoryName: matches[ 1 ], // (tschw) currently unused
  27604. nodeName: matches[ 2 ],
  27605. objectName: matches[ 3 ],
  27606. objectIndex: matches[ 4 ],
  27607. propertyName: matches[ 5 ], // required
  27608. propertyIndex: matches[ 6 ]
  27609. };
  27610. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27611. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27612. const objectName = results.nodeName.substring( lastDot + 1 );
  27613. // Object names must be checked against an allowlist. Otherwise, there
  27614. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27615. // 'bar' could be the objectName, or part of a nodeName (which can
  27616. // include '.' characters).
  27617. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27618. results.nodeName = results.nodeName.substring( 0, lastDot );
  27619. results.objectName = objectName;
  27620. }
  27621. }
  27622. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27623. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27624. }
  27625. return results;
  27626. }
  27627. static findNode( root, nodeName ) {
  27628. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27629. return root;
  27630. }
  27631. // search into skeleton bones.
  27632. if ( root.skeleton ) {
  27633. const bone = root.skeleton.getBoneByName( nodeName );
  27634. if ( bone !== undefined ) {
  27635. return bone;
  27636. }
  27637. }
  27638. // search into node subtree.
  27639. if ( root.children ) {
  27640. const searchNodeSubtree = function ( children ) {
  27641. for ( let i = 0; i < children.length; i ++ ) {
  27642. const childNode = children[ i ];
  27643. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27644. return childNode;
  27645. }
  27646. const result = searchNodeSubtree( childNode.children );
  27647. if ( result ) return result;
  27648. }
  27649. return null;
  27650. };
  27651. const subTreeNode = searchNodeSubtree( root.children );
  27652. if ( subTreeNode ) {
  27653. return subTreeNode;
  27654. }
  27655. }
  27656. return null;
  27657. }
  27658. // these are used to "bind" a nonexistent property
  27659. _getValue_unavailable() {}
  27660. _setValue_unavailable() {}
  27661. // Getters
  27662. _getValue_direct( buffer, offset ) {
  27663. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27664. }
  27665. _getValue_array( buffer, offset ) {
  27666. const source = this.resolvedProperty;
  27667. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27668. buffer[ offset ++ ] = source[ i ];
  27669. }
  27670. }
  27671. _getValue_arrayElement( buffer, offset ) {
  27672. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27673. }
  27674. _getValue_toArray( buffer, offset ) {
  27675. this.resolvedProperty.toArray( buffer, offset );
  27676. }
  27677. // Direct
  27678. _setValue_direct( buffer, offset ) {
  27679. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27680. }
  27681. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27682. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27683. this.targetObject.needsUpdate = true;
  27684. }
  27685. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27686. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27687. this.targetObject.matrixWorldNeedsUpdate = true;
  27688. }
  27689. // EntireArray
  27690. _setValue_array( buffer, offset ) {
  27691. const dest = this.resolvedProperty;
  27692. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27693. dest[ i ] = buffer[ offset ++ ];
  27694. }
  27695. }
  27696. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27697. const dest = this.resolvedProperty;
  27698. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27699. dest[ i ] = buffer[ offset ++ ];
  27700. }
  27701. this.targetObject.needsUpdate = true;
  27702. }
  27703. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27704. const dest = this.resolvedProperty;
  27705. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27706. dest[ i ] = buffer[ offset ++ ];
  27707. }
  27708. this.targetObject.matrixWorldNeedsUpdate = true;
  27709. }
  27710. // ArrayElement
  27711. _setValue_arrayElement( buffer, offset ) {
  27712. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27713. }
  27714. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27715. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27716. this.targetObject.needsUpdate = true;
  27717. }
  27718. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27719. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27720. this.targetObject.matrixWorldNeedsUpdate = true;
  27721. }
  27722. // HasToFromArray
  27723. _setValue_fromArray( buffer, offset ) {
  27724. this.resolvedProperty.fromArray( buffer, offset );
  27725. }
  27726. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27727. this.resolvedProperty.fromArray( buffer, offset );
  27728. this.targetObject.needsUpdate = true;
  27729. }
  27730. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27731. this.resolvedProperty.fromArray( buffer, offset );
  27732. this.targetObject.matrixWorldNeedsUpdate = true;
  27733. }
  27734. _getValue_unbound( targetArray, offset ) {
  27735. this.bind();
  27736. this.getValue( targetArray, offset );
  27737. }
  27738. _setValue_unbound( sourceArray, offset ) {
  27739. this.bind();
  27740. this.setValue( sourceArray, offset );
  27741. }
  27742. // create getter / setter pair for a property in the scene graph
  27743. bind() {
  27744. let targetObject = this.node;
  27745. const parsedPath = this.parsedPath;
  27746. const objectName = parsedPath.objectName;
  27747. const propertyName = parsedPath.propertyName;
  27748. let propertyIndex = parsedPath.propertyIndex;
  27749. if ( ! targetObject ) {
  27750. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27751. this.node = targetObject;
  27752. }
  27753. // set fail state so we can just 'return' on error
  27754. this.getValue = this._getValue_unavailable;
  27755. this.setValue = this._setValue_unavailable;
  27756. // ensure there is a value node
  27757. if ( ! targetObject ) {
  27758. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  27759. return;
  27760. }
  27761. if ( objectName ) {
  27762. let objectIndex = parsedPath.objectIndex;
  27763. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27764. switch ( objectName ) {
  27765. case 'materials':
  27766. if ( ! targetObject.material ) {
  27767. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27768. return;
  27769. }
  27770. if ( ! targetObject.material.materials ) {
  27771. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27772. return;
  27773. }
  27774. targetObject = targetObject.material.materials;
  27775. break;
  27776. case 'bones':
  27777. if ( ! targetObject.skeleton ) {
  27778. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27779. return;
  27780. }
  27781. // potential future optimization: skip this if propertyIndex is already an integer
  27782. // and convert the integer string to a true integer.
  27783. targetObject = targetObject.skeleton.bones;
  27784. // support resolving morphTarget names into indices.
  27785. for ( let i = 0; i < targetObject.length; i ++ ) {
  27786. if ( targetObject[ i ].name === objectIndex ) {
  27787. objectIndex = i;
  27788. break;
  27789. }
  27790. }
  27791. break;
  27792. case 'map':
  27793. if ( 'map' in targetObject ) {
  27794. targetObject = targetObject.map;
  27795. break;
  27796. }
  27797. if ( ! targetObject.material ) {
  27798. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27799. return;
  27800. }
  27801. if ( ! targetObject.material.map ) {
  27802. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27803. return;
  27804. }
  27805. targetObject = targetObject.material.map;
  27806. break;
  27807. default:
  27808. if ( targetObject[ objectName ] === undefined ) {
  27809. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27810. return;
  27811. }
  27812. targetObject = targetObject[ objectName ];
  27813. }
  27814. if ( objectIndex !== undefined ) {
  27815. if ( targetObject[ objectIndex ] === undefined ) {
  27816. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27817. return;
  27818. }
  27819. targetObject = targetObject[ objectIndex ];
  27820. }
  27821. }
  27822. // resolve property
  27823. const nodeProperty = targetObject[ propertyName ];
  27824. if ( nodeProperty === undefined ) {
  27825. const nodeName = parsedPath.nodeName;
  27826. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27827. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27828. return;
  27829. }
  27830. // determine versioning scheme
  27831. let versioning = this.Versioning.None;
  27832. this.targetObject = targetObject;
  27833. if ( targetObject.needsUpdate !== undefined ) { // material
  27834. versioning = this.Versioning.NeedsUpdate;
  27835. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27836. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27837. }
  27838. // determine how the property gets bound
  27839. let bindingType = this.BindingType.Direct;
  27840. if ( propertyIndex !== undefined ) {
  27841. // access a sub element of the property array (only primitives are supported right now)
  27842. if ( propertyName === 'morphTargetInfluences' ) {
  27843. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27844. // support resolving morphTarget names into indices.
  27845. if ( ! targetObject.geometry ) {
  27846. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27847. return;
  27848. }
  27849. if ( ! targetObject.geometry.morphAttributes ) {
  27850. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27851. return;
  27852. }
  27853. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27854. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27855. }
  27856. }
  27857. bindingType = this.BindingType.ArrayElement;
  27858. this.resolvedProperty = nodeProperty;
  27859. this.propertyIndex = propertyIndex;
  27860. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27861. // must use copy for Object3D.Euler/Quaternion
  27862. bindingType = this.BindingType.HasFromToArray;
  27863. this.resolvedProperty = nodeProperty;
  27864. } else if ( Array.isArray( nodeProperty ) ) {
  27865. bindingType = this.BindingType.EntireArray;
  27866. this.resolvedProperty = nodeProperty;
  27867. } else {
  27868. this.propertyName = propertyName;
  27869. }
  27870. // select getter / setter
  27871. this.getValue = this.GetterByBindingType[ bindingType ];
  27872. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27873. }
  27874. unbind() {
  27875. this.node = null;
  27876. // back to the prototype version of getValue / setValue
  27877. // note: avoiding to mutate the shape of 'this' via 'delete'
  27878. this.getValue = this._getValue_unbound;
  27879. this.setValue = this._setValue_unbound;
  27880. }
  27881. }
  27882. PropertyBinding.Composite = Composite;
  27883. PropertyBinding.prototype.BindingType = {
  27884. Direct: 0,
  27885. EntireArray: 1,
  27886. ArrayElement: 2,
  27887. HasFromToArray: 3
  27888. };
  27889. PropertyBinding.prototype.Versioning = {
  27890. None: 0,
  27891. NeedsUpdate: 1,
  27892. MatrixWorldNeedsUpdate: 2
  27893. };
  27894. PropertyBinding.prototype.GetterByBindingType = [
  27895. PropertyBinding.prototype._getValue_direct,
  27896. PropertyBinding.prototype._getValue_array,
  27897. PropertyBinding.prototype._getValue_arrayElement,
  27898. PropertyBinding.prototype._getValue_toArray,
  27899. ];
  27900. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27901. [
  27902. // Direct
  27903. PropertyBinding.prototype._setValue_direct,
  27904. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27905. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27906. ], [
  27907. // EntireArray
  27908. PropertyBinding.prototype._setValue_array,
  27909. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27910. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27911. ], [
  27912. // ArrayElement
  27913. PropertyBinding.prototype._setValue_arrayElement,
  27914. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27915. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27916. ], [
  27917. // HasToFromArray
  27918. PropertyBinding.prototype._setValue_fromArray,
  27919. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27920. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27921. ]
  27922. ];
  27923. /**
  27924. *
  27925. * A group of objects that receives a shared animation state.
  27926. *
  27927. * Usage:
  27928. *
  27929. * - Add objects you would otherwise pass as 'root' to the
  27930. * constructor or the .clipAction method of AnimationMixer.
  27931. *
  27932. * - Instead pass this object as 'root'.
  27933. *
  27934. * - You can also add and remove objects later when the mixer
  27935. * is running.
  27936. *
  27937. * Note:
  27938. *
  27939. * Objects of this class appear as one object to the mixer,
  27940. * so cache control of the individual objects must be done
  27941. * on the group.
  27942. *
  27943. * Limitation:
  27944. *
  27945. * - The animated properties must be compatible among the
  27946. * all objects in the group.
  27947. *
  27948. * - A single property can either be controlled through a
  27949. * target group or directly, but not both.
  27950. */
  27951. class AnimationObjectGroup {
  27952. constructor() {
  27953. this.isAnimationObjectGroup = true;
  27954. this.uuid = generateUUID();
  27955. // cached objects followed by the active ones
  27956. this._objects = Array.prototype.slice.call( arguments );
  27957. this.nCachedObjects_ = 0; // threshold
  27958. // note: read by PropertyBinding.Composite
  27959. const indices = {};
  27960. this._indicesByUUID = indices; // for bookkeeping
  27961. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27962. indices[ arguments[ i ].uuid ] = i;
  27963. }
  27964. this._paths = []; // inside: string
  27965. this._parsedPaths = []; // inside: { we don't care, here }
  27966. this._bindings = []; // inside: Array< PropertyBinding >
  27967. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27968. const scope = this;
  27969. this.stats = {
  27970. objects: {
  27971. get total() {
  27972. return scope._objects.length;
  27973. },
  27974. get inUse() {
  27975. return this.total - scope.nCachedObjects_;
  27976. }
  27977. },
  27978. get bindingsPerObject() {
  27979. return scope._bindings.length;
  27980. }
  27981. };
  27982. }
  27983. add() {
  27984. const objects = this._objects,
  27985. indicesByUUID = this._indicesByUUID,
  27986. paths = this._paths,
  27987. parsedPaths = this._parsedPaths,
  27988. bindings = this._bindings,
  27989. nBindings = bindings.length;
  27990. let knownObject = undefined,
  27991. nObjects = objects.length,
  27992. nCachedObjects = this.nCachedObjects_;
  27993. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27994. const object = arguments[ i ],
  27995. uuid = object.uuid;
  27996. let index = indicesByUUID[ uuid ];
  27997. if ( index === undefined ) {
  27998. // unknown object -> add it to the ACTIVE region
  27999. index = nObjects ++;
  28000. indicesByUUID[ uuid ] = index;
  28001. objects.push( object );
  28002. // accounting is done, now do the same for all bindings
  28003. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28004. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28005. }
  28006. } else if ( index < nCachedObjects ) {
  28007. knownObject = objects[ index ];
  28008. // move existing object to the ACTIVE region
  28009. const firstActiveIndex = -- nCachedObjects,
  28010. lastCachedObject = objects[ firstActiveIndex ];
  28011. indicesByUUID[ lastCachedObject.uuid ] = index;
  28012. objects[ index ] = lastCachedObject;
  28013. indicesByUUID[ uuid ] = firstActiveIndex;
  28014. objects[ firstActiveIndex ] = object;
  28015. // accounting is done, now do the same for all bindings
  28016. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28017. const bindingsForPath = bindings[ j ],
  28018. lastCached = bindingsForPath[ firstActiveIndex ];
  28019. let binding = bindingsForPath[ index ];
  28020. bindingsForPath[ index ] = lastCached;
  28021. if ( binding === undefined ) {
  28022. // since we do not bother to create new bindings
  28023. // for objects that are cached, the binding may
  28024. // or may not exist
  28025. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  28026. }
  28027. bindingsForPath[ firstActiveIndex ] = binding;
  28028. }
  28029. } else if ( objects[ index ] !== knownObject ) {
  28030. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  28031. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  28032. } // else the object is already where we want it to be
  28033. } // for arguments
  28034. this.nCachedObjects_ = nCachedObjects;
  28035. }
  28036. remove() {
  28037. const objects = this._objects,
  28038. indicesByUUID = this._indicesByUUID,
  28039. bindings = this._bindings,
  28040. nBindings = bindings.length;
  28041. let nCachedObjects = this.nCachedObjects_;
  28042. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28043. const object = arguments[ i ],
  28044. uuid = object.uuid,
  28045. index = indicesByUUID[ uuid ];
  28046. if ( index !== undefined && index >= nCachedObjects ) {
  28047. // move existing object into the CACHED region
  28048. const lastCachedIndex = nCachedObjects ++,
  28049. firstActiveObject = objects[ lastCachedIndex ];
  28050. indicesByUUID[ firstActiveObject.uuid ] = index;
  28051. objects[ index ] = firstActiveObject;
  28052. indicesByUUID[ uuid ] = lastCachedIndex;
  28053. objects[ lastCachedIndex ] = object;
  28054. // accounting is done, now do the same for all bindings
  28055. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28056. const bindingsForPath = bindings[ j ],
  28057. firstActive = bindingsForPath[ lastCachedIndex ],
  28058. binding = bindingsForPath[ index ];
  28059. bindingsForPath[ index ] = firstActive;
  28060. bindingsForPath[ lastCachedIndex ] = binding;
  28061. }
  28062. }
  28063. } // for arguments
  28064. this.nCachedObjects_ = nCachedObjects;
  28065. }
  28066. // remove & forget
  28067. uncache() {
  28068. const objects = this._objects,
  28069. indicesByUUID = this._indicesByUUID,
  28070. bindings = this._bindings,
  28071. nBindings = bindings.length;
  28072. let nCachedObjects = this.nCachedObjects_,
  28073. nObjects = objects.length;
  28074. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  28075. const object = arguments[ i ],
  28076. uuid = object.uuid,
  28077. index = indicesByUUID[ uuid ];
  28078. if ( index !== undefined ) {
  28079. delete indicesByUUID[ uuid ];
  28080. if ( index < nCachedObjects ) {
  28081. // object is cached, shrink the CACHED region
  28082. const firstActiveIndex = -- nCachedObjects,
  28083. lastCachedObject = objects[ firstActiveIndex ],
  28084. lastIndex = -- nObjects,
  28085. lastObject = objects[ lastIndex ];
  28086. // last cached object takes this object's place
  28087. indicesByUUID[ lastCachedObject.uuid ] = index;
  28088. objects[ index ] = lastCachedObject;
  28089. // last object goes to the activated slot and pop
  28090. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  28091. objects[ firstActiveIndex ] = lastObject;
  28092. objects.pop();
  28093. // accounting is done, now do the same for all bindings
  28094. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28095. const bindingsForPath = bindings[ j ],
  28096. lastCached = bindingsForPath[ firstActiveIndex ],
  28097. last = bindingsForPath[ lastIndex ];
  28098. bindingsForPath[ index ] = lastCached;
  28099. bindingsForPath[ firstActiveIndex ] = last;
  28100. bindingsForPath.pop();
  28101. }
  28102. } else {
  28103. // object is active, just swap with the last and pop
  28104. const lastIndex = -- nObjects,
  28105. lastObject = objects[ lastIndex ];
  28106. if ( lastIndex > 0 ) {
  28107. indicesByUUID[ lastObject.uuid ] = index;
  28108. }
  28109. objects[ index ] = lastObject;
  28110. objects.pop();
  28111. // accounting is done, now do the same for all bindings
  28112. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  28113. const bindingsForPath = bindings[ j ];
  28114. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  28115. bindingsForPath.pop();
  28116. }
  28117. } // cached or active
  28118. } // if object is known
  28119. } // for arguments
  28120. this.nCachedObjects_ = nCachedObjects;
  28121. }
  28122. // Internal interface used by befriended PropertyBinding.Composite:
  28123. subscribe_( path, parsedPath ) {
  28124. // returns an array of bindings for the given path that is changed
  28125. // according to the contained objects in the group
  28126. const indicesByPath = this._bindingsIndicesByPath;
  28127. let index = indicesByPath[ path ];
  28128. const bindings = this._bindings;
  28129. if ( index !== undefined ) return bindings[ index ];
  28130. const paths = this._paths,
  28131. parsedPaths = this._parsedPaths,
  28132. objects = this._objects,
  28133. nObjects = objects.length,
  28134. nCachedObjects = this.nCachedObjects_,
  28135. bindingsForPath = new Array( nObjects );
  28136. index = bindings.length;
  28137. indicesByPath[ path ] = index;
  28138. paths.push( path );
  28139. parsedPaths.push( parsedPath );
  28140. bindings.push( bindingsForPath );
  28141. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  28142. const object = objects[ i ];
  28143. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  28144. }
  28145. return bindingsForPath;
  28146. }
  28147. unsubscribe_( path ) {
  28148. // tells the group to forget about a property path and no longer
  28149. // update the array previously obtained with 'subscribe_'
  28150. const indicesByPath = this._bindingsIndicesByPath,
  28151. index = indicesByPath[ path ];
  28152. if ( index !== undefined ) {
  28153. const paths = this._paths,
  28154. parsedPaths = this._parsedPaths,
  28155. bindings = this._bindings,
  28156. lastBindingsIndex = bindings.length - 1,
  28157. lastBindings = bindings[ lastBindingsIndex ],
  28158. lastBindingsPath = path[ lastBindingsIndex ];
  28159. indicesByPath[ lastBindingsPath ] = index;
  28160. bindings[ index ] = lastBindings;
  28161. bindings.pop();
  28162. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  28163. parsedPaths.pop();
  28164. paths[ index ] = paths[ lastBindingsIndex ];
  28165. paths.pop();
  28166. }
  28167. }
  28168. }
  28169. class AnimationAction {
  28170. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  28171. this._mixer = mixer;
  28172. this._clip = clip;
  28173. this._localRoot = localRoot;
  28174. this.blendMode = blendMode;
  28175. const tracks = clip.tracks,
  28176. nTracks = tracks.length,
  28177. interpolants = new Array( nTracks );
  28178. const interpolantSettings = {
  28179. endingStart: ZeroCurvatureEnding,
  28180. endingEnd: ZeroCurvatureEnding
  28181. };
  28182. for ( let i = 0; i !== nTracks; ++ i ) {
  28183. const interpolant = tracks[ i ].createInterpolant( null );
  28184. interpolants[ i ] = interpolant;
  28185. interpolant.settings = interpolantSettings;
  28186. }
  28187. this._interpolantSettings = interpolantSettings;
  28188. this._interpolants = interpolants; // bound by the mixer
  28189. // inside: PropertyMixer (managed by the mixer)
  28190. this._propertyBindings = new Array( nTracks );
  28191. this._cacheIndex = null; // for the memory manager
  28192. this._byClipCacheIndex = null; // for the memory manager
  28193. this._timeScaleInterpolant = null;
  28194. this._weightInterpolant = null;
  28195. this.loop = LoopRepeat;
  28196. this._loopCount = - 1;
  28197. // global mixer time when the action is to be started
  28198. // it's set back to 'null' upon start of the action
  28199. this._startTime = null;
  28200. // scaled local time of the action
  28201. // gets clamped or wrapped to 0..clip.duration according to loop
  28202. this.time = 0;
  28203. this.timeScale = 1;
  28204. this._effectiveTimeScale = 1;
  28205. this.weight = 1;
  28206. this._effectiveWeight = 1;
  28207. this.repetitions = Infinity; // no. of repetitions when looping
  28208. this.paused = false; // true -> zero effective time scale
  28209. this.enabled = true; // false -> zero effective weight
  28210. this.clampWhenFinished = false;// keep feeding the last frame?
  28211. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  28212. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  28213. }
  28214. // State & Scheduling
  28215. play() {
  28216. this._mixer._activateAction( this );
  28217. return this;
  28218. }
  28219. stop() {
  28220. this._mixer._deactivateAction( this );
  28221. return this.reset();
  28222. }
  28223. reset() {
  28224. this.paused = false;
  28225. this.enabled = true;
  28226. this.time = 0; // restart clip
  28227. this._loopCount = - 1;// forget previous loops
  28228. this._startTime = null;// forget scheduling
  28229. return this.stopFading().stopWarping();
  28230. }
  28231. isRunning() {
  28232. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  28233. this._startTime === null && this._mixer._isActiveAction( this );
  28234. }
  28235. // return true when play has been called
  28236. isScheduled() {
  28237. return this._mixer._isActiveAction( this );
  28238. }
  28239. startAt( time ) {
  28240. this._startTime = time;
  28241. return this;
  28242. }
  28243. setLoop( mode, repetitions ) {
  28244. this.loop = mode;
  28245. this.repetitions = repetitions;
  28246. return this;
  28247. }
  28248. // Weight
  28249. // set the weight stopping any scheduled fading
  28250. // although .enabled = false yields an effective weight of zero, this
  28251. // method does *not* change .enabled, because it would be confusing
  28252. setEffectiveWeight( weight ) {
  28253. this.weight = weight;
  28254. // note: same logic as when updated at runtime
  28255. this._effectiveWeight = this.enabled ? weight : 0;
  28256. return this.stopFading();
  28257. }
  28258. // return the weight considering fading and .enabled
  28259. getEffectiveWeight() {
  28260. return this._effectiveWeight;
  28261. }
  28262. fadeIn( duration ) {
  28263. return this._scheduleFading( duration, 0, 1 );
  28264. }
  28265. fadeOut( duration ) {
  28266. return this._scheduleFading( duration, 1, 0 );
  28267. }
  28268. crossFadeFrom( fadeOutAction, duration, warp ) {
  28269. fadeOutAction.fadeOut( duration );
  28270. this.fadeIn( duration );
  28271. if ( warp ) {
  28272. const fadeInDuration = this._clip.duration,
  28273. fadeOutDuration = fadeOutAction._clip.duration,
  28274. startEndRatio = fadeOutDuration / fadeInDuration,
  28275. endStartRatio = fadeInDuration / fadeOutDuration;
  28276. fadeOutAction.warp( 1.0, startEndRatio, duration );
  28277. this.warp( endStartRatio, 1.0, duration );
  28278. }
  28279. return this;
  28280. }
  28281. crossFadeTo( fadeInAction, duration, warp ) {
  28282. return fadeInAction.crossFadeFrom( this, duration, warp );
  28283. }
  28284. stopFading() {
  28285. const weightInterpolant = this._weightInterpolant;
  28286. if ( weightInterpolant !== null ) {
  28287. this._weightInterpolant = null;
  28288. this._mixer._takeBackControlInterpolant( weightInterpolant );
  28289. }
  28290. return this;
  28291. }
  28292. // Time Scale Control
  28293. // set the time scale stopping any scheduled warping
  28294. // although .paused = true yields an effective time scale of zero, this
  28295. // method does *not* change .paused, because it would be confusing
  28296. setEffectiveTimeScale( timeScale ) {
  28297. this.timeScale = timeScale;
  28298. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  28299. return this.stopWarping();
  28300. }
  28301. // return the time scale considering warping and .paused
  28302. getEffectiveTimeScale() {
  28303. return this._effectiveTimeScale;
  28304. }
  28305. setDuration( duration ) {
  28306. this.timeScale = this._clip.duration / duration;
  28307. return this.stopWarping();
  28308. }
  28309. syncWith( action ) {
  28310. this.time = action.time;
  28311. this.timeScale = action.timeScale;
  28312. return this.stopWarping();
  28313. }
  28314. halt( duration ) {
  28315. return this.warp( this._effectiveTimeScale, 0, duration );
  28316. }
  28317. warp( startTimeScale, endTimeScale, duration ) {
  28318. const mixer = this._mixer,
  28319. now = mixer.time,
  28320. timeScale = this.timeScale;
  28321. let interpolant = this._timeScaleInterpolant;
  28322. if ( interpolant === null ) {
  28323. interpolant = mixer._lendControlInterpolant();
  28324. this._timeScaleInterpolant = interpolant;
  28325. }
  28326. const times = interpolant.parameterPositions,
  28327. values = interpolant.sampleValues;
  28328. times[ 0 ] = now;
  28329. times[ 1 ] = now + duration;
  28330. values[ 0 ] = startTimeScale / timeScale;
  28331. values[ 1 ] = endTimeScale / timeScale;
  28332. return this;
  28333. }
  28334. stopWarping() {
  28335. const timeScaleInterpolant = this._timeScaleInterpolant;
  28336. if ( timeScaleInterpolant !== null ) {
  28337. this._timeScaleInterpolant = null;
  28338. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  28339. }
  28340. return this;
  28341. }
  28342. // Object Accessors
  28343. getMixer() {
  28344. return this._mixer;
  28345. }
  28346. getClip() {
  28347. return this._clip;
  28348. }
  28349. getRoot() {
  28350. return this._localRoot || this._mixer._root;
  28351. }
  28352. // Interna
  28353. _update( time, deltaTime, timeDirection, accuIndex ) {
  28354. // called by the mixer
  28355. if ( ! this.enabled ) {
  28356. // call ._updateWeight() to update ._effectiveWeight
  28357. this._updateWeight( time );
  28358. return;
  28359. }
  28360. const startTime = this._startTime;
  28361. if ( startTime !== null ) {
  28362. // check for scheduled start of action
  28363. const timeRunning = ( time - startTime ) * timeDirection;
  28364. if ( timeRunning < 0 || timeDirection === 0 ) {
  28365. deltaTime = 0;
  28366. } else {
  28367. this._startTime = null; // unschedule
  28368. deltaTime = timeDirection * timeRunning;
  28369. }
  28370. }
  28371. // apply time scale and advance time
  28372. deltaTime *= this._updateTimeScale( time );
  28373. const clipTime = this._updateTime( deltaTime );
  28374. // note: _updateTime may disable the action resulting in
  28375. // an effective weight of 0
  28376. const weight = this._updateWeight( time );
  28377. if ( weight > 0 ) {
  28378. const interpolants = this._interpolants;
  28379. const propertyMixers = this._propertyBindings;
  28380. switch ( this.blendMode ) {
  28381. case AdditiveAnimationBlendMode:
  28382. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28383. interpolants[ j ].evaluate( clipTime );
  28384. propertyMixers[ j ].accumulateAdditive( weight );
  28385. }
  28386. break;
  28387. case NormalAnimationBlendMode:
  28388. default:
  28389. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28390. interpolants[ j ].evaluate( clipTime );
  28391. propertyMixers[ j ].accumulate( accuIndex, weight );
  28392. }
  28393. }
  28394. }
  28395. }
  28396. _updateWeight( time ) {
  28397. let weight = 0;
  28398. if ( this.enabled ) {
  28399. weight = this.weight;
  28400. const interpolant = this._weightInterpolant;
  28401. if ( interpolant !== null ) {
  28402. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28403. weight *= interpolantValue;
  28404. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28405. this.stopFading();
  28406. if ( interpolantValue === 0 ) {
  28407. // faded out, disable
  28408. this.enabled = false;
  28409. }
  28410. }
  28411. }
  28412. }
  28413. this._effectiveWeight = weight;
  28414. return weight;
  28415. }
  28416. _updateTimeScale( time ) {
  28417. let timeScale = 0;
  28418. if ( ! this.paused ) {
  28419. timeScale = this.timeScale;
  28420. const interpolant = this._timeScaleInterpolant;
  28421. if ( interpolant !== null ) {
  28422. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28423. timeScale *= interpolantValue;
  28424. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28425. this.stopWarping();
  28426. if ( timeScale === 0 ) {
  28427. // motion has halted, pause
  28428. this.paused = true;
  28429. } else {
  28430. // warp done - apply final time scale
  28431. this.timeScale = timeScale;
  28432. }
  28433. }
  28434. }
  28435. }
  28436. this._effectiveTimeScale = timeScale;
  28437. return timeScale;
  28438. }
  28439. _updateTime( deltaTime ) {
  28440. const duration = this._clip.duration;
  28441. const loop = this.loop;
  28442. let time = this.time + deltaTime;
  28443. let loopCount = this._loopCount;
  28444. const pingPong = ( loop === LoopPingPong );
  28445. if ( deltaTime === 0 ) {
  28446. if ( loopCount === - 1 ) return time;
  28447. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  28448. }
  28449. if ( loop === LoopOnce ) {
  28450. if ( loopCount === - 1 ) {
  28451. // just started
  28452. this._loopCount = 0;
  28453. this._setEndings( true, true, false );
  28454. }
  28455. handle_stop: {
  28456. if ( time >= duration ) {
  28457. time = duration;
  28458. } else if ( time < 0 ) {
  28459. time = 0;
  28460. } else {
  28461. this.time = time;
  28462. break handle_stop;
  28463. }
  28464. if ( this.clampWhenFinished ) this.paused = true;
  28465. else this.enabled = false;
  28466. this.time = time;
  28467. this._mixer.dispatchEvent( {
  28468. type: 'finished', action: this,
  28469. direction: deltaTime < 0 ? - 1 : 1
  28470. } );
  28471. }
  28472. } else { // repetitive Repeat or PingPong
  28473. if ( loopCount === - 1 ) {
  28474. // just started
  28475. if ( deltaTime >= 0 ) {
  28476. loopCount = 0;
  28477. this._setEndings( true, this.repetitions === 0, pingPong );
  28478. } else {
  28479. // when looping in reverse direction, the initial
  28480. // transition through zero counts as a repetition,
  28481. // so leave loopCount at -1
  28482. this._setEndings( this.repetitions === 0, true, pingPong );
  28483. }
  28484. }
  28485. if ( time >= duration || time < 0 ) {
  28486. // wrap around
  28487. const loopDelta = Math.floor( time / duration ); // signed
  28488. time -= duration * loopDelta;
  28489. loopCount += Math.abs( loopDelta );
  28490. const pending = this.repetitions - loopCount;
  28491. if ( pending <= 0 ) {
  28492. // have to stop (switch state, clamp time, fire event)
  28493. if ( this.clampWhenFinished ) this.paused = true;
  28494. else this.enabled = false;
  28495. time = deltaTime > 0 ? duration : 0;
  28496. this.time = time;
  28497. this._mixer.dispatchEvent( {
  28498. type: 'finished', action: this,
  28499. direction: deltaTime > 0 ? 1 : - 1
  28500. } );
  28501. } else {
  28502. // keep running
  28503. if ( pending === 1 ) {
  28504. // entering the last round
  28505. const atStart = deltaTime < 0;
  28506. this._setEndings( atStart, ! atStart, pingPong );
  28507. } else {
  28508. this._setEndings( false, false, pingPong );
  28509. }
  28510. this._loopCount = loopCount;
  28511. this.time = time;
  28512. this._mixer.dispatchEvent( {
  28513. type: 'loop', action: this, loopDelta: loopDelta
  28514. } );
  28515. }
  28516. } else {
  28517. this.time = time;
  28518. }
  28519. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28520. // invert time for the "pong round"
  28521. return duration - time;
  28522. }
  28523. }
  28524. return time;
  28525. }
  28526. _setEndings( atStart, atEnd, pingPong ) {
  28527. const settings = this._interpolantSettings;
  28528. if ( pingPong ) {
  28529. settings.endingStart = ZeroSlopeEnding;
  28530. settings.endingEnd = ZeroSlopeEnding;
  28531. } else {
  28532. // assuming for LoopOnce atStart == atEnd == true
  28533. if ( atStart ) {
  28534. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28535. } else {
  28536. settings.endingStart = WrapAroundEnding;
  28537. }
  28538. if ( atEnd ) {
  28539. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28540. } else {
  28541. settings.endingEnd = WrapAroundEnding;
  28542. }
  28543. }
  28544. }
  28545. _scheduleFading( duration, weightNow, weightThen ) {
  28546. const mixer = this._mixer, now = mixer.time;
  28547. let interpolant = this._weightInterpolant;
  28548. if ( interpolant === null ) {
  28549. interpolant = mixer._lendControlInterpolant();
  28550. this._weightInterpolant = interpolant;
  28551. }
  28552. const times = interpolant.parameterPositions,
  28553. values = interpolant.sampleValues;
  28554. times[ 0 ] = now;
  28555. values[ 0 ] = weightNow;
  28556. times[ 1 ] = now + duration;
  28557. values[ 1 ] = weightThen;
  28558. return this;
  28559. }
  28560. }
  28561. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  28562. class AnimationMixer extends EventDispatcher {
  28563. constructor( root ) {
  28564. super();
  28565. this._root = root;
  28566. this._initMemoryManager();
  28567. this._accuIndex = 0;
  28568. this.time = 0;
  28569. this.timeScale = 1.0;
  28570. }
  28571. _bindAction( action, prototypeAction ) {
  28572. const root = action._localRoot || this._root,
  28573. tracks = action._clip.tracks,
  28574. nTracks = tracks.length,
  28575. bindings = action._propertyBindings,
  28576. interpolants = action._interpolants,
  28577. rootUuid = root.uuid,
  28578. bindingsByRoot = this._bindingsByRootAndName;
  28579. let bindingsByName = bindingsByRoot[ rootUuid ];
  28580. if ( bindingsByName === undefined ) {
  28581. bindingsByName = {};
  28582. bindingsByRoot[ rootUuid ] = bindingsByName;
  28583. }
  28584. for ( let i = 0; i !== nTracks; ++ i ) {
  28585. const track = tracks[ i ],
  28586. trackName = track.name;
  28587. let binding = bindingsByName[ trackName ];
  28588. if ( binding !== undefined ) {
  28589. ++ binding.referenceCount;
  28590. bindings[ i ] = binding;
  28591. } else {
  28592. binding = bindings[ i ];
  28593. if ( binding !== undefined ) {
  28594. // existing binding, make sure the cache knows
  28595. if ( binding._cacheIndex === null ) {
  28596. ++ binding.referenceCount;
  28597. this._addInactiveBinding( binding, rootUuid, trackName );
  28598. }
  28599. continue;
  28600. }
  28601. const path = prototypeAction && prototypeAction.
  28602. _propertyBindings[ i ].binding.parsedPath;
  28603. binding = new PropertyMixer(
  28604. PropertyBinding.create( root, trackName, path ),
  28605. track.ValueTypeName, track.getValueSize() );
  28606. ++ binding.referenceCount;
  28607. this._addInactiveBinding( binding, rootUuid, trackName );
  28608. bindings[ i ] = binding;
  28609. }
  28610. interpolants[ i ].resultBuffer = binding.buffer;
  28611. }
  28612. }
  28613. _activateAction( action ) {
  28614. if ( ! this._isActiveAction( action ) ) {
  28615. if ( action._cacheIndex === null ) {
  28616. // this action has been forgotten by the cache, but the user
  28617. // appears to be still using it -> rebind
  28618. const rootUuid = ( action._localRoot || this._root ).uuid,
  28619. clipUuid = action._clip.uuid,
  28620. actionsForClip = this._actionsByClip[ clipUuid ];
  28621. this._bindAction( action,
  28622. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28623. this._addInactiveAction( action, clipUuid, rootUuid );
  28624. }
  28625. const bindings = action._propertyBindings;
  28626. // increment reference counts / sort out state
  28627. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28628. const binding = bindings[ i ];
  28629. if ( binding.useCount ++ === 0 ) {
  28630. this._lendBinding( binding );
  28631. binding.saveOriginalState();
  28632. }
  28633. }
  28634. this._lendAction( action );
  28635. }
  28636. }
  28637. _deactivateAction( action ) {
  28638. if ( this._isActiveAction( action ) ) {
  28639. const bindings = action._propertyBindings;
  28640. // decrement reference counts / sort out state
  28641. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28642. const binding = bindings[ i ];
  28643. if ( -- binding.useCount === 0 ) {
  28644. binding.restoreOriginalState();
  28645. this._takeBackBinding( binding );
  28646. }
  28647. }
  28648. this._takeBackAction( action );
  28649. }
  28650. }
  28651. // Memory manager
  28652. _initMemoryManager() {
  28653. this._actions = []; // 'nActiveActions' followed by inactive ones
  28654. this._nActiveActions = 0;
  28655. this._actionsByClip = {};
  28656. // inside:
  28657. // {
  28658. // knownActions: Array< AnimationAction > - used as prototypes
  28659. // actionByRoot: AnimationAction - lookup
  28660. // }
  28661. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28662. this._nActiveBindings = 0;
  28663. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28664. this._controlInterpolants = []; // same game as above
  28665. this._nActiveControlInterpolants = 0;
  28666. const scope = this;
  28667. this.stats = {
  28668. actions: {
  28669. get total() {
  28670. return scope._actions.length;
  28671. },
  28672. get inUse() {
  28673. return scope._nActiveActions;
  28674. }
  28675. },
  28676. bindings: {
  28677. get total() {
  28678. return scope._bindings.length;
  28679. },
  28680. get inUse() {
  28681. return scope._nActiveBindings;
  28682. }
  28683. },
  28684. controlInterpolants: {
  28685. get total() {
  28686. return scope._controlInterpolants.length;
  28687. },
  28688. get inUse() {
  28689. return scope._nActiveControlInterpolants;
  28690. }
  28691. }
  28692. };
  28693. }
  28694. // Memory management for AnimationAction objects
  28695. _isActiveAction( action ) {
  28696. const index = action._cacheIndex;
  28697. return index !== null && index < this._nActiveActions;
  28698. }
  28699. _addInactiveAction( action, clipUuid, rootUuid ) {
  28700. const actions = this._actions,
  28701. actionsByClip = this._actionsByClip;
  28702. let actionsForClip = actionsByClip[ clipUuid ];
  28703. if ( actionsForClip === undefined ) {
  28704. actionsForClip = {
  28705. knownActions: [ action ],
  28706. actionByRoot: {}
  28707. };
  28708. action._byClipCacheIndex = 0;
  28709. actionsByClip[ clipUuid ] = actionsForClip;
  28710. } else {
  28711. const knownActions = actionsForClip.knownActions;
  28712. action._byClipCacheIndex = knownActions.length;
  28713. knownActions.push( action );
  28714. }
  28715. action._cacheIndex = actions.length;
  28716. actions.push( action );
  28717. actionsForClip.actionByRoot[ rootUuid ] = action;
  28718. }
  28719. _removeInactiveAction( action ) {
  28720. const actions = this._actions,
  28721. lastInactiveAction = actions[ actions.length - 1 ],
  28722. cacheIndex = action._cacheIndex;
  28723. lastInactiveAction._cacheIndex = cacheIndex;
  28724. actions[ cacheIndex ] = lastInactiveAction;
  28725. actions.pop();
  28726. action._cacheIndex = null;
  28727. const clipUuid = action._clip.uuid,
  28728. actionsByClip = this._actionsByClip,
  28729. actionsForClip = actionsByClip[ clipUuid ],
  28730. knownActionsForClip = actionsForClip.knownActions,
  28731. lastKnownAction =
  28732. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28733. byClipCacheIndex = action._byClipCacheIndex;
  28734. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28735. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28736. knownActionsForClip.pop();
  28737. action._byClipCacheIndex = null;
  28738. const actionByRoot = actionsForClip.actionByRoot,
  28739. rootUuid = ( action._localRoot || this._root ).uuid;
  28740. delete actionByRoot[ rootUuid ];
  28741. if ( knownActionsForClip.length === 0 ) {
  28742. delete actionsByClip[ clipUuid ];
  28743. }
  28744. this._removeInactiveBindingsForAction( action );
  28745. }
  28746. _removeInactiveBindingsForAction( action ) {
  28747. const bindings = action._propertyBindings;
  28748. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28749. const binding = bindings[ i ];
  28750. if ( -- binding.referenceCount === 0 ) {
  28751. this._removeInactiveBinding( binding );
  28752. }
  28753. }
  28754. }
  28755. _lendAction( action ) {
  28756. // [ active actions | inactive actions ]
  28757. // [ active actions >| inactive actions ]
  28758. // s a
  28759. // <-swap->
  28760. // a s
  28761. const actions = this._actions,
  28762. prevIndex = action._cacheIndex,
  28763. lastActiveIndex = this._nActiveActions ++,
  28764. firstInactiveAction = actions[ lastActiveIndex ];
  28765. action._cacheIndex = lastActiveIndex;
  28766. actions[ lastActiveIndex ] = action;
  28767. firstInactiveAction._cacheIndex = prevIndex;
  28768. actions[ prevIndex ] = firstInactiveAction;
  28769. }
  28770. _takeBackAction( action ) {
  28771. // [ active actions | inactive actions ]
  28772. // [ active actions |< inactive actions ]
  28773. // a s
  28774. // <-swap->
  28775. // s a
  28776. const actions = this._actions,
  28777. prevIndex = action._cacheIndex,
  28778. firstInactiveIndex = -- this._nActiveActions,
  28779. lastActiveAction = actions[ firstInactiveIndex ];
  28780. action._cacheIndex = firstInactiveIndex;
  28781. actions[ firstInactiveIndex ] = action;
  28782. lastActiveAction._cacheIndex = prevIndex;
  28783. actions[ prevIndex ] = lastActiveAction;
  28784. }
  28785. // Memory management for PropertyMixer objects
  28786. _addInactiveBinding( binding, rootUuid, trackName ) {
  28787. const bindingsByRoot = this._bindingsByRootAndName,
  28788. bindings = this._bindings;
  28789. let bindingByName = bindingsByRoot[ rootUuid ];
  28790. if ( bindingByName === undefined ) {
  28791. bindingByName = {};
  28792. bindingsByRoot[ rootUuid ] = bindingByName;
  28793. }
  28794. bindingByName[ trackName ] = binding;
  28795. binding._cacheIndex = bindings.length;
  28796. bindings.push( binding );
  28797. }
  28798. _removeInactiveBinding( binding ) {
  28799. const bindings = this._bindings,
  28800. propBinding = binding.binding,
  28801. rootUuid = propBinding.rootNode.uuid,
  28802. trackName = propBinding.path,
  28803. bindingsByRoot = this._bindingsByRootAndName,
  28804. bindingByName = bindingsByRoot[ rootUuid ],
  28805. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28806. cacheIndex = binding._cacheIndex;
  28807. lastInactiveBinding._cacheIndex = cacheIndex;
  28808. bindings[ cacheIndex ] = lastInactiveBinding;
  28809. bindings.pop();
  28810. delete bindingByName[ trackName ];
  28811. if ( Object.keys( bindingByName ).length === 0 ) {
  28812. delete bindingsByRoot[ rootUuid ];
  28813. }
  28814. }
  28815. _lendBinding( binding ) {
  28816. const bindings = this._bindings,
  28817. prevIndex = binding._cacheIndex,
  28818. lastActiveIndex = this._nActiveBindings ++,
  28819. firstInactiveBinding = bindings[ lastActiveIndex ];
  28820. binding._cacheIndex = lastActiveIndex;
  28821. bindings[ lastActiveIndex ] = binding;
  28822. firstInactiveBinding._cacheIndex = prevIndex;
  28823. bindings[ prevIndex ] = firstInactiveBinding;
  28824. }
  28825. _takeBackBinding( binding ) {
  28826. const bindings = this._bindings,
  28827. prevIndex = binding._cacheIndex,
  28828. firstInactiveIndex = -- this._nActiveBindings,
  28829. lastActiveBinding = bindings[ firstInactiveIndex ];
  28830. binding._cacheIndex = firstInactiveIndex;
  28831. bindings[ firstInactiveIndex ] = binding;
  28832. lastActiveBinding._cacheIndex = prevIndex;
  28833. bindings[ prevIndex ] = lastActiveBinding;
  28834. }
  28835. // Memory management of Interpolants for weight and time scale
  28836. _lendControlInterpolant() {
  28837. const interpolants = this._controlInterpolants,
  28838. lastActiveIndex = this._nActiveControlInterpolants ++;
  28839. let interpolant = interpolants[ lastActiveIndex ];
  28840. if ( interpolant === undefined ) {
  28841. interpolant = new LinearInterpolant(
  28842. new Float32Array( 2 ), new Float32Array( 2 ),
  28843. 1, _controlInterpolantsResultBuffer );
  28844. interpolant.__cacheIndex = lastActiveIndex;
  28845. interpolants[ lastActiveIndex ] = interpolant;
  28846. }
  28847. return interpolant;
  28848. }
  28849. _takeBackControlInterpolant( interpolant ) {
  28850. const interpolants = this._controlInterpolants,
  28851. prevIndex = interpolant.__cacheIndex,
  28852. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28853. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28854. interpolant.__cacheIndex = firstInactiveIndex;
  28855. interpolants[ firstInactiveIndex ] = interpolant;
  28856. lastActiveInterpolant.__cacheIndex = prevIndex;
  28857. interpolants[ prevIndex ] = lastActiveInterpolant;
  28858. }
  28859. // return an action for a clip optionally using a custom root target
  28860. // object (this method allocates a lot of dynamic memory in case a
  28861. // previously unknown clip/root combination is specified)
  28862. clipAction( clip, optionalRoot, blendMode ) {
  28863. const root = optionalRoot || this._root,
  28864. rootUuid = root.uuid;
  28865. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28866. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28867. const actionsForClip = this._actionsByClip[ clipUuid ];
  28868. let prototypeAction = null;
  28869. if ( blendMode === undefined ) {
  28870. if ( clipObject !== null ) {
  28871. blendMode = clipObject.blendMode;
  28872. } else {
  28873. blendMode = NormalAnimationBlendMode;
  28874. }
  28875. }
  28876. if ( actionsForClip !== undefined ) {
  28877. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28878. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28879. return existingAction;
  28880. }
  28881. // we know the clip, so we don't have to parse all
  28882. // the bindings again but can just copy
  28883. prototypeAction = actionsForClip.knownActions[ 0 ];
  28884. // also, take the clip from the prototype action
  28885. if ( clipObject === null )
  28886. clipObject = prototypeAction._clip;
  28887. }
  28888. // clip must be known when specified via string
  28889. if ( clipObject === null ) return null;
  28890. // allocate all resources required to run it
  28891. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28892. this._bindAction( newAction, prototypeAction );
  28893. // and make the action known to the memory manager
  28894. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28895. return newAction;
  28896. }
  28897. // get an existing action
  28898. existingAction( clip, optionalRoot ) {
  28899. const root = optionalRoot || this._root,
  28900. rootUuid = root.uuid,
  28901. clipObject = typeof clip === 'string' ?
  28902. AnimationClip.findByName( root, clip ) : clip,
  28903. clipUuid = clipObject ? clipObject.uuid : clip,
  28904. actionsForClip = this._actionsByClip[ clipUuid ];
  28905. if ( actionsForClip !== undefined ) {
  28906. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28907. }
  28908. return null;
  28909. }
  28910. // deactivates all previously scheduled actions
  28911. stopAllAction() {
  28912. const actions = this._actions,
  28913. nActions = this._nActiveActions;
  28914. for ( let i = nActions - 1; i >= 0; -- i ) {
  28915. actions[ i ].stop();
  28916. }
  28917. return this;
  28918. }
  28919. // advance the time and update apply the animation
  28920. update( deltaTime ) {
  28921. deltaTime *= this.timeScale;
  28922. const actions = this._actions,
  28923. nActions = this._nActiveActions,
  28924. time = this.time += deltaTime,
  28925. timeDirection = Math.sign( deltaTime ),
  28926. accuIndex = this._accuIndex ^= 1;
  28927. // run active actions
  28928. for ( let i = 0; i !== nActions; ++ i ) {
  28929. const action = actions[ i ];
  28930. action._update( time, deltaTime, timeDirection, accuIndex );
  28931. }
  28932. // update scene graph
  28933. const bindings = this._bindings,
  28934. nBindings = this._nActiveBindings;
  28935. for ( let i = 0; i !== nBindings; ++ i ) {
  28936. bindings[ i ].apply( accuIndex );
  28937. }
  28938. return this;
  28939. }
  28940. // Allows you to seek to a specific time in an animation.
  28941. setTime( timeInSeconds ) {
  28942. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28943. for ( let i = 0; i < this._actions.length; i ++ ) {
  28944. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28945. }
  28946. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28947. }
  28948. // return this mixer's root target object
  28949. getRoot() {
  28950. return this._root;
  28951. }
  28952. // free all resources specific to a particular clip
  28953. uncacheClip( clip ) {
  28954. const actions = this._actions,
  28955. clipUuid = clip.uuid,
  28956. actionsByClip = this._actionsByClip,
  28957. actionsForClip = actionsByClip[ clipUuid ];
  28958. if ( actionsForClip !== undefined ) {
  28959. // note: just calling _removeInactiveAction would mess up the
  28960. // iteration state and also require updating the state we can
  28961. // just throw away
  28962. const actionsToRemove = actionsForClip.knownActions;
  28963. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28964. const action = actionsToRemove[ i ];
  28965. this._deactivateAction( action );
  28966. const cacheIndex = action._cacheIndex,
  28967. lastInactiveAction = actions[ actions.length - 1 ];
  28968. action._cacheIndex = null;
  28969. action._byClipCacheIndex = null;
  28970. lastInactiveAction._cacheIndex = cacheIndex;
  28971. actions[ cacheIndex ] = lastInactiveAction;
  28972. actions.pop();
  28973. this._removeInactiveBindingsForAction( action );
  28974. }
  28975. delete actionsByClip[ clipUuid ];
  28976. }
  28977. }
  28978. // free all resources specific to a particular root target object
  28979. uncacheRoot( root ) {
  28980. const rootUuid = root.uuid,
  28981. actionsByClip = this._actionsByClip;
  28982. for ( const clipUuid in actionsByClip ) {
  28983. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28984. action = actionByRoot[ rootUuid ];
  28985. if ( action !== undefined ) {
  28986. this._deactivateAction( action );
  28987. this._removeInactiveAction( action );
  28988. }
  28989. }
  28990. const bindingsByRoot = this._bindingsByRootAndName,
  28991. bindingByName = bindingsByRoot[ rootUuid ];
  28992. if ( bindingByName !== undefined ) {
  28993. for ( const trackName in bindingByName ) {
  28994. const binding = bindingByName[ trackName ];
  28995. binding.restoreOriginalState();
  28996. this._removeInactiveBinding( binding );
  28997. }
  28998. }
  28999. }
  29000. // remove a targeted clip from the cache
  29001. uncacheAction( clip, optionalRoot ) {
  29002. const action = this.existingAction( clip, optionalRoot );
  29003. if ( action !== null ) {
  29004. this._deactivateAction( action );
  29005. this._removeInactiveAction( action );
  29006. }
  29007. }
  29008. }
  29009. class Uniform {
  29010. constructor( value ) {
  29011. this.value = value;
  29012. }
  29013. clone() {
  29014. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29015. }
  29016. }
  29017. let _id = 0;
  29018. class UniformsGroup extends EventDispatcher {
  29019. constructor() {
  29020. super();
  29021. this.isUniformsGroup = true;
  29022. Object.defineProperty( this, 'id', { value: _id ++ } );
  29023. this.name = '';
  29024. this.usage = StaticDrawUsage;
  29025. this.uniforms = [];
  29026. }
  29027. add( uniform ) {
  29028. this.uniforms.push( uniform );
  29029. return this;
  29030. }
  29031. remove( uniform ) {
  29032. const index = this.uniforms.indexOf( uniform );
  29033. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  29034. return this;
  29035. }
  29036. setName( name ) {
  29037. this.name = name;
  29038. return this;
  29039. }
  29040. setUsage( value ) {
  29041. this.usage = value;
  29042. return this;
  29043. }
  29044. dispose() {
  29045. this.dispatchEvent( { type: 'dispose' } );
  29046. return this;
  29047. }
  29048. copy( source ) {
  29049. this.name = source.name;
  29050. this.usage = source.usage;
  29051. const uniformsSource = source.uniforms;
  29052. this.uniforms.length = 0;
  29053. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  29054. this.uniforms.push( uniformsSource[ i ].clone() );
  29055. }
  29056. return this;
  29057. }
  29058. clone() {
  29059. return new this.constructor().copy( this );
  29060. }
  29061. }
  29062. class InstancedInterleavedBuffer extends InterleavedBuffer {
  29063. constructor( array, stride, meshPerAttribute = 1 ) {
  29064. super( array, stride );
  29065. this.isInstancedInterleavedBuffer = true;
  29066. this.meshPerAttribute = meshPerAttribute;
  29067. }
  29068. copy( source ) {
  29069. super.copy( source );
  29070. this.meshPerAttribute = source.meshPerAttribute;
  29071. return this;
  29072. }
  29073. clone( data ) {
  29074. const ib = super.clone( data );
  29075. ib.meshPerAttribute = this.meshPerAttribute;
  29076. return ib;
  29077. }
  29078. toJSON( data ) {
  29079. const json = super.toJSON( data );
  29080. json.isInstancedInterleavedBuffer = true;
  29081. json.meshPerAttribute = this.meshPerAttribute;
  29082. return json;
  29083. }
  29084. }
  29085. class GLBufferAttribute {
  29086. constructor( buffer, type, itemSize, elementSize, count ) {
  29087. this.isGLBufferAttribute = true;
  29088. this.name = '';
  29089. this.buffer = buffer;
  29090. this.type = type;
  29091. this.itemSize = itemSize;
  29092. this.elementSize = elementSize;
  29093. this.count = count;
  29094. this.version = 0;
  29095. }
  29096. set needsUpdate( value ) {
  29097. if ( value === true ) this.version ++;
  29098. }
  29099. setBuffer( buffer ) {
  29100. this.buffer = buffer;
  29101. return this;
  29102. }
  29103. setType( type, elementSize ) {
  29104. this.type = type;
  29105. this.elementSize = elementSize;
  29106. return this;
  29107. }
  29108. setItemSize( itemSize ) {
  29109. this.itemSize = itemSize;
  29110. return this;
  29111. }
  29112. setCount( count ) {
  29113. this.count = count;
  29114. return this;
  29115. }
  29116. }
  29117. class Raycaster {
  29118. constructor( origin, direction, near = 0, far = Infinity ) {
  29119. this.ray = new Ray( origin, direction );
  29120. // direction is assumed to be normalized (for accurate distance calculations)
  29121. this.near = near;
  29122. this.far = far;
  29123. this.camera = null;
  29124. this.layers = new Layers();
  29125. this.params = {
  29126. Mesh: {},
  29127. Line: { threshold: 1 },
  29128. LOD: {},
  29129. Points: { threshold: 1 },
  29130. Sprite: {}
  29131. };
  29132. }
  29133. set( origin, direction ) {
  29134. // direction is assumed to be normalized (for accurate distance calculations)
  29135. this.ray.set( origin, direction );
  29136. }
  29137. setFromCamera( coords, camera ) {
  29138. if ( camera.isPerspectiveCamera ) {
  29139. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  29140. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  29141. this.camera = camera;
  29142. } else if ( camera.isOrthographicCamera ) {
  29143. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  29144. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  29145. this.camera = camera;
  29146. } else {
  29147. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  29148. }
  29149. }
  29150. intersectObject( object, recursive = true, intersects = [] ) {
  29151. intersectObject( object, this, intersects, recursive );
  29152. intersects.sort( ascSort );
  29153. return intersects;
  29154. }
  29155. intersectObjects( objects, recursive = true, intersects = [] ) {
  29156. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  29157. intersectObject( objects[ i ], this, intersects, recursive );
  29158. }
  29159. intersects.sort( ascSort );
  29160. return intersects;
  29161. }
  29162. }
  29163. function ascSort( a, b ) {
  29164. return a.distance - b.distance;
  29165. }
  29166. function intersectObject( object, raycaster, intersects, recursive ) {
  29167. if ( object.layers.test( raycaster.layers ) ) {
  29168. object.raycast( raycaster, intersects );
  29169. }
  29170. if ( recursive === true ) {
  29171. const children = object.children;
  29172. for ( let i = 0, l = children.length; i < l; i ++ ) {
  29173. intersectObject( children[ i ], raycaster, intersects, true );
  29174. }
  29175. }
  29176. }
  29177. /**
  29178. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  29179. *
  29180. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  29181. * The azimuthal angle (theta) is measured from the positive z-axis.
  29182. */
  29183. class Spherical {
  29184. constructor( radius = 1, phi = 0, theta = 0 ) {
  29185. this.radius = radius;
  29186. this.phi = phi; // polar angle
  29187. this.theta = theta; // azimuthal angle
  29188. return this;
  29189. }
  29190. set( radius, phi, theta ) {
  29191. this.radius = radius;
  29192. this.phi = phi;
  29193. this.theta = theta;
  29194. return this;
  29195. }
  29196. copy( other ) {
  29197. this.radius = other.radius;
  29198. this.phi = other.phi;
  29199. this.theta = other.theta;
  29200. return this;
  29201. }
  29202. // restrict phi to be between EPS and PI-EPS
  29203. makeSafe() {
  29204. const EPS = 0.000001;
  29205. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  29206. return this;
  29207. }
  29208. setFromVector3( v ) {
  29209. return this.setFromCartesianCoords( v.x, v.y, v.z );
  29210. }
  29211. setFromCartesianCoords( x, y, z ) {
  29212. this.radius = Math.sqrt( x * x + y * y + z * z );
  29213. if ( this.radius === 0 ) {
  29214. this.theta = 0;
  29215. this.phi = 0;
  29216. } else {
  29217. this.theta = Math.atan2( x, z );
  29218. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  29219. }
  29220. return this;
  29221. }
  29222. clone() {
  29223. return new this.constructor().copy( this );
  29224. }
  29225. }
  29226. /**
  29227. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  29228. */
  29229. class Cylindrical {
  29230. constructor( radius = 1, theta = 0, y = 0 ) {
  29231. this.radius = radius; // distance from the origin to a point in the x-z plane
  29232. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  29233. this.y = y; // height above the x-z plane
  29234. return this;
  29235. }
  29236. set( radius, theta, y ) {
  29237. this.radius = radius;
  29238. this.theta = theta;
  29239. this.y = y;
  29240. return this;
  29241. }
  29242. copy( other ) {
  29243. this.radius = other.radius;
  29244. this.theta = other.theta;
  29245. this.y = other.y;
  29246. return this;
  29247. }
  29248. setFromVector3( v ) {
  29249. return this.setFromCartesianCoords( v.x, v.y, v.z );
  29250. }
  29251. setFromCartesianCoords( x, y, z ) {
  29252. this.radius = Math.sqrt( x * x + z * z );
  29253. this.theta = Math.atan2( x, z );
  29254. this.y = y;
  29255. return this;
  29256. }
  29257. clone() {
  29258. return new this.constructor().copy( this );
  29259. }
  29260. }
  29261. const _vector$4 = /*@__PURE__*/ new Vector2();
  29262. class Box2 {
  29263. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  29264. this.isBox2 = true;
  29265. this.min = min;
  29266. this.max = max;
  29267. }
  29268. set( min, max ) {
  29269. this.min.copy( min );
  29270. this.max.copy( max );
  29271. return this;
  29272. }
  29273. setFromPoints( points ) {
  29274. this.makeEmpty();
  29275. for ( let i = 0, il = points.length; i < il; i ++ ) {
  29276. this.expandByPoint( points[ i ] );
  29277. }
  29278. return this;
  29279. }
  29280. setFromCenterAndSize( center, size ) {
  29281. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  29282. this.min.copy( center ).sub( halfSize );
  29283. this.max.copy( center ).add( halfSize );
  29284. return this;
  29285. }
  29286. clone() {
  29287. return new this.constructor().copy( this );
  29288. }
  29289. copy( box ) {
  29290. this.min.copy( box.min );
  29291. this.max.copy( box.max );
  29292. return this;
  29293. }
  29294. makeEmpty() {
  29295. this.min.x = this.min.y = + Infinity;
  29296. this.max.x = this.max.y = - Infinity;
  29297. return this;
  29298. }
  29299. isEmpty() {
  29300. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  29301. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  29302. }
  29303. getCenter( target ) {
  29304. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  29305. }
  29306. getSize( target ) {
  29307. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  29308. }
  29309. expandByPoint( point ) {
  29310. this.min.min( point );
  29311. this.max.max( point );
  29312. return this;
  29313. }
  29314. expandByVector( vector ) {
  29315. this.min.sub( vector );
  29316. this.max.add( vector );
  29317. return this;
  29318. }
  29319. expandByScalar( scalar ) {
  29320. this.min.addScalar( - scalar );
  29321. this.max.addScalar( scalar );
  29322. return this;
  29323. }
  29324. containsPoint( point ) {
  29325. return point.x < this.min.x || point.x > this.max.x ||
  29326. point.y < this.min.y || point.y > this.max.y ? false : true;
  29327. }
  29328. containsBox( box ) {
  29329. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  29330. this.min.y <= box.min.y && box.max.y <= this.max.y;
  29331. }
  29332. getParameter( point, target ) {
  29333. // This can potentially have a divide by zero if the box
  29334. // has a size dimension of 0.
  29335. return target.set(
  29336. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  29337. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  29338. );
  29339. }
  29340. intersectsBox( box ) {
  29341. // using 4 splitting planes to rule out intersections
  29342. return box.max.x < this.min.x || box.min.x > this.max.x ||
  29343. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  29344. }
  29345. clampPoint( point, target ) {
  29346. return target.copy( point ).clamp( this.min, this.max );
  29347. }
  29348. distanceToPoint( point ) {
  29349. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  29350. }
  29351. intersect( box ) {
  29352. this.min.max( box.min );
  29353. this.max.min( box.max );
  29354. if ( this.isEmpty() ) this.makeEmpty();
  29355. return this;
  29356. }
  29357. union( box ) {
  29358. this.min.min( box.min );
  29359. this.max.max( box.max );
  29360. return this;
  29361. }
  29362. translate( offset ) {
  29363. this.min.add( offset );
  29364. this.max.add( offset );
  29365. return this;
  29366. }
  29367. equals( box ) {
  29368. return box.min.equals( this.min ) && box.max.equals( this.max );
  29369. }
  29370. }
  29371. const _startP = /*@__PURE__*/ new Vector3();
  29372. const _startEnd = /*@__PURE__*/ new Vector3();
  29373. class Line3 {
  29374. constructor( start = new Vector3(), end = new Vector3() ) {
  29375. this.start = start;
  29376. this.end = end;
  29377. }
  29378. set( start, end ) {
  29379. this.start.copy( start );
  29380. this.end.copy( end );
  29381. return this;
  29382. }
  29383. copy( line ) {
  29384. this.start.copy( line.start );
  29385. this.end.copy( line.end );
  29386. return this;
  29387. }
  29388. getCenter( target ) {
  29389. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  29390. }
  29391. delta( target ) {
  29392. return target.subVectors( this.end, this.start );
  29393. }
  29394. distanceSq() {
  29395. return this.start.distanceToSquared( this.end );
  29396. }
  29397. distance() {
  29398. return this.start.distanceTo( this.end );
  29399. }
  29400. at( t, target ) {
  29401. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29402. }
  29403. closestPointToPointParameter( point, clampToLine ) {
  29404. _startP.subVectors( point, this.start );
  29405. _startEnd.subVectors( this.end, this.start );
  29406. const startEnd2 = _startEnd.dot( _startEnd );
  29407. const startEnd_startP = _startEnd.dot( _startP );
  29408. let t = startEnd_startP / startEnd2;
  29409. if ( clampToLine ) {
  29410. t = clamp( t, 0, 1 );
  29411. }
  29412. return t;
  29413. }
  29414. closestPointToPoint( point, clampToLine, target ) {
  29415. const t = this.closestPointToPointParameter( point, clampToLine );
  29416. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29417. }
  29418. applyMatrix4( matrix ) {
  29419. this.start.applyMatrix4( matrix );
  29420. this.end.applyMatrix4( matrix );
  29421. return this;
  29422. }
  29423. equals( line ) {
  29424. return line.start.equals( this.start ) && line.end.equals( this.end );
  29425. }
  29426. clone() {
  29427. return new this.constructor().copy( this );
  29428. }
  29429. }
  29430. const _vector$3 = /*@__PURE__*/ new Vector3();
  29431. class SpotLightHelper extends Object3D {
  29432. constructor( light, color ) {
  29433. super();
  29434. this.light = light;
  29435. this.matrix = light.matrixWorld;
  29436. this.matrixAutoUpdate = false;
  29437. this.color = color;
  29438. this.type = 'SpotLightHelper';
  29439. const geometry = new BufferGeometry();
  29440. const positions = [
  29441. 0, 0, 0, 0, 0, 1,
  29442. 0, 0, 0, 1, 0, 1,
  29443. 0, 0, 0, - 1, 0, 1,
  29444. 0, 0, 0, 0, 1, 1,
  29445. 0, 0, 0, 0, - 1, 1
  29446. ];
  29447. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  29448. const p1 = ( i / l ) * Math.PI * 2;
  29449. const p2 = ( j / l ) * Math.PI * 2;
  29450. positions.push(
  29451. Math.cos( p1 ), Math.sin( p1 ), 1,
  29452. Math.cos( p2 ), Math.sin( p2 ), 1
  29453. );
  29454. }
  29455. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29456. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29457. this.cone = new LineSegments( geometry, material );
  29458. this.add( this.cone );
  29459. this.update();
  29460. }
  29461. dispose() {
  29462. this.cone.geometry.dispose();
  29463. this.cone.material.dispose();
  29464. }
  29465. update() {
  29466. this.light.updateWorldMatrix( true, false );
  29467. this.light.target.updateWorldMatrix( true, false );
  29468. const coneLength = this.light.distance ? this.light.distance : 1000;
  29469. const coneWidth = coneLength * Math.tan( this.light.angle );
  29470. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  29471. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29472. this.cone.lookAt( _vector$3 );
  29473. if ( this.color !== undefined ) {
  29474. this.cone.material.color.set( this.color );
  29475. } else {
  29476. this.cone.material.color.copy( this.light.color );
  29477. }
  29478. }
  29479. }
  29480. const _vector$2 = /*@__PURE__*/ new Vector3();
  29481. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  29482. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  29483. class SkeletonHelper extends LineSegments {
  29484. constructor( object ) {
  29485. const bones = getBoneList( object );
  29486. const geometry = new BufferGeometry();
  29487. const vertices = [];
  29488. const colors = [];
  29489. const color1 = new Color( 0, 0, 1 );
  29490. const color2 = new Color( 0, 1, 0 );
  29491. for ( let i = 0; i < bones.length; i ++ ) {
  29492. const bone = bones[ i ];
  29493. if ( bone.parent && bone.parent.isBone ) {
  29494. vertices.push( 0, 0, 0 );
  29495. vertices.push( 0, 0, 0 );
  29496. colors.push( color1.r, color1.g, color1.b );
  29497. colors.push( color2.r, color2.g, color2.b );
  29498. }
  29499. }
  29500. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29501. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29502. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  29503. super( geometry, material );
  29504. this.isSkeletonHelper = true;
  29505. this.type = 'SkeletonHelper';
  29506. this.root = object;
  29507. this.bones = bones;
  29508. this.matrix = object.matrixWorld;
  29509. this.matrixAutoUpdate = false;
  29510. }
  29511. updateMatrixWorld( force ) {
  29512. const bones = this.bones;
  29513. const geometry = this.geometry;
  29514. const position = geometry.getAttribute( 'position' );
  29515. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29516. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29517. const bone = bones[ i ];
  29518. if ( bone.parent && bone.parent.isBone ) {
  29519. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29520. _vector$2.setFromMatrixPosition( _boneMatrix );
  29521. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29522. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29523. _vector$2.setFromMatrixPosition( _boneMatrix );
  29524. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29525. j += 2;
  29526. }
  29527. }
  29528. geometry.getAttribute( 'position' ).needsUpdate = true;
  29529. super.updateMatrixWorld( force );
  29530. }
  29531. dispose() {
  29532. this.geometry.dispose();
  29533. this.material.dispose();
  29534. }
  29535. }
  29536. function getBoneList( object ) {
  29537. const boneList = [];
  29538. if ( object.isBone === true ) {
  29539. boneList.push( object );
  29540. }
  29541. for ( let i = 0; i < object.children.length; i ++ ) {
  29542. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29543. }
  29544. return boneList;
  29545. }
  29546. class PointLightHelper extends Mesh {
  29547. constructor( light, sphereSize, color ) {
  29548. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29549. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29550. super( geometry, material );
  29551. this.light = light;
  29552. this.color = color;
  29553. this.type = 'PointLightHelper';
  29554. this.matrix = this.light.matrixWorld;
  29555. this.matrixAutoUpdate = false;
  29556. this.update();
  29557. /*
  29558. // TODO: delete this comment?
  29559. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  29560. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29561. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29562. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29563. const d = light.distance;
  29564. if ( d === 0.0 ) {
  29565. this.lightDistance.visible = false;
  29566. } else {
  29567. this.lightDistance.scale.set( d, d, d );
  29568. }
  29569. this.add( this.lightDistance );
  29570. */
  29571. }
  29572. dispose() {
  29573. this.geometry.dispose();
  29574. this.material.dispose();
  29575. }
  29576. update() {
  29577. this.light.updateWorldMatrix( true, false );
  29578. if ( this.color !== undefined ) {
  29579. this.material.color.set( this.color );
  29580. } else {
  29581. this.material.color.copy( this.light.color );
  29582. }
  29583. /*
  29584. const d = this.light.distance;
  29585. if ( d === 0.0 ) {
  29586. this.lightDistance.visible = false;
  29587. } else {
  29588. this.lightDistance.visible = true;
  29589. this.lightDistance.scale.set( d, d, d );
  29590. }
  29591. */
  29592. }
  29593. }
  29594. const _vector$1 = /*@__PURE__*/ new Vector3();
  29595. const _color1 = /*@__PURE__*/ new Color();
  29596. const _color2 = /*@__PURE__*/ new Color();
  29597. class HemisphereLightHelper extends Object3D {
  29598. constructor( light, size, color ) {
  29599. super();
  29600. this.light = light;
  29601. this.matrix = light.matrixWorld;
  29602. this.matrixAutoUpdate = false;
  29603. this.color = color;
  29604. this.type = 'HemisphereLightHelper';
  29605. const geometry = new OctahedronGeometry( size );
  29606. geometry.rotateY( Math.PI * 0.5 );
  29607. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29608. if ( this.color === undefined ) this.material.vertexColors = true;
  29609. const position = geometry.getAttribute( 'position' );
  29610. const colors = new Float32Array( position.count * 3 );
  29611. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29612. this.add( new Mesh( geometry, this.material ) );
  29613. this.update();
  29614. }
  29615. dispose() {
  29616. this.children[ 0 ].geometry.dispose();
  29617. this.children[ 0 ].material.dispose();
  29618. }
  29619. update() {
  29620. const mesh = this.children[ 0 ];
  29621. if ( this.color !== undefined ) {
  29622. this.material.color.set( this.color );
  29623. } else {
  29624. const colors = mesh.geometry.getAttribute( 'color' );
  29625. _color1.copy( this.light.color );
  29626. _color2.copy( this.light.groundColor );
  29627. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29628. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29629. colors.setXYZ( i, color.r, color.g, color.b );
  29630. }
  29631. colors.needsUpdate = true;
  29632. }
  29633. this.light.updateWorldMatrix( true, false );
  29634. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29635. }
  29636. }
  29637. class GridHelper extends LineSegments {
  29638. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29639. color1 = new Color( color1 );
  29640. color2 = new Color( color2 );
  29641. const center = divisions / 2;
  29642. const step = size / divisions;
  29643. const halfSize = size / 2;
  29644. const vertices = [], colors = [];
  29645. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29646. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29647. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29648. const color = i === center ? color1 : color2;
  29649. color.toArray( colors, j ); j += 3;
  29650. color.toArray( colors, j ); j += 3;
  29651. color.toArray( colors, j ); j += 3;
  29652. color.toArray( colors, j ); j += 3;
  29653. }
  29654. const geometry = new BufferGeometry();
  29655. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29656. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29657. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29658. super( geometry, material );
  29659. this.type = 'GridHelper';
  29660. }
  29661. dispose() {
  29662. this.geometry.dispose();
  29663. this.material.dispose();
  29664. }
  29665. }
  29666. class PolarGridHelper extends LineSegments {
  29667. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29668. color1 = new Color( color1 );
  29669. color2 = new Color( color2 );
  29670. const vertices = [];
  29671. const colors = [];
  29672. // create the sectors
  29673. if ( sectors > 1 ) {
  29674. for ( let i = 0; i < sectors; i ++ ) {
  29675. const v = ( i / sectors ) * ( Math.PI * 2 );
  29676. const x = Math.sin( v ) * radius;
  29677. const z = Math.cos( v ) * radius;
  29678. vertices.push( 0, 0, 0 );
  29679. vertices.push( x, 0, z );
  29680. const color = ( i & 1 ) ? color1 : color2;
  29681. colors.push( color.r, color.g, color.b );
  29682. colors.push( color.r, color.g, color.b );
  29683. }
  29684. }
  29685. // create the rings
  29686. for ( let i = 0; i < rings; i ++ ) {
  29687. const color = ( i & 1 ) ? color1 : color2;
  29688. const r = radius - ( radius / rings * i );
  29689. for ( let j = 0; j < divisions; j ++ ) {
  29690. // first vertex
  29691. let v = ( j / divisions ) * ( Math.PI * 2 );
  29692. let x = Math.sin( v ) * r;
  29693. let z = Math.cos( v ) * r;
  29694. vertices.push( x, 0, z );
  29695. colors.push( color.r, color.g, color.b );
  29696. // second vertex
  29697. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29698. x = Math.sin( v ) * r;
  29699. z = Math.cos( v ) * r;
  29700. vertices.push( x, 0, z );
  29701. colors.push( color.r, color.g, color.b );
  29702. }
  29703. }
  29704. const geometry = new BufferGeometry();
  29705. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29706. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29707. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29708. super( geometry, material );
  29709. this.type = 'PolarGridHelper';
  29710. }
  29711. dispose() {
  29712. this.geometry.dispose();
  29713. this.material.dispose();
  29714. }
  29715. }
  29716. const _v1 = /*@__PURE__*/ new Vector3();
  29717. const _v2 = /*@__PURE__*/ new Vector3();
  29718. const _v3 = /*@__PURE__*/ new Vector3();
  29719. class DirectionalLightHelper extends Object3D {
  29720. constructor( light, size, color ) {
  29721. super();
  29722. this.light = light;
  29723. this.matrix = light.matrixWorld;
  29724. this.matrixAutoUpdate = false;
  29725. this.color = color;
  29726. this.type = 'DirectionalLightHelper';
  29727. if ( size === undefined ) size = 1;
  29728. let geometry = new BufferGeometry();
  29729. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29730. - size, size, 0,
  29731. size, size, 0,
  29732. size, - size, 0,
  29733. - size, - size, 0,
  29734. - size, size, 0
  29735. ], 3 ) );
  29736. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29737. this.lightPlane = new Line( geometry, material );
  29738. this.add( this.lightPlane );
  29739. geometry = new BufferGeometry();
  29740. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29741. this.targetLine = new Line( geometry, material );
  29742. this.add( this.targetLine );
  29743. this.update();
  29744. }
  29745. dispose() {
  29746. this.lightPlane.geometry.dispose();
  29747. this.lightPlane.material.dispose();
  29748. this.targetLine.geometry.dispose();
  29749. this.targetLine.material.dispose();
  29750. }
  29751. update() {
  29752. this.light.updateWorldMatrix( true, false );
  29753. this.light.target.updateWorldMatrix( true, false );
  29754. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29755. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29756. _v3.subVectors( _v2, _v1 );
  29757. this.lightPlane.lookAt( _v2 );
  29758. if ( this.color !== undefined ) {
  29759. this.lightPlane.material.color.set( this.color );
  29760. this.targetLine.material.color.set( this.color );
  29761. } else {
  29762. this.lightPlane.material.color.copy( this.light.color );
  29763. this.targetLine.material.color.copy( this.light.color );
  29764. }
  29765. this.targetLine.lookAt( _v2 );
  29766. this.targetLine.scale.z = _v3.length();
  29767. }
  29768. }
  29769. const _vector = /*@__PURE__*/ new Vector3();
  29770. const _camera = /*@__PURE__*/ new Camera();
  29771. /**
  29772. * - shows frustum, line of sight and up of the camera
  29773. * - suitable for fast updates
  29774. * - based on frustum visualization in lightgl.js shadowmap example
  29775. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29776. */
  29777. class CameraHelper extends LineSegments {
  29778. constructor( camera ) {
  29779. const geometry = new BufferGeometry();
  29780. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29781. const vertices = [];
  29782. const colors = [];
  29783. const pointMap = {};
  29784. // near
  29785. addLine( 'n1', 'n2' );
  29786. addLine( 'n2', 'n4' );
  29787. addLine( 'n4', 'n3' );
  29788. addLine( 'n3', 'n1' );
  29789. // far
  29790. addLine( 'f1', 'f2' );
  29791. addLine( 'f2', 'f4' );
  29792. addLine( 'f4', 'f3' );
  29793. addLine( 'f3', 'f1' );
  29794. // sides
  29795. addLine( 'n1', 'f1' );
  29796. addLine( 'n2', 'f2' );
  29797. addLine( 'n3', 'f3' );
  29798. addLine( 'n4', 'f4' );
  29799. // cone
  29800. addLine( 'p', 'n1' );
  29801. addLine( 'p', 'n2' );
  29802. addLine( 'p', 'n3' );
  29803. addLine( 'p', 'n4' );
  29804. // up
  29805. addLine( 'u1', 'u2' );
  29806. addLine( 'u2', 'u3' );
  29807. addLine( 'u3', 'u1' );
  29808. // target
  29809. addLine( 'c', 't' );
  29810. addLine( 'p', 'c' );
  29811. // cross
  29812. addLine( 'cn1', 'cn2' );
  29813. addLine( 'cn3', 'cn4' );
  29814. addLine( 'cf1', 'cf2' );
  29815. addLine( 'cf3', 'cf4' );
  29816. function addLine( a, b ) {
  29817. addPoint( a );
  29818. addPoint( b );
  29819. }
  29820. function addPoint( id ) {
  29821. vertices.push( 0, 0, 0 );
  29822. colors.push( 0, 0, 0 );
  29823. if ( pointMap[ id ] === undefined ) {
  29824. pointMap[ id ] = [];
  29825. }
  29826. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29827. }
  29828. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29829. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29830. super( geometry, material );
  29831. this.type = 'CameraHelper';
  29832. this.camera = camera;
  29833. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29834. this.matrix = camera.matrixWorld;
  29835. this.matrixAutoUpdate = false;
  29836. this.pointMap = pointMap;
  29837. this.update();
  29838. // colors
  29839. const colorFrustum = new Color( 0xffaa00 );
  29840. const colorCone = new Color( 0xff0000 );
  29841. const colorUp = new Color( 0x00aaff );
  29842. const colorTarget = new Color( 0xffffff );
  29843. const colorCross = new Color( 0x333333 );
  29844. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29845. }
  29846. setColors( frustum, cone, up, target, cross ) {
  29847. const geometry = this.geometry;
  29848. const colorAttribute = geometry.getAttribute( 'color' );
  29849. // near
  29850. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29851. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29852. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29853. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29854. // far
  29855. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29856. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29857. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29858. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29859. // sides
  29860. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29861. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29862. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29863. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29864. // cone
  29865. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29866. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29867. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29868. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29869. // up
  29870. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29871. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29872. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29873. // target
  29874. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29875. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29876. // cross
  29877. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29878. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29879. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29880. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29881. colorAttribute.needsUpdate = true;
  29882. }
  29883. update() {
  29884. const geometry = this.geometry;
  29885. const pointMap = this.pointMap;
  29886. const w = 1, h = 1;
  29887. // we need just camera projection matrix inverse
  29888. // world matrix must be identity
  29889. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29890. // center / target
  29891. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29892. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29893. // near
  29894. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29895. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29896. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29897. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29898. // far
  29899. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29900. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29901. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29902. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29903. // up
  29904. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29905. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29906. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29907. // cross
  29908. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29909. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29910. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29911. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29912. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29913. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29914. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29915. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29916. geometry.getAttribute( 'position' ).needsUpdate = true;
  29917. }
  29918. dispose() {
  29919. this.geometry.dispose();
  29920. this.material.dispose();
  29921. }
  29922. }
  29923. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29924. _vector.set( x, y, z ).unproject( camera );
  29925. const points = pointMap[ point ];
  29926. if ( points !== undefined ) {
  29927. const position = geometry.getAttribute( 'position' );
  29928. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29929. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29930. }
  29931. }
  29932. }
  29933. const _box = /*@__PURE__*/ new Box3();
  29934. class BoxHelper extends LineSegments {
  29935. constructor( object, color = 0xffff00 ) {
  29936. 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 ] );
  29937. const positions = new Float32Array( 8 * 3 );
  29938. const geometry = new BufferGeometry();
  29939. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29940. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29941. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29942. this.object = object;
  29943. this.type = 'BoxHelper';
  29944. this.matrixAutoUpdate = false;
  29945. this.update();
  29946. }
  29947. update( object ) {
  29948. if ( object !== undefined ) {
  29949. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29950. }
  29951. if ( this.object !== undefined ) {
  29952. _box.setFromObject( this.object );
  29953. }
  29954. if ( _box.isEmpty() ) return;
  29955. const min = _box.min;
  29956. const max = _box.max;
  29957. /*
  29958. 5____4
  29959. 1/___0/|
  29960. | 6__|_7
  29961. 2/___3/
  29962. 0: max.x, max.y, max.z
  29963. 1: min.x, max.y, max.z
  29964. 2: min.x, min.y, max.z
  29965. 3: max.x, min.y, max.z
  29966. 4: max.x, max.y, min.z
  29967. 5: min.x, max.y, min.z
  29968. 6: min.x, min.y, min.z
  29969. 7: max.x, min.y, min.z
  29970. */
  29971. const position = this.geometry.attributes.position;
  29972. const array = position.array;
  29973. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29974. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29975. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29976. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29977. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29978. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29979. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29980. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29981. position.needsUpdate = true;
  29982. this.geometry.computeBoundingSphere();
  29983. }
  29984. setFromObject( object ) {
  29985. this.object = object;
  29986. this.update();
  29987. return this;
  29988. }
  29989. copy( source, recursive ) {
  29990. super.copy( source, recursive );
  29991. this.object = source.object;
  29992. return this;
  29993. }
  29994. dispose() {
  29995. this.geometry.dispose();
  29996. this.material.dispose();
  29997. }
  29998. }
  29999. class Box3Helper extends LineSegments {
  30000. constructor( box, color = 0xffff00 ) {
  30001. 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 ] );
  30002. 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 ];
  30003. const geometry = new BufferGeometry();
  30004. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30005. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30006. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30007. this.box = box;
  30008. this.type = 'Box3Helper';
  30009. this.geometry.computeBoundingSphere();
  30010. }
  30011. updateMatrixWorld( force ) {
  30012. const box = this.box;
  30013. if ( box.isEmpty() ) return;
  30014. box.getCenter( this.position );
  30015. box.getSize( this.scale );
  30016. this.scale.multiplyScalar( 0.5 );
  30017. super.updateMatrixWorld( force );
  30018. }
  30019. dispose() {
  30020. this.geometry.dispose();
  30021. this.material.dispose();
  30022. }
  30023. }
  30024. class PlaneHelper extends Line {
  30025. constructor( plane, size = 1, hex = 0xffff00 ) {
  30026. const color = hex;
  30027. 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 ];
  30028. const geometry = new BufferGeometry();
  30029. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30030. geometry.computeBoundingSphere();
  30031. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30032. this.type = 'PlaneHelper';
  30033. this.plane = plane;
  30034. this.size = size;
  30035. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  30036. const geometry2 = new BufferGeometry();
  30037. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  30038. geometry2.computeBoundingSphere();
  30039. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  30040. }
  30041. updateMatrixWorld( force ) {
  30042. this.position.set( 0, 0, 0 );
  30043. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  30044. this.lookAt( this.plane.normal );
  30045. this.translateZ( - this.plane.constant );
  30046. super.updateMatrixWorld( force );
  30047. }
  30048. dispose() {
  30049. this.geometry.dispose();
  30050. this.material.dispose();
  30051. this.children[ 0 ].geometry.dispose();
  30052. this.children[ 0 ].material.dispose();
  30053. }
  30054. }
  30055. const _axis = /*@__PURE__*/ new Vector3();
  30056. let _lineGeometry, _coneGeometry;
  30057. class ArrowHelper extends Object3D {
  30058. // dir is assumed to be normalized
  30059. 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 ) {
  30060. super();
  30061. this.type = 'ArrowHelper';
  30062. if ( _lineGeometry === undefined ) {
  30063. _lineGeometry = new BufferGeometry();
  30064. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  30065. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  30066. _coneGeometry.translate( 0, - 0.5, 0 );
  30067. }
  30068. this.position.copy( origin );
  30069. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  30070. this.line.matrixAutoUpdate = false;
  30071. this.add( this.line );
  30072. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  30073. this.cone.matrixAutoUpdate = false;
  30074. this.add( this.cone );
  30075. this.setDirection( dir );
  30076. this.setLength( length, headLength, headWidth );
  30077. }
  30078. setDirection( dir ) {
  30079. // dir is assumed to be normalized
  30080. if ( dir.y > 0.99999 ) {
  30081. this.quaternion.set( 0, 0, 0, 1 );
  30082. } else if ( dir.y < - 0.99999 ) {
  30083. this.quaternion.set( 1, 0, 0, 0 );
  30084. } else {
  30085. _axis.set( dir.z, 0, - dir.x ).normalize();
  30086. const radians = Math.acos( dir.y );
  30087. this.quaternion.setFromAxisAngle( _axis, radians );
  30088. }
  30089. }
  30090. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  30091. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  30092. this.line.updateMatrix();
  30093. this.cone.scale.set( headWidth, headLength, headWidth );
  30094. this.cone.position.y = length;
  30095. this.cone.updateMatrix();
  30096. }
  30097. setColor( color ) {
  30098. this.line.material.color.set( color );
  30099. this.cone.material.color.set( color );
  30100. }
  30101. copy( source ) {
  30102. super.copy( source, false );
  30103. this.line.copy( source.line );
  30104. this.cone.copy( source.cone );
  30105. return this;
  30106. }
  30107. dispose() {
  30108. this.line.geometry.dispose();
  30109. this.line.material.dispose();
  30110. this.cone.geometry.dispose();
  30111. this.cone.material.dispose();
  30112. }
  30113. }
  30114. class AxesHelper extends LineSegments {
  30115. constructor( size = 1 ) {
  30116. const vertices = [
  30117. 0, 0, 0, size, 0, 0,
  30118. 0, 0, 0, 0, size, 0,
  30119. 0, 0, 0, 0, 0, size
  30120. ];
  30121. const colors = [
  30122. 1, 0, 0, 1, 0.6, 0,
  30123. 0, 1, 0, 0.6, 1, 0,
  30124. 0, 0, 1, 0, 0.6, 1
  30125. ];
  30126. const geometry = new BufferGeometry();
  30127. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30128. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30129. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30130. super( geometry, material );
  30131. this.type = 'AxesHelper';
  30132. }
  30133. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  30134. const color = new Color();
  30135. const array = this.geometry.attributes.color.array;
  30136. color.set( xAxisColor );
  30137. color.toArray( array, 0 );
  30138. color.toArray( array, 3 );
  30139. color.set( yAxisColor );
  30140. color.toArray( array, 6 );
  30141. color.toArray( array, 9 );
  30142. color.set( zAxisColor );
  30143. color.toArray( array, 12 );
  30144. color.toArray( array, 15 );
  30145. this.geometry.attributes.color.needsUpdate = true;
  30146. return this;
  30147. }
  30148. dispose() {
  30149. this.geometry.dispose();
  30150. this.material.dispose();
  30151. }
  30152. }
  30153. class ShapePath {
  30154. constructor() {
  30155. this.type = 'ShapePath';
  30156. this.color = new Color();
  30157. this.subPaths = [];
  30158. this.currentPath = null;
  30159. }
  30160. moveTo( x, y ) {
  30161. this.currentPath = new Path();
  30162. this.subPaths.push( this.currentPath );
  30163. this.currentPath.moveTo( x, y );
  30164. return this;
  30165. }
  30166. lineTo( x, y ) {
  30167. this.currentPath.lineTo( x, y );
  30168. return this;
  30169. }
  30170. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  30171. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  30172. return this;
  30173. }
  30174. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  30175. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  30176. return this;
  30177. }
  30178. splineThru( pts ) {
  30179. this.currentPath.splineThru( pts );
  30180. return this;
  30181. }
  30182. toShapes( isCCW ) {
  30183. function toShapesNoHoles( inSubpaths ) {
  30184. const shapes = [];
  30185. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  30186. const tmpPath = inSubpaths[ i ];
  30187. const tmpShape = new Shape();
  30188. tmpShape.curves = tmpPath.curves;
  30189. shapes.push( tmpShape );
  30190. }
  30191. return shapes;
  30192. }
  30193. function isPointInsidePolygon( inPt, inPolygon ) {
  30194. const polyLen = inPolygon.length;
  30195. // inPt on polygon contour => immediate success or
  30196. // toggling of inside/outside at every single! intersection point of an edge
  30197. // with the horizontal line through inPt, left of inPt
  30198. // not counting lowerY endpoints of edges and whole edges on that line
  30199. let inside = false;
  30200. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  30201. let edgeLowPt = inPolygon[ p ];
  30202. let edgeHighPt = inPolygon[ q ];
  30203. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  30204. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  30205. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  30206. // not parallel
  30207. if ( edgeDy < 0 ) {
  30208. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  30209. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  30210. }
  30211. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  30212. if ( inPt.y === edgeLowPt.y ) {
  30213. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  30214. // continue; // no intersection or edgeLowPt => doesn't count !!!
  30215. } else {
  30216. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  30217. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  30218. if ( perpEdge < 0 ) continue;
  30219. inside = ! inside; // true intersection left of inPt
  30220. }
  30221. } else {
  30222. // parallel or collinear
  30223. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  30224. // edge lies on the same horizontal line as inPt
  30225. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  30226. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  30227. // continue;
  30228. }
  30229. }
  30230. return inside;
  30231. }
  30232. const isClockWise = ShapeUtils.isClockWise;
  30233. const subPaths = this.subPaths;
  30234. if ( subPaths.length === 0 ) return [];
  30235. let solid, tmpPath, tmpShape;
  30236. const shapes = [];
  30237. if ( subPaths.length === 1 ) {
  30238. tmpPath = subPaths[ 0 ];
  30239. tmpShape = new Shape();
  30240. tmpShape.curves = tmpPath.curves;
  30241. shapes.push( tmpShape );
  30242. return shapes;
  30243. }
  30244. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  30245. holesFirst = isCCW ? ! holesFirst : holesFirst;
  30246. // console.log("Holes first", holesFirst);
  30247. const betterShapeHoles = [];
  30248. const newShapes = [];
  30249. let newShapeHoles = [];
  30250. let mainIdx = 0;
  30251. let tmpPoints;
  30252. newShapes[ mainIdx ] = undefined;
  30253. newShapeHoles[ mainIdx ] = [];
  30254. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  30255. tmpPath = subPaths[ i ];
  30256. tmpPoints = tmpPath.getPoints();
  30257. solid = isClockWise( tmpPoints );
  30258. solid = isCCW ? ! solid : solid;
  30259. if ( solid ) {
  30260. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  30261. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  30262. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  30263. if ( holesFirst ) mainIdx ++;
  30264. newShapeHoles[ mainIdx ] = [];
  30265. //console.log('cw', i);
  30266. } else {
  30267. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  30268. //console.log('ccw', i);
  30269. }
  30270. }
  30271. // only Holes? -> probably all Shapes with wrong orientation
  30272. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  30273. if ( newShapes.length > 1 ) {
  30274. let ambiguous = false;
  30275. let toChange = 0;
  30276. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30277. betterShapeHoles[ sIdx ] = [];
  30278. }
  30279. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30280. const sho = newShapeHoles[ sIdx ];
  30281. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  30282. const ho = sho[ hIdx ];
  30283. let hole_unassigned = true;
  30284. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  30285. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  30286. if ( sIdx !== s2Idx ) toChange ++;
  30287. if ( hole_unassigned ) {
  30288. hole_unassigned = false;
  30289. betterShapeHoles[ s2Idx ].push( ho );
  30290. } else {
  30291. ambiguous = true;
  30292. }
  30293. }
  30294. }
  30295. if ( hole_unassigned ) {
  30296. betterShapeHoles[ sIdx ].push( ho );
  30297. }
  30298. }
  30299. }
  30300. if ( toChange > 0 && ambiguous === false ) {
  30301. newShapeHoles = betterShapeHoles;
  30302. }
  30303. }
  30304. let tmpHoles;
  30305. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  30306. tmpShape = newShapes[ i ].s;
  30307. shapes.push( tmpShape );
  30308. tmpHoles = newShapeHoles[ i ];
  30309. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  30310. tmpShape.holes.push( tmpHoles[ j ].h );
  30311. }
  30312. }
  30313. //console.log("shape", shapes);
  30314. return shapes;
  30315. }
  30316. }
  30317. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30318. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30319. revision: REVISION,
  30320. } } ) );
  30321. }
  30322. if ( typeof window !== 'undefined' ) {
  30323. if ( window.__THREE__ ) {
  30324. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30325. } else {
  30326. window.__THREE__ = REVISION;
  30327. }
  30328. }
  30329. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, 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, 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, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearDisplayP3ColorSpace, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, P3Primaries, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, Rec709Primaries, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RenderTarget, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, TwoPassDoubleSide, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, createCanvasElement, sRGBEncoding };