three.cjs 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '153';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const TwoPassDoubleSide = 2; // r149
  22. const NoBlending = 0;
  23. const NormalBlending = 1;
  24. const AdditiveBlending = 2;
  25. const SubtractiveBlending = 3;
  26. const MultiplyBlending = 4;
  27. const CustomBlending = 5;
  28. const AddEquation = 100;
  29. const SubtractEquation = 101;
  30. const ReverseSubtractEquation = 102;
  31. const MinEquation = 103;
  32. const MaxEquation = 104;
  33. const ZeroFactor = 200;
  34. const OneFactor = 201;
  35. const SrcColorFactor = 202;
  36. const OneMinusSrcColorFactor = 203;
  37. const SrcAlphaFactor = 204;
  38. const OneMinusSrcAlphaFactor = 205;
  39. const DstAlphaFactor = 206;
  40. const OneMinusDstAlphaFactor = 207;
  41. const DstColorFactor = 208;
  42. const OneMinusDstColorFactor = 209;
  43. const SrcAlphaSaturateFactor = 210;
  44. const NeverDepth = 0;
  45. const AlwaysDepth = 1;
  46. const LessDepth = 2;
  47. const LessEqualDepth = 3;
  48. const EqualDepth = 4;
  49. const GreaterEqualDepth = 5;
  50. const GreaterDepth = 6;
  51. const NotEqualDepth = 7;
  52. const MultiplyOperation = 0;
  53. const MixOperation = 1;
  54. const AddOperation = 2;
  55. const NoToneMapping = 0;
  56. const LinearToneMapping = 1;
  57. const ReinhardToneMapping = 2;
  58. const CineonToneMapping = 3;
  59. const ACESFilmicToneMapping = 4;
  60. const CustomToneMapping = 5;
  61. const UVMapping = 300;
  62. const CubeReflectionMapping = 301;
  63. const CubeRefractionMapping = 302;
  64. const EquirectangularReflectionMapping = 303;
  65. const EquirectangularRefractionMapping = 304;
  66. const CubeUVReflectionMapping = 306;
  67. const RepeatWrapping = 1000;
  68. const ClampToEdgeWrapping = 1001;
  69. const MirroredRepeatWrapping = 1002;
  70. const NearestFilter = 1003;
  71. const NearestMipmapNearestFilter = 1004;
  72. const NearestMipMapNearestFilter = 1004;
  73. const NearestMipmapLinearFilter = 1005;
  74. const NearestMipMapLinearFilter = 1005;
  75. const LinearFilter = 1006;
  76. const LinearMipmapNearestFilter = 1007;
  77. const LinearMipMapNearestFilter = 1007;
  78. const LinearMipmapLinearFilter = 1008;
  79. const LinearMipMapLinearFilter = 1008;
  80. const UnsignedByteType = 1009;
  81. const ByteType = 1010;
  82. const ShortType = 1011;
  83. const UnsignedShortType = 1012;
  84. const IntType = 1013;
  85. const UnsignedIntType = 1014;
  86. const FloatType = 1015;
  87. const HalfFloatType = 1016;
  88. const UnsignedShort4444Type = 1017;
  89. const UnsignedShort5551Type = 1018;
  90. const UnsignedInt248Type = 1020;
  91. const AlphaFormat = 1021;
  92. const RGBAFormat = 1023;
  93. const LuminanceFormat = 1024;
  94. const LuminanceAlphaFormat = 1025;
  95. const DepthFormat = 1026;
  96. const DepthStencilFormat = 1027;
  97. const RedFormat = 1028;
  98. const RedIntegerFormat = 1029;
  99. const RGFormat = 1030;
  100. const RGIntegerFormat = 1031;
  101. const RGBAIntegerFormat = 1033;
  102. const RGB_S3TC_DXT1_Format = 33776;
  103. const RGBA_S3TC_DXT1_Format = 33777;
  104. const RGBA_S3TC_DXT3_Format = 33778;
  105. const RGBA_S3TC_DXT5_Format = 33779;
  106. const RGB_PVRTC_4BPPV1_Format = 35840;
  107. const RGB_PVRTC_2BPPV1_Format = 35841;
  108. const RGBA_PVRTC_4BPPV1_Format = 35842;
  109. const RGBA_PVRTC_2BPPV1_Format = 35843;
  110. const RGB_ETC1_Format = 36196;
  111. const RGB_ETC2_Format = 37492;
  112. const RGBA_ETC2_EAC_Format = 37496;
  113. const RGBA_ASTC_4x4_Format = 37808;
  114. const RGBA_ASTC_5x4_Format = 37809;
  115. const RGBA_ASTC_5x5_Format = 37810;
  116. const RGBA_ASTC_6x5_Format = 37811;
  117. const RGBA_ASTC_6x6_Format = 37812;
  118. const RGBA_ASTC_8x5_Format = 37813;
  119. const RGBA_ASTC_8x6_Format = 37814;
  120. const RGBA_ASTC_8x8_Format = 37815;
  121. const RGBA_ASTC_10x5_Format = 37816;
  122. const RGBA_ASTC_10x6_Format = 37817;
  123. const RGBA_ASTC_10x8_Format = 37818;
  124. const RGBA_ASTC_10x10_Format = 37819;
  125. const RGBA_ASTC_12x10_Format = 37820;
  126. const RGBA_ASTC_12x12_Format = 37821;
  127. const RGBA_BPTC_Format = 36492;
  128. const RED_RGTC1_Format = 36283;
  129. const SIGNED_RED_RGTC1_Format = 36284;
  130. const RED_GREEN_RGTC2_Format = 36285;
  131. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  132. const LoopOnce = 2200;
  133. const LoopRepeat = 2201;
  134. const LoopPingPong = 2202;
  135. const InterpolateDiscrete = 2300;
  136. const InterpolateLinear = 2301;
  137. const InterpolateSmooth = 2302;
  138. const ZeroCurvatureEnding = 2400;
  139. const ZeroSlopeEnding = 2401;
  140. const WrapAroundEnding = 2402;
  141. const NormalAnimationBlendMode = 2500;
  142. const AdditiveAnimationBlendMode = 2501;
  143. const TrianglesDrawMode = 0;
  144. const TriangleStripDrawMode = 1;
  145. const TriangleFanDrawMode = 2;
  146. /** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */
  147. const LinearEncoding = 3000;
  148. /** @deprecated Use SRGBColorSpace in three.js r152+. */
  149. const sRGBEncoding = 3001;
  150. const BasicDepthPacking = 3200;
  151. const RGBADepthPacking = 3201;
  152. const TangentSpaceNormalMap = 0;
  153. const ObjectSpaceNormalMap = 1;
  154. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  155. const NoColorSpace = '';
  156. const SRGBColorSpace = 'srgb';
  157. const LinearSRGBColorSpace = 'srgb-linear';
  158. const DisplayP3ColorSpace = 'display-p3';
  159. const ZeroStencilOp = 0;
  160. const KeepStencilOp = 7680;
  161. const ReplaceStencilOp = 7681;
  162. const IncrementStencilOp = 7682;
  163. const DecrementStencilOp = 7683;
  164. const IncrementWrapStencilOp = 34055;
  165. const DecrementWrapStencilOp = 34056;
  166. const InvertStencilOp = 5386;
  167. const NeverStencilFunc = 512;
  168. const LessStencilFunc = 513;
  169. const EqualStencilFunc = 514;
  170. const LessEqualStencilFunc = 515;
  171. const GreaterStencilFunc = 516;
  172. const NotEqualStencilFunc = 517;
  173. const GreaterEqualStencilFunc = 518;
  174. const AlwaysStencilFunc = 519;
  175. const NeverCompare = 512;
  176. const LessCompare = 513;
  177. const EqualCompare = 514;
  178. const LessEqualCompare = 515;
  179. const GreaterCompare = 516;
  180. const NotEqualCompare = 517;
  181. const GreaterEqualCompare = 518;
  182. const AlwaysCompare = 519;
  183. const StaticDrawUsage = 35044;
  184. const DynamicDrawUsage = 35048;
  185. const StreamDrawUsage = 35040;
  186. const StaticReadUsage = 35045;
  187. const DynamicReadUsage = 35049;
  188. const StreamReadUsage = 35041;
  189. const StaticCopyUsage = 35046;
  190. const DynamicCopyUsage = 35050;
  191. const StreamCopyUsage = 35042;
  192. const GLSL1 = '100';
  193. const GLSL3 = '300 es';
  194. const _SRGBAFormat = 1035; // fallback for WebGL 1
  195. const WebGLCoordinateSystem = 2000;
  196. const WebGPUCoordinateSystem = 2001;
  197. /**
  198. * https://github.com/mrdoob/eventdispatcher.js/
  199. */
  200. class EventDispatcher {
  201. addEventListener( type, listener ) {
  202. if ( this._listeners === undefined ) this._listeners = {};
  203. const listeners = this._listeners;
  204. if ( listeners[ type ] === undefined ) {
  205. listeners[ type ] = [];
  206. }
  207. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  208. listeners[ type ].push( listener );
  209. }
  210. }
  211. hasEventListener( type, listener ) {
  212. if ( this._listeners === undefined ) return false;
  213. const listeners = this._listeners;
  214. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  215. }
  216. removeEventListener( type, listener ) {
  217. if ( this._listeners === undefined ) return;
  218. const listeners = this._listeners;
  219. const listenerArray = listeners[ type ];
  220. if ( listenerArray !== undefined ) {
  221. const index = listenerArray.indexOf( listener );
  222. if ( index !== - 1 ) {
  223. listenerArray.splice( index, 1 );
  224. }
  225. }
  226. }
  227. dispatchEvent( event ) {
  228. if ( this._listeners === undefined ) return;
  229. const listeners = this._listeners;
  230. const listenerArray = listeners[ event.type ];
  231. if ( listenerArray !== undefined ) {
  232. event.target = this;
  233. // Make a copy, in case listeners are removed while iterating.
  234. const array = listenerArray.slice( 0 );
  235. for ( let i = 0, l = array.length; i < l; i ++ ) {
  236. array[ i ].call( this, event );
  237. }
  238. event.target = null;
  239. }
  240. }
  241. }
  242. 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' ];
  243. let _seed = 1234567;
  244. const DEG2RAD = Math.PI / 180;
  245. const RAD2DEG = 180 / Math.PI;
  246. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  247. function generateUUID() {
  248. const d0 = Math.random() * 0xffffffff | 0;
  249. const d1 = Math.random() * 0xffffffff | 0;
  250. const d2 = Math.random() * 0xffffffff | 0;
  251. const d3 = Math.random() * 0xffffffff | 0;
  252. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  253. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  254. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  255. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  256. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  257. return uuid.toLowerCase();
  258. }
  259. function clamp( value, min, max ) {
  260. return Math.max( min, Math.min( max, value ) );
  261. }
  262. // compute euclidean modulo of m % n
  263. // https://en.wikipedia.org/wiki/Modulo_operation
  264. function euclideanModulo( n, m ) {
  265. return ( ( n % m ) + m ) % m;
  266. }
  267. // Linear mapping from range <a1, a2> to range <b1, b2>
  268. function mapLinear( x, a1, a2, b1, b2 ) {
  269. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  270. }
  271. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  272. function inverseLerp( x, y, value ) {
  273. if ( x !== y ) {
  274. return ( value - x ) / ( y - x );
  275. } else {
  276. return 0;
  277. }
  278. }
  279. // https://en.wikipedia.org/wiki/Linear_interpolation
  280. function lerp( x, y, t ) {
  281. return ( 1 - t ) * x + t * y;
  282. }
  283. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  284. function damp( x, y, lambda, dt ) {
  285. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  286. }
  287. // https://www.desmos.com/calculator/vcsjnyz7x4
  288. function pingpong( x, length = 1 ) {
  289. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  290. }
  291. // http://en.wikipedia.org/wiki/Smoothstep
  292. function smoothstep( x, min, max ) {
  293. if ( x <= min ) return 0;
  294. if ( x >= max ) return 1;
  295. x = ( x - min ) / ( max - min );
  296. return x * x * ( 3 - 2 * x );
  297. }
  298. function smootherstep( 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 * x * ( x * ( x * 6 - 15 ) + 10 );
  303. }
  304. // Random integer from <low, high> interval
  305. function randInt( low, high ) {
  306. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  307. }
  308. // Random float from <low, high> interval
  309. function randFloat( low, high ) {
  310. return low + Math.random() * ( high - low );
  311. }
  312. // Random float from <-range/2, range/2> interval
  313. function randFloatSpread( range ) {
  314. return range * ( 0.5 - Math.random() );
  315. }
  316. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  317. function seededRandom( s ) {
  318. if ( s !== undefined ) _seed = s;
  319. // Mulberry32 generator
  320. let t = _seed += 0x6D2B79F5;
  321. t = Math.imul( t ^ t >>> 15, t | 1 );
  322. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  323. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  324. }
  325. function degToRad( degrees ) {
  326. return degrees * DEG2RAD;
  327. }
  328. function radToDeg( radians ) {
  329. return radians * RAD2DEG;
  330. }
  331. function isPowerOfTwo( value ) {
  332. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  333. }
  334. function ceilPowerOfTwo( value ) {
  335. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  336. }
  337. function floorPowerOfTwo( value ) {
  338. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  339. }
  340. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  341. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  342. // rotations are applied to the axes in the order specified by 'order'
  343. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  344. // angles are in radians
  345. const cos = Math.cos;
  346. const sin = Math.sin;
  347. const c2 = cos( b / 2 );
  348. const s2 = sin( b / 2 );
  349. const c13 = cos( ( a + c ) / 2 );
  350. const s13 = sin( ( a + c ) / 2 );
  351. const c1_3 = cos( ( a - c ) / 2 );
  352. const s1_3 = sin( ( a - c ) / 2 );
  353. const c3_1 = cos( ( c - a ) / 2 );
  354. const s3_1 = sin( ( c - a ) / 2 );
  355. switch ( order ) {
  356. case 'XYX':
  357. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  358. break;
  359. case 'YZY':
  360. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  361. break;
  362. case 'ZXZ':
  363. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  364. break;
  365. case 'XZX':
  366. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  367. break;
  368. case 'YXY':
  369. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  370. break;
  371. case 'ZYZ':
  372. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  373. break;
  374. default:
  375. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  376. }
  377. }
  378. function denormalize( value, array ) {
  379. switch ( array.constructor ) {
  380. case Float32Array:
  381. return value;
  382. case Uint32Array:
  383. return value / 4294967295.0;
  384. case Uint16Array:
  385. return value / 65535.0;
  386. case Uint8Array:
  387. return value / 255.0;
  388. case Int32Array:
  389. return Math.max( value / 2147483647.0, - 1.0 );
  390. case Int16Array:
  391. return Math.max( value / 32767.0, - 1.0 );
  392. case Int8Array:
  393. return Math.max( value / 127.0, - 1.0 );
  394. default:
  395. throw new Error( 'Invalid component type.' );
  396. }
  397. }
  398. function normalize( value, array ) {
  399. switch ( array.constructor ) {
  400. case Float32Array:
  401. return value;
  402. case Uint32Array:
  403. return Math.round( value * 4294967295.0 );
  404. case Uint16Array:
  405. return Math.round( value * 65535.0 );
  406. case Uint8Array:
  407. return Math.round( value * 255.0 );
  408. case Int32Array:
  409. return Math.round( value * 2147483647.0 );
  410. case Int16Array:
  411. return Math.round( value * 32767.0 );
  412. case Int8Array:
  413. return Math.round( value * 127.0 );
  414. default:
  415. throw new Error( 'Invalid component type.' );
  416. }
  417. }
  418. const MathUtils = {
  419. DEG2RAD: DEG2RAD,
  420. RAD2DEG: RAD2DEG,
  421. generateUUID: generateUUID,
  422. clamp: clamp,
  423. euclideanModulo: euclideanModulo,
  424. mapLinear: mapLinear,
  425. inverseLerp: inverseLerp,
  426. lerp: lerp,
  427. damp: damp,
  428. pingpong: pingpong,
  429. smoothstep: smoothstep,
  430. smootherstep: smootherstep,
  431. randInt: randInt,
  432. randFloat: randFloat,
  433. randFloatSpread: randFloatSpread,
  434. seededRandom: seededRandom,
  435. degToRad: degToRad,
  436. radToDeg: radToDeg,
  437. isPowerOfTwo: isPowerOfTwo,
  438. ceilPowerOfTwo: ceilPowerOfTwo,
  439. floorPowerOfTwo: floorPowerOfTwo,
  440. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  441. normalize: normalize,
  442. denormalize: denormalize
  443. };
  444. class Vector2 {
  445. constructor( x = 0, y = 0 ) {
  446. Vector2.prototype.isVector2 = true;
  447. this.x = x;
  448. this.y = y;
  449. }
  450. get width() {
  451. return this.x;
  452. }
  453. set width( value ) {
  454. this.x = value;
  455. }
  456. get height() {
  457. return this.y;
  458. }
  459. set height( value ) {
  460. this.y = value;
  461. }
  462. set( x, y ) {
  463. this.x = x;
  464. this.y = y;
  465. return this;
  466. }
  467. setScalar( scalar ) {
  468. this.x = scalar;
  469. this.y = scalar;
  470. return this;
  471. }
  472. setX( x ) {
  473. this.x = x;
  474. return this;
  475. }
  476. setY( y ) {
  477. this.y = y;
  478. return this;
  479. }
  480. setComponent( index, value ) {
  481. switch ( index ) {
  482. case 0: this.x = value; break;
  483. case 1: this.y = value; break;
  484. default: throw new Error( 'index is out of range: ' + index );
  485. }
  486. return this;
  487. }
  488. getComponent( index ) {
  489. switch ( index ) {
  490. case 0: return this.x;
  491. case 1: return this.y;
  492. default: throw new Error( 'index is out of range: ' + index );
  493. }
  494. }
  495. clone() {
  496. return new this.constructor( this.x, this.y );
  497. }
  498. copy( v ) {
  499. this.x = v.x;
  500. this.y = v.y;
  501. return this;
  502. }
  503. add( v ) {
  504. this.x += v.x;
  505. this.y += v.y;
  506. return this;
  507. }
  508. addScalar( s ) {
  509. this.x += s;
  510. this.y += s;
  511. return this;
  512. }
  513. addVectors( a, b ) {
  514. this.x = a.x + b.x;
  515. this.y = a.y + b.y;
  516. return this;
  517. }
  518. addScaledVector( v, s ) {
  519. this.x += v.x * s;
  520. this.y += v.y * s;
  521. return this;
  522. }
  523. sub( v ) {
  524. this.x -= v.x;
  525. this.y -= v.y;
  526. return this;
  527. }
  528. subScalar( s ) {
  529. this.x -= s;
  530. this.y -= s;
  531. return this;
  532. }
  533. subVectors( a, b ) {
  534. this.x = a.x - b.x;
  535. this.y = a.y - b.y;
  536. return this;
  537. }
  538. multiply( v ) {
  539. this.x *= v.x;
  540. this.y *= v.y;
  541. return this;
  542. }
  543. multiplyScalar( scalar ) {
  544. this.x *= scalar;
  545. this.y *= scalar;
  546. return this;
  547. }
  548. divide( v ) {
  549. this.x /= v.x;
  550. this.y /= v.y;
  551. return this;
  552. }
  553. divideScalar( scalar ) {
  554. return this.multiplyScalar( 1 / scalar );
  555. }
  556. applyMatrix3( m ) {
  557. const x = this.x, y = this.y;
  558. const e = m.elements;
  559. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  560. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  561. return this;
  562. }
  563. min( v ) {
  564. this.x = Math.min( this.x, v.x );
  565. this.y = Math.min( this.y, v.y );
  566. return this;
  567. }
  568. max( v ) {
  569. this.x = Math.max( this.x, v.x );
  570. this.y = Math.max( this.y, v.y );
  571. return this;
  572. }
  573. clamp( min, max ) {
  574. // assumes min < max, componentwise
  575. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  576. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  577. return this;
  578. }
  579. clampScalar( minVal, maxVal ) {
  580. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  581. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  582. return this;
  583. }
  584. clampLength( min, max ) {
  585. const length = this.length();
  586. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  587. }
  588. floor() {
  589. this.x = Math.floor( this.x );
  590. this.y = Math.floor( this.y );
  591. return this;
  592. }
  593. ceil() {
  594. this.x = Math.ceil( this.x );
  595. this.y = Math.ceil( this.y );
  596. return this;
  597. }
  598. round() {
  599. this.x = Math.round( this.x );
  600. this.y = Math.round( this.y );
  601. return this;
  602. }
  603. roundToZero() {
  604. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  605. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  606. return this;
  607. }
  608. negate() {
  609. this.x = - this.x;
  610. this.y = - this.y;
  611. return this;
  612. }
  613. dot( v ) {
  614. return this.x * v.x + this.y * v.y;
  615. }
  616. cross( v ) {
  617. return this.x * v.y - this.y * v.x;
  618. }
  619. lengthSq() {
  620. return this.x * this.x + this.y * this.y;
  621. }
  622. length() {
  623. return Math.sqrt( this.x * this.x + this.y * this.y );
  624. }
  625. manhattanLength() {
  626. return Math.abs( this.x ) + Math.abs( this.y );
  627. }
  628. normalize() {
  629. return this.divideScalar( this.length() || 1 );
  630. }
  631. angle() {
  632. // computes the angle in radians with respect to the positive x-axis
  633. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  634. return angle;
  635. }
  636. angleTo( v ) {
  637. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  638. if ( denominator === 0 ) return Math.PI / 2;
  639. const theta = this.dot( v ) / denominator;
  640. // clamp, to handle numerical problems
  641. return Math.acos( clamp( theta, - 1, 1 ) );
  642. }
  643. distanceTo( v ) {
  644. return Math.sqrt( this.distanceToSquared( v ) );
  645. }
  646. distanceToSquared( v ) {
  647. const dx = this.x - v.x, dy = this.y - v.y;
  648. return dx * dx + dy * dy;
  649. }
  650. manhattanDistanceTo( v ) {
  651. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  652. }
  653. setLength( length ) {
  654. return this.normalize().multiplyScalar( length );
  655. }
  656. lerp( v, alpha ) {
  657. this.x += ( v.x - this.x ) * alpha;
  658. this.y += ( v.y - this.y ) * alpha;
  659. return this;
  660. }
  661. lerpVectors( v1, v2, alpha ) {
  662. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  663. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  664. return this;
  665. }
  666. equals( v ) {
  667. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  668. }
  669. fromArray( array, offset = 0 ) {
  670. this.x = array[ offset ];
  671. this.y = array[ offset + 1 ];
  672. return this;
  673. }
  674. toArray( array = [], offset = 0 ) {
  675. array[ offset ] = this.x;
  676. array[ offset + 1 ] = this.y;
  677. return array;
  678. }
  679. fromBufferAttribute( attribute, index ) {
  680. this.x = attribute.getX( index );
  681. this.y = attribute.getY( index );
  682. return this;
  683. }
  684. rotateAround( center, angle ) {
  685. const c = Math.cos( angle ), s = Math.sin( angle );
  686. const x = this.x - center.x;
  687. const y = this.y - center.y;
  688. this.x = x * c - y * s + center.x;
  689. this.y = x * s + y * c + center.y;
  690. return this;
  691. }
  692. random() {
  693. this.x = Math.random();
  694. this.y = Math.random();
  695. return this;
  696. }
  697. *[ Symbol.iterator ]() {
  698. yield this.x;
  699. yield this.y;
  700. }
  701. }
  702. class Matrix3 {
  703. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  704. Matrix3.prototype.isMatrix3 = true;
  705. this.elements = [
  706. 1, 0, 0,
  707. 0, 1, 0,
  708. 0, 0, 1
  709. ];
  710. if ( n11 !== undefined ) {
  711. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  712. }
  713. }
  714. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  715. const te = this.elements;
  716. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  717. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  718. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  719. return this;
  720. }
  721. identity() {
  722. this.set(
  723. 1, 0, 0,
  724. 0, 1, 0,
  725. 0, 0, 1
  726. );
  727. return this;
  728. }
  729. copy( m ) {
  730. const te = this.elements;
  731. const me = m.elements;
  732. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  733. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  734. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  735. return this;
  736. }
  737. extractBasis( xAxis, yAxis, zAxis ) {
  738. xAxis.setFromMatrix3Column( this, 0 );
  739. yAxis.setFromMatrix3Column( this, 1 );
  740. zAxis.setFromMatrix3Column( this, 2 );
  741. return this;
  742. }
  743. setFromMatrix4( m ) {
  744. const me = m.elements;
  745. this.set(
  746. me[ 0 ], me[ 4 ], me[ 8 ],
  747. me[ 1 ], me[ 5 ], me[ 9 ],
  748. me[ 2 ], me[ 6 ], me[ 10 ]
  749. );
  750. return this;
  751. }
  752. multiply( m ) {
  753. return this.multiplyMatrices( this, m );
  754. }
  755. premultiply( m ) {
  756. return this.multiplyMatrices( m, this );
  757. }
  758. multiplyMatrices( a, b ) {
  759. const ae = a.elements;
  760. const be = b.elements;
  761. const te = this.elements;
  762. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  763. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  764. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  765. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  766. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  767. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  768. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  769. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  770. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  771. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  772. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  773. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  774. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  775. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  776. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  777. return this;
  778. }
  779. multiplyScalar( s ) {
  780. const te = this.elements;
  781. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  782. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  783. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  784. return this;
  785. }
  786. determinant() {
  787. const te = this.elements;
  788. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  789. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  790. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  791. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  792. }
  793. invert() {
  794. const te = this.elements,
  795. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  796. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  797. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  798. t11 = n33 * n22 - n32 * n23,
  799. t12 = n32 * n13 - n33 * n12,
  800. t13 = n23 * n12 - n22 * n13,
  801. det = n11 * t11 + n21 * t12 + n31 * t13;
  802. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  803. const detInv = 1 / det;
  804. te[ 0 ] = t11 * detInv;
  805. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  806. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  807. te[ 3 ] = t12 * detInv;
  808. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  809. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  810. te[ 6 ] = t13 * detInv;
  811. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  812. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  813. return this;
  814. }
  815. transpose() {
  816. let tmp;
  817. const m = this.elements;
  818. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  819. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  820. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  821. return this;
  822. }
  823. getNormalMatrix( matrix4 ) {
  824. return this.setFromMatrix4( matrix4 ).invert().transpose();
  825. }
  826. transposeIntoArray( r ) {
  827. const m = this.elements;
  828. r[ 0 ] = m[ 0 ];
  829. r[ 1 ] = m[ 3 ];
  830. r[ 2 ] = m[ 6 ];
  831. r[ 3 ] = m[ 1 ];
  832. r[ 4 ] = m[ 4 ];
  833. r[ 5 ] = m[ 7 ];
  834. r[ 6 ] = m[ 2 ];
  835. r[ 7 ] = m[ 5 ];
  836. r[ 8 ] = m[ 8 ];
  837. return this;
  838. }
  839. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  840. const c = Math.cos( rotation );
  841. const s = Math.sin( rotation );
  842. this.set(
  843. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  844. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  845. 0, 0, 1
  846. );
  847. return this;
  848. }
  849. //
  850. scale( sx, sy ) {
  851. this.premultiply( _m3.makeScale( sx, sy ) );
  852. return this;
  853. }
  854. rotate( theta ) {
  855. this.premultiply( _m3.makeRotation( - theta ) );
  856. return this;
  857. }
  858. translate( tx, ty ) {
  859. this.premultiply( _m3.makeTranslation( tx, ty ) );
  860. return this;
  861. }
  862. // for 2D Transforms
  863. makeTranslation( x, y ) {
  864. if ( x.isVector2 ) {
  865. this.set(
  866. 1, 0, x.x,
  867. 0, 1, x.y,
  868. 0, 0, 1
  869. );
  870. } else {
  871. this.set(
  872. 1, 0, x,
  873. 0, 1, y,
  874. 0, 0, 1
  875. );
  876. }
  877. return this;
  878. }
  879. makeRotation( theta ) {
  880. // counterclockwise
  881. const c = Math.cos( theta );
  882. const s = Math.sin( theta );
  883. this.set(
  884. c, - s, 0,
  885. s, c, 0,
  886. 0, 0, 1
  887. );
  888. return this;
  889. }
  890. makeScale( x, y ) {
  891. this.set(
  892. x, 0, 0,
  893. 0, y, 0,
  894. 0, 0, 1
  895. );
  896. return this;
  897. }
  898. //
  899. equals( matrix ) {
  900. const te = this.elements;
  901. const me = matrix.elements;
  902. for ( let i = 0; i < 9; i ++ ) {
  903. if ( te[ i ] !== me[ i ] ) return false;
  904. }
  905. return true;
  906. }
  907. fromArray( array, offset = 0 ) {
  908. for ( let i = 0; i < 9; i ++ ) {
  909. this.elements[ i ] = array[ i + offset ];
  910. }
  911. return this;
  912. }
  913. toArray( array = [], offset = 0 ) {
  914. const te = this.elements;
  915. array[ offset ] = te[ 0 ];
  916. array[ offset + 1 ] = te[ 1 ];
  917. array[ offset + 2 ] = te[ 2 ];
  918. array[ offset + 3 ] = te[ 3 ];
  919. array[ offset + 4 ] = te[ 4 ];
  920. array[ offset + 5 ] = te[ 5 ];
  921. array[ offset + 6 ] = te[ 6 ];
  922. array[ offset + 7 ] = te[ 7 ];
  923. array[ offset + 8 ] = te[ 8 ];
  924. return array;
  925. }
  926. clone() {
  927. return new this.constructor().fromArray( this.elements );
  928. }
  929. }
  930. const _m3 = /*@__PURE__*/ new Matrix3();
  931. function arrayNeedsUint32( array ) {
  932. // assumes larger values usually on last
  933. for ( let i = array.length - 1; i >= 0; -- i ) {
  934. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  935. }
  936. return false;
  937. }
  938. const TYPED_ARRAYS = {
  939. Int8Array: Int8Array,
  940. Uint8Array: Uint8Array,
  941. Uint8ClampedArray: Uint8ClampedArray,
  942. Int16Array: Int16Array,
  943. Uint16Array: Uint16Array,
  944. Int32Array: Int32Array,
  945. Uint32Array: Uint32Array,
  946. Float32Array: Float32Array,
  947. Float64Array: Float64Array
  948. };
  949. function getTypedArray( type, buffer ) {
  950. return new TYPED_ARRAYS[ type ]( buffer );
  951. }
  952. function createElementNS( name ) {
  953. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  954. }
  955. const _cache = {};
  956. function warnOnce( message ) {
  957. if ( message in _cache ) return;
  958. _cache[ message ] = true;
  959. console.warn( message );
  960. }
  961. function SRGBToLinear( c ) {
  962. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  963. }
  964. function LinearToSRGB( c ) {
  965. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  966. }
  967. /**
  968. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  969. * or clipping. Based on W3C specifications for sRGB and Display P3,
  970. * and ICC specifications for the D50 connection space. Values in/out
  971. * are _linear_ sRGB and _linear_ Display P3.
  972. *
  973. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  974. *
  975. * Reference:
  976. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  977. */
  978. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [
  979. 0.8224621, 0.0331941, 0.0170827,
  980. 0.1775380, 0.9668058, 0.0723974,
  981. - 0.0000001, 0.0000001, 0.9105199
  982. ] );
  983. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [
  984. 1.2249401, - 0.0420569, - 0.0196376,
  985. - 0.2249404, 1.0420571, - 0.0786361,
  986. 0.0000001, 0.0000000, 1.0982735
  987. ] );
  988. function DisplayP3ToLinearSRGB( color ) {
  989. // Display P3 uses the sRGB transfer functions
  990. return color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  991. }
  992. function LinearSRGBToDisplayP3( color ) {
  993. // Display P3 uses the sRGB transfer functions
  994. return color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB();
  995. }
  996. // Conversions from <source> to Linear-sRGB reference space.
  997. const TO_LINEAR = {
  998. [ LinearSRGBColorSpace ]: ( color ) => color,
  999. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  1000. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  1001. };
  1002. // Conversions to <target> from Linear-sRGB reference space.
  1003. const FROM_LINEAR = {
  1004. [ LinearSRGBColorSpace ]: ( color ) => color,
  1005. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  1006. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  1007. };
  1008. const ColorManagement = {
  1009. enabled: true,
  1010. get legacyMode() {
  1011. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1012. return ! this.enabled;
  1013. },
  1014. set legacyMode( legacyMode ) {
  1015. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1016. this.enabled = ! legacyMode;
  1017. },
  1018. get workingColorSpace() {
  1019. return LinearSRGBColorSpace;
  1020. },
  1021. set workingColorSpace( colorSpace ) {
  1022. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  1023. },
  1024. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1025. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1026. return color;
  1027. }
  1028. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  1029. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  1030. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  1031. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  1032. }
  1033. return targetFromLinear( sourceToLinear( color ) );
  1034. },
  1035. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1036. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1037. },
  1038. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1039. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1040. },
  1041. };
  1042. let _canvas;
  1043. class ImageUtils {
  1044. static getDataURL( image ) {
  1045. if ( /^data:/i.test( image.src ) ) {
  1046. return image.src;
  1047. }
  1048. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1049. return image.src;
  1050. }
  1051. let canvas;
  1052. if ( image instanceof HTMLCanvasElement ) {
  1053. canvas = image;
  1054. } else {
  1055. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1056. _canvas.width = image.width;
  1057. _canvas.height = image.height;
  1058. const context = _canvas.getContext( '2d' );
  1059. if ( image instanceof ImageData ) {
  1060. context.putImageData( image, 0, 0 );
  1061. } else {
  1062. context.drawImage( image, 0, 0, image.width, image.height );
  1063. }
  1064. canvas = _canvas;
  1065. }
  1066. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1067. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1068. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1069. } else {
  1070. return canvas.toDataURL( 'image/png' );
  1071. }
  1072. }
  1073. static sRGBToLinear( image ) {
  1074. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1075. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1076. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1077. const canvas = createElementNS( 'canvas' );
  1078. canvas.width = image.width;
  1079. canvas.height = image.height;
  1080. const context = canvas.getContext( '2d' );
  1081. context.drawImage( image, 0, 0, image.width, image.height );
  1082. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1083. const data = imageData.data;
  1084. for ( let i = 0; i < data.length; i ++ ) {
  1085. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1086. }
  1087. context.putImageData( imageData, 0, 0 );
  1088. return canvas;
  1089. } else if ( image.data ) {
  1090. const data = image.data.slice( 0 );
  1091. for ( let i = 0; i < data.length; i ++ ) {
  1092. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1093. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1094. } else {
  1095. // assuming float
  1096. data[ i ] = SRGBToLinear( data[ i ] );
  1097. }
  1098. }
  1099. return {
  1100. data: data,
  1101. width: image.width,
  1102. height: image.height
  1103. };
  1104. } else {
  1105. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1106. return image;
  1107. }
  1108. }
  1109. }
  1110. let sourceId = 0;
  1111. class Source {
  1112. constructor( data = null ) {
  1113. this.isSource = true;
  1114. Object.defineProperty( this, 'id', { value: sourceId ++ } );
  1115. this.uuid = generateUUID();
  1116. this.data = data;
  1117. this.version = 0;
  1118. }
  1119. set needsUpdate( value ) {
  1120. if ( value === true ) this.version ++;
  1121. }
  1122. toJSON( meta ) {
  1123. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1124. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1125. return meta.images[ this.uuid ];
  1126. }
  1127. const output = {
  1128. uuid: this.uuid,
  1129. url: ''
  1130. };
  1131. const data = this.data;
  1132. if ( data !== null ) {
  1133. let url;
  1134. if ( Array.isArray( data ) ) {
  1135. // cube texture
  1136. url = [];
  1137. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1138. if ( data[ i ].isDataTexture ) {
  1139. url.push( serializeImage( data[ i ].image ) );
  1140. } else {
  1141. url.push( serializeImage( data[ i ] ) );
  1142. }
  1143. }
  1144. } else {
  1145. // texture
  1146. url = serializeImage( data );
  1147. }
  1148. output.url = url;
  1149. }
  1150. if ( ! isRootObject ) {
  1151. meta.images[ this.uuid ] = output;
  1152. }
  1153. return output;
  1154. }
  1155. }
  1156. function serializeImage( image ) {
  1157. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1158. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1159. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1160. // default images
  1161. return ImageUtils.getDataURL( image );
  1162. } else {
  1163. if ( image.data ) {
  1164. // images of DataTexture
  1165. return {
  1166. data: Array.from( image.data ),
  1167. width: image.width,
  1168. height: image.height,
  1169. type: image.data.constructor.name
  1170. };
  1171. } else {
  1172. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1173. return {};
  1174. }
  1175. }
  1176. }
  1177. let textureId = 0;
  1178. class Texture extends EventDispatcher {
  1179. 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 ) {
  1180. super();
  1181. this.isTexture = true;
  1182. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1183. this.uuid = generateUUID();
  1184. this.name = '';
  1185. this.source = new Source( image );
  1186. this.mipmaps = [];
  1187. this.mapping = mapping;
  1188. this.channel = 0;
  1189. this.wrapS = wrapS;
  1190. this.wrapT = wrapT;
  1191. this.magFilter = magFilter;
  1192. this.minFilter = minFilter;
  1193. this.anisotropy = anisotropy;
  1194. this.format = format;
  1195. this.internalFormat = null;
  1196. this.type = type;
  1197. this.offset = new Vector2( 0, 0 );
  1198. this.repeat = new Vector2( 1, 1 );
  1199. this.center = new Vector2( 0, 0 );
  1200. this.rotation = 0;
  1201. this.matrixAutoUpdate = true;
  1202. this.matrix = new Matrix3();
  1203. this.generateMipmaps = true;
  1204. this.premultiplyAlpha = false;
  1205. this.flipY = true;
  1206. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1207. if ( typeof colorSpace === 'string' ) {
  1208. this.colorSpace = colorSpace;
  1209. } else { // @deprecated, r152
  1210. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1211. this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1212. }
  1213. this.userData = {};
  1214. this.version = 0;
  1215. this.onUpdate = null;
  1216. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1217. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1218. }
  1219. get image() {
  1220. return this.source.data;
  1221. }
  1222. set image( value = null ) {
  1223. this.source.data = value;
  1224. }
  1225. updateMatrix() {
  1226. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1227. }
  1228. clone() {
  1229. return new this.constructor().copy( this );
  1230. }
  1231. copy( source ) {
  1232. this.name = source.name;
  1233. this.source = source.source;
  1234. this.mipmaps = source.mipmaps.slice( 0 );
  1235. this.mapping = source.mapping;
  1236. this.channel = source.channel;
  1237. this.wrapS = source.wrapS;
  1238. this.wrapT = source.wrapT;
  1239. this.magFilter = source.magFilter;
  1240. this.minFilter = source.minFilter;
  1241. this.anisotropy = source.anisotropy;
  1242. this.format = source.format;
  1243. this.internalFormat = source.internalFormat;
  1244. this.type = source.type;
  1245. this.offset.copy( source.offset );
  1246. this.repeat.copy( source.repeat );
  1247. this.center.copy( source.center );
  1248. this.rotation = source.rotation;
  1249. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1250. this.matrix.copy( source.matrix );
  1251. this.generateMipmaps = source.generateMipmaps;
  1252. this.premultiplyAlpha = source.premultiplyAlpha;
  1253. this.flipY = source.flipY;
  1254. this.unpackAlignment = source.unpackAlignment;
  1255. this.colorSpace = source.colorSpace;
  1256. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1257. this.needsUpdate = true;
  1258. return this;
  1259. }
  1260. toJSON( meta ) {
  1261. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1262. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1263. return meta.textures[ this.uuid ];
  1264. }
  1265. const output = {
  1266. metadata: {
  1267. version: 4.6,
  1268. type: 'Texture',
  1269. generator: 'Texture.toJSON'
  1270. },
  1271. uuid: this.uuid,
  1272. name: this.name,
  1273. image: this.source.toJSON( meta ).uuid,
  1274. mapping: this.mapping,
  1275. channel: this.channel,
  1276. repeat: [ this.repeat.x, this.repeat.y ],
  1277. offset: [ this.offset.x, this.offset.y ],
  1278. center: [ this.center.x, this.center.y ],
  1279. rotation: this.rotation,
  1280. wrap: [ this.wrapS, this.wrapT ],
  1281. format: this.format,
  1282. internalFormat: this.internalFormat,
  1283. type: this.type,
  1284. colorSpace: this.colorSpace,
  1285. minFilter: this.minFilter,
  1286. magFilter: this.magFilter,
  1287. anisotropy: this.anisotropy,
  1288. flipY: this.flipY,
  1289. generateMipmaps: this.generateMipmaps,
  1290. premultiplyAlpha: this.premultiplyAlpha,
  1291. unpackAlignment: this.unpackAlignment
  1292. };
  1293. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1294. if ( ! isRootObject ) {
  1295. meta.textures[ this.uuid ] = output;
  1296. }
  1297. return output;
  1298. }
  1299. dispose() {
  1300. this.dispatchEvent( { type: 'dispose' } );
  1301. }
  1302. transformUv( uv ) {
  1303. if ( this.mapping !== UVMapping ) return uv;
  1304. uv.applyMatrix3( this.matrix );
  1305. if ( uv.x < 0 || uv.x > 1 ) {
  1306. switch ( this.wrapS ) {
  1307. case RepeatWrapping:
  1308. uv.x = uv.x - Math.floor( uv.x );
  1309. break;
  1310. case ClampToEdgeWrapping:
  1311. uv.x = uv.x < 0 ? 0 : 1;
  1312. break;
  1313. case MirroredRepeatWrapping:
  1314. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1315. uv.x = Math.ceil( uv.x ) - uv.x;
  1316. } else {
  1317. uv.x = uv.x - Math.floor( uv.x );
  1318. }
  1319. break;
  1320. }
  1321. }
  1322. if ( uv.y < 0 || uv.y > 1 ) {
  1323. switch ( this.wrapT ) {
  1324. case RepeatWrapping:
  1325. uv.y = uv.y - Math.floor( uv.y );
  1326. break;
  1327. case ClampToEdgeWrapping:
  1328. uv.y = uv.y < 0 ? 0 : 1;
  1329. break;
  1330. case MirroredRepeatWrapping:
  1331. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1332. uv.y = Math.ceil( uv.y ) - uv.y;
  1333. } else {
  1334. uv.y = uv.y - Math.floor( uv.y );
  1335. }
  1336. break;
  1337. }
  1338. }
  1339. if ( this.flipY ) {
  1340. uv.y = 1 - uv.y;
  1341. }
  1342. return uv;
  1343. }
  1344. set needsUpdate( value ) {
  1345. if ( value === true ) {
  1346. this.version ++;
  1347. this.source.needsUpdate = true;
  1348. }
  1349. }
  1350. get encoding() { // @deprecated, r152
  1351. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1352. return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  1353. }
  1354. set encoding( encoding ) { // @deprecated, r152
  1355. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1356. this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1357. }
  1358. }
  1359. Texture.DEFAULT_IMAGE = null;
  1360. Texture.DEFAULT_MAPPING = UVMapping;
  1361. Texture.DEFAULT_ANISOTROPY = 1;
  1362. class Vector4 {
  1363. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1364. Vector4.prototype.isVector4 = true;
  1365. this.x = x;
  1366. this.y = y;
  1367. this.z = z;
  1368. this.w = w;
  1369. }
  1370. get width() {
  1371. return this.z;
  1372. }
  1373. set width( value ) {
  1374. this.z = value;
  1375. }
  1376. get height() {
  1377. return this.w;
  1378. }
  1379. set height( value ) {
  1380. this.w = value;
  1381. }
  1382. set( x, y, z, w ) {
  1383. this.x = x;
  1384. this.y = y;
  1385. this.z = z;
  1386. this.w = w;
  1387. return this;
  1388. }
  1389. setScalar( scalar ) {
  1390. this.x = scalar;
  1391. this.y = scalar;
  1392. this.z = scalar;
  1393. this.w = scalar;
  1394. return this;
  1395. }
  1396. setX( x ) {
  1397. this.x = x;
  1398. return this;
  1399. }
  1400. setY( y ) {
  1401. this.y = y;
  1402. return this;
  1403. }
  1404. setZ( z ) {
  1405. this.z = z;
  1406. return this;
  1407. }
  1408. setW( w ) {
  1409. this.w = w;
  1410. return this;
  1411. }
  1412. setComponent( index, value ) {
  1413. switch ( index ) {
  1414. case 0: this.x = value; break;
  1415. case 1: this.y = value; break;
  1416. case 2: this.z = value; break;
  1417. case 3: this.w = value; break;
  1418. default: throw new Error( 'index is out of range: ' + index );
  1419. }
  1420. return this;
  1421. }
  1422. getComponent( index ) {
  1423. switch ( index ) {
  1424. case 0: return this.x;
  1425. case 1: return this.y;
  1426. case 2: return this.z;
  1427. case 3: return this.w;
  1428. default: throw new Error( 'index is out of range: ' + index );
  1429. }
  1430. }
  1431. clone() {
  1432. return new this.constructor( this.x, this.y, this.z, this.w );
  1433. }
  1434. copy( v ) {
  1435. this.x = v.x;
  1436. this.y = v.y;
  1437. this.z = v.z;
  1438. this.w = ( v.w !== undefined ) ? v.w : 1;
  1439. return this;
  1440. }
  1441. add( v ) {
  1442. this.x += v.x;
  1443. this.y += v.y;
  1444. this.z += v.z;
  1445. this.w += v.w;
  1446. return this;
  1447. }
  1448. addScalar( s ) {
  1449. this.x += s;
  1450. this.y += s;
  1451. this.z += s;
  1452. this.w += s;
  1453. return this;
  1454. }
  1455. addVectors( a, b ) {
  1456. this.x = a.x + b.x;
  1457. this.y = a.y + b.y;
  1458. this.z = a.z + b.z;
  1459. this.w = a.w + b.w;
  1460. return this;
  1461. }
  1462. addScaledVector( v, s ) {
  1463. this.x += v.x * s;
  1464. this.y += v.y * s;
  1465. this.z += v.z * s;
  1466. this.w += v.w * s;
  1467. return this;
  1468. }
  1469. sub( v ) {
  1470. this.x -= v.x;
  1471. this.y -= v.y;
  1472. this.z -= v.z;
  1473. this.w -= v.w;
  1474. return this;
  1475. }
  1476. subScalar( s ) {
  1477. this.x -= s;
  1478. this.y -= s;
  1479. this.z -= s;
  1480. this.w -= s;
  1481. return this;
  1482. }
  1483. subVectors( a, b ) {
  1484. this.x = a.x - b.x;
  1485. this.y = a.y - b.y;
  1486. this.z = a.z - b.z;
  1487. this.w = a.w - b.w;
  1488. return this;
  1489. }
  1490. multiply( v ) {
  1491. this.x *= v.x;
  1492. this.y *= v.y;
  1493. this.z *= v.z;
  1494. this.w *= v.w;
  1495. return this;
  1496. }
  1497. multiplyScalar( scalar ) {
  1498. this.x *= scalar;
  1499. this.y *= scalar;
  1500. this.z *= scalar;
  1501. this.w *= scalar;
  1502. return this;
  1503. }
  1504. applyMatrix4( m ) {
  1505. const x = this.x, y = this.y, z = this.z, w = this.w;
  1506. const e = m.elements;
  1507. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1508. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1509. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1510. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1511. return this;
  1512. }
  1513. divideScalar( scalar ) {
  1514. return this.multiplyScalar( 1 / scalar );
  1515. }
  1516. setAxisAngleFromQuaternion( q ) {
  1517. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1518. // q is assumed to be normalized
  1519. this.w = 2 * Math.acos( q.w );
  1520. const s = Math.sqrt( 1 - q.w * q.w );
  1521. if ( s < 0.0001 ) {
  1522. this.x = 1;
  1523. this.y = 0;
  1524. this.z = 0;
  1525. } else {
  1526. this.x = q.x / s;
  1527. this.y = q.y / s;
  1528. this.z = q.z / s;
  1529. }
  1530. return this;
  1531. }
  1532. setAxisAngleFromRotationMatrix( m ) {
  1533. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1534. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1535. let angle, x, y, z; // variables for result
  1536. const epsilon = 0.01, // margin to allow for rounding errors
  1537. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1538. te = m.elements,
  1539. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1540. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1541. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1542. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1543. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1544. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1545. // singularity found
  1546. // first check for identity matrix which must have +1 for all terms
  1547. // in leading diagonal and zero in other terms
  1548. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1549. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1550. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1551. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1552. // this singularity is identity matrix so angle = 0
  1553. this.set( 1, 0, 0, 0 );
  1554. return this; // zero angle, arbitrary axis
  1555. }
  1556. // otherwise this singularity is angle = 180
  1557. angle = Math.PI;
  1558. const xx = ( m11 + 1 ) / 2;
  1559. const yy = ( m22 + 1 ) / 2;
  1560. const zz = ( m33 + 1 ) / 2;
  1561. const xy = ( m12 + m21 ) / 4;
  1562. const xz = ( m13 + m31 ) / 4;
  1563. const yz = ( m23 + m32 ) / 4;
  1564. if ( ( xx > yy ) && ( xx > zz ) ) {
  1565. // m11 is the largest diagonal term
  1566. if ( xx < epsilon ) {
  1567. x = 0;
  1568. y = 0.707106781;
  1569. z = 0.707106781;
  1570. } else {
  1571. x = Math.sqrt( xx );
  1572. y = xy / x;
  1573. z = xz / x;
  1574. }
  1575. } else if ( yy > zz ) {
  1576. // m22 is the largest diagonal term
  1577. if ( yy < epsilon ) {
  1578. x = 0.707106781;
  1579. y = 0;
  1580. z = 0.707106781;
  1581. } else {
  1582. y = Math.sqrt( yy );
  1583. x = xy / y;
  1584. z = yz / y;
  1585. }
  1586. } else {
  1587. // m33 is the largest diagonal term so base result on this
  1588. if ( zz < epsilon ) {
  1589. x = 0.707106781;
  1590. y = 0.707106781;
  1591. z = 0;
  1592. } else {
  1593. z = Math.sqrt( zz );
  1594. x = xz / z;
  1595. y = yz / z;
  1596. }
  1597. }
  1598. this.set( x, y, z, angle );
  1599. return this; // return 180 deg rotation
  1600. }
  1601. // as we have reached here there are no singularities so we can handle normally
  1602. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1603. ( m13 - m31 ) * ( m13 - m31 ) +
  1604. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1605. if ( Math.abs( s ) < 0.001 ) s = 1;
  1606. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1607. // caught by singularity test above, but I've left it in just in case
  1608. this.x = ( m32 - m23 ) / s;
  1609. this.y = ( m13 - m31 ) / s;
  1610. this.z = ( m21 - m12 ) / s;
  1611. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1612. return this;
  1613. }
  1614. min( v ) {
  1615. this.x = Math.min( this.x, v.x );
  1616. this.y = Math.min( this.y, v.y );
  1617. this.z = Math.min( this.z, v.z );
  1618. this.w = Math.min( this.w, v.w );
  1619. return this;
  1620. }
  1621. max( v ) {
  1622. this.x = Math.max( this.x, v.x );
  1623. this.y = Math.max( this.y, v.y );
  1624. this.z = Math.max( this.z, v.z );
  1625. this.w = Math.max( this.w, v.w );
  1626. return this;
  1627. }
  1628. clamp( min, max ) {
  1629. // assumes min < max, componentwise
  1630. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1631. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1632. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1633. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1634. return this;
  1635. }
  1636. clampScalar( minVal, maxVal ) {
  1637. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1638. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1639. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1640. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1641. return this;
  1642. }
  1643. clampLength( min, max ) {
  1644. const length = this.length();
  1645. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1646. }
  1647. floor() {
  1648. this.x = Math.floor( this.x );
  1649. this.y = Math.floor( this.y );
  1650. this.z = Math.floor( this.z );
  1651. this.w = Math.floor( this.w );
  1652. return this;
  1653. }
  1654. ceil() {
  1655. this.x = Math.ceil( this.x );
  1656. this.y = Math.ceil( this.y );
  1657. this.z = Math.ceil( this.z );
  1658. this.w = Math.ceil( this.w );
  1659. return this;
  1660. }
  1661. round() {
  1662. this.x = Math.round( this.x );
  1663. this.y = Math.round( this.y );
  1664. this.z = Math.round( this.z );
  1665. this.w = Math.round( this.w );
  1666. return this;
  1667. }
  1668. roundToZero() {
  1669. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1670. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1671. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1672. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1673. return this;
  1674. }
  1675. negate() {
  1676. this.x = - this.x;
  1677. this.y = - this.y;
  1678. this.z = - this.z;
  1679. this.w = - this.w;
  1680. return this;
  1681. }
  1682. dot( v ) {
  1683. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1684. }
  1685. lengthSq() {
  1686. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1687. }
  1688. length() {
  1689. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1690. }
  1691. manhattanLength() {
  1692. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1693. }
  1694. normalize() {
  1695. return this.divideScalar( this.length() || 1 );
  1696. }
  1697. setLength( length ) {
  1698. return this.normalize().multiplyScalar( length );
  1699. }
  1700. lerp( v, alpha ) {
  1701. this.x += ( v.x - this.x ) * alpha;
  1702. this.y += ( v.y - this.y ) * alpha;
  1703. this.z += ( v.z - this.z ) * alpha;
  1704. this.w += ( v.w - this.w ) * alpha;
  1705. return this;
  1706. }
  1707. lerpVectors( v1, v2, alpha ) {
  1708. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1709. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1710. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1711. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1712. return this;
  1713. }
  1714. equals( v ) {
  1715. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1716. }
  1717. fromArray( array, offset = 0 ) {
  1718. this.x = array[ offset ];
  1719. this.y = array[ offset + 1 ];
  1720. this.z = array[ offset + 2 ];
  1721. this.w = array[ offset + 3 ];
  1722. return this;
  1723. }
  1724. toArray( array = [], offset = 0 ) {
  1725. array[ offset ] = this.x;
  1726. array[ offset + 1 ] = this.y;
  1727. array[ offset + 2 ] = this.z;
  1728. array[ offset + 3 ] = this.w;
  1729. return array;
  1730. }
  1731. fromBufferAttribute( attribute, index ) {
  1732. this.x = attribute.getX( index );
  1733. this.y = attribute.getY( index );
  1734. this.z = attribute.getZ( index );
  1735. this.w = attribute.getW( index );
  1736. return this;
  1737. }
  1738. random() {
  1739. this.x = Math.random();
  1740. this.y = Math.random();
  1741. this.z = Math.random();
  1742. this.w = Math.random();
  1743. return this;
  1744. }
  1745. *[ Symbol.iterator ]() {
  1746. yield this.x;
  1747. yield this.y;
  1748. yield this.z;
  1749. yield this.w;
  1750. }
  1751. }
  1752. /*
  1753. In options, we can specify:
  1754. * Texture parameters for an auto-generated target texture
  1755. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1756. */
  1757. class WebGLRenderTarget extends EventDispatcher {
  1758. constructor( width = 1, height = 1, options = {} ) {
  1759. super();
  1760. this.isWebGLRenderTarget = true;
  1761. this.width = width;
  1762. this.height = height;
  1763. this.depth = 1;
  1764. this.scissor = new Vector4( 0, 0, width, height );
  1765. this.scissorTest = false;
  1766. this.viewport = new Vector4( 0, 0, width, height );
  1767. const image = { width: width, height: height, depth: 1 };
  1768. if ( options.encoding !== undefined ) {
  1769. // @deprecated, r152
  1770. warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  1771. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1772. }
  1773. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1774. this.texture.isRenderTargetTexture = true;
  1775. this.texture.flipY = false;
  1776. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1777. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1778. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1779. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1780. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1781. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1782. this.samples = options.samples !== undefined ? options.samples : 0;
  1783. }
  1784. setSize( width, height, depth = 1 ) {
  1785. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1786. this.width = width;
  1787. this.height = height;
  1788. this.depth = depth;
  1789. this.texture.image.width = width;
  1790. this.texture.image.height = height;
  1791. this.texture.image.depth = depth;
  1792. this.dispose();
  1793. }
  1794. this.viewport.set( 0, 0, width, height );
  1795. this.scissor.set( 0, 0, width, height );
  1796. }
  1797. clone() {
  1798. return new this.constructor().copy( this );
  1799. }
  1800. copy( source ) {
  1801. this.width = source.width;
  1802. this.height = source.height;
  1803. this.depth = source.depth;
  1804. this.scissor.copy( source.scissor );
  1805. this.scissorTest = source.scissorTest;
  1806. this.viewport.copy( source.viewport );
  1807. this.texture = source.texture.clone();
  1808. this.texture.isRenderTargetTexture = true;
  1809. // ensure image object is not shared, see #20328
  1810. const image = Object.assign( {}, source.texture.image );
  1811. this.texture.source = new Source( image );
  1812. this.depthBuffer = source.depthBuffer;
  1813. this.stencilBuffer = source.stencilBuffer;
  1814. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1815. this.samples = source.samples;
  1816. return this;
  1817. }
  1818. dispose() {
  1819. this.dispatchEvent( { type: 'dispose' } );
  1820. }
  1821. }
  1822. class DataArrayTexture extends Texture {
  1823. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1824. super( null );
  1825. this.isDataArrayTexture = true;
  1826. this.image = { data, width, height, depth };
  1827. this.magFilter = NearestFilter;
  1828. this.minFilter = NearestFilter;
  1829. this.wrapR = ClampToEdgeWrapping;
  1830. this.generateMipmaps = false;
  1831. this.flipY = false;
  1832. this.unpackAlignment = 1;
  1833. }
  1834. }
  1835. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1836. constructor( width = 1, height = 1, depth = 1 ) {
  1837. super( width, height );
  1838. this.isWebGLArrayRenderTarget = true;
  1839. this.depth = depth;
  1840. this.texture = new DataArrayTexture( null, width, height, depth );
  1841. this.texture.isRenderTargetTexture = true;
  1842. }
  1843. }
  1844. class Data3DTexture extends Texture {
  1845. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1846. // We're going to add .setXXX() methods for setting properties later.
  1847. // Users can still set in DataTexture3D directly.
  1848. //
  1849. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1850. // texture.anisotropy = 16;
  1851. //
  1852. // See #14839
  1853. super( null );
  1854. this.isData3DTexture = true;
  1855. this.image = { data, width, height, depth };
  1856. this.magFilter = NearestFilter;
  1857. this.minFilter = NearestFilter;
  1858. this.wrapR = ClampToEdgeWrapping;
  1859. this.generateMipmaps = false;
  1860. this.flipY = false;
  1861. this.unpackAlignment = 1;
  1862. }
  1863. }
  1864. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1865. constructor( width = 1, height = 1, depth = 1 ) {
  1866. super( width, height );
  1867. this.isWebGL3DRenderTarget = true;
  1868. this.depth = depth;
  1869. this.texture = new Data3DTexture( null, width, height, depth );
  1870. this.texture.isRenderTargetTexture = true;
  1871. }
  1872. }
  1873. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1874. constructor( width = 1, height = 1, count = 1, options = {} ) {
  1875. super( width, height, options );
  1876. this.isWebGLMultipleRenderTargets = true;
  1877. const texture = this.texture;
  1878. this.texture = [];
  1879. for ( let i = 0; i < count; i ++ ) {
  1880. this.texture[ i ] = texture.clone();
  1881. this.texture[ i ].isRenderTargetTexture = true;
  1882. }
  1883. }
  1884. setSize( width, height, depth = 1 ) {
  1885. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1886. this.width = width;
  1887. this.height = height;
  1888. this.depth = depth;
  1889. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1890. this.texture[ i ].image.width = width;
  1891. this.texture[ i ].image.height = height;
  1892. this.texture[ i ].image.depth = depth;
  1893. }
  1894. this.dispose();
  1895. }
  1896. this.viewport.set( 0, 0, width, height );
  1897. this.scissor.set( 0, 0, width, height );
  1898. return this;
  1899. }
  1900. copy( source ) {
  1901. this.dispose();
  1902. this.width = source.width;
  1903. this.height = source.height;
  1904. this.depth = source.depth;
  1905. this.scissor.copy( source.scissor );
  1906. this.scissorTest = source.scissorTest;
  1907. this.viewport.copy( source.viewport );
  1908. this.depthBuffer = source.depthBuffer;
  1909. this.stencilBuffer = source.stencilBuffer;
  1910. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1911. this.texture.length = 0;
  1912. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1913. this.texture[ i ] = source.texture[ i ].clone();
  1914. this.texture[ i ].isRenderTargetTexture = true;
  1915. }
  1916. return this;
  1917. }
  1918. }
  1919. class Quaternion {
  1920. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1921. this.isQuaternion = true;
  1922. this._x = x;
  1923. this._y = y;
  1924. this._z = z;
  1925. this._w = w;
  1926. }
  1927. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1928. // fuzz-free, array-based Quaternion SLERP operation
  1929. let x0 = src0[ srcOffset0 + 0 ],
  1930. y0 = src0[ srcOffset0 + 1 ],
  1931. z0 = src0[ srcOffset0 + 2 ],
  1932. w0 = src0[ srcOffset0 + 3 ];
  1933. const x1 = src1[ srcOffset1 + 0 ],
  1934. y1 = src1[ srcOffset1 + 1 ],
  1935. z1 = src1[ srcOffset1 + 2 ],
  1936. w1 = src1[ srcOffset1 + 3 ];
  1937. if ( t === 0 ) {
  1938. dst[ dstOffset + 0 ] = x0;
  1939. dst[ dstOffset + 1 ] = y0;
  1940. dst[ dstOffset + 2 ] = z0;
  1941. dst[ dstOffset + 3 ] = w0;
  1942. return;
  1943. }
  1944. if ( t === 1 ) {
  1945. dst[ dstOffset + 0 ] = x1;
  1946. dst[ dstOffset + 1 ] = y1;
  1947. dst[ dstOffset + 2 ] = z1;
  1948. dst[ dstOffset + 3 ] = w1;
  1949. return;
  1950. }
  1951. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1952. let s = 1 - t;
  1953. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1954. dir = ( cos >= 0 ? 1 : - 1 ),
  1955. sqrSin = 1 - cos * cos;
  1956. // Skip the Slerp for tiny steps to avoid numeric problems:
  1957. if ( sqrSin > Number.EPSILON ) {
  1958. const sin = Math.sqrt( sqrSin ),
  1959. len = Math.atan2( sin, cos * dir );
  1960. s = Math.sin( s * len ) / sin;
  1961. t = Math.sin( t * len ) / sin;
  1962. }
  1963. const tDir = t * dir;
  1964. x0 = x0 * s + x1 * tDir;
  1965. y0 = y0 * s + y1 * tDir;
  1966. z0 = z0 * s + z1 * tDir;
  1967. w0 = w0 * s + w1 * tDir;
  1968. // Normalize in case we just did a lerp:
  1969. if ( s === 1 - t ) {
  1970. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1971. x0 *= f;
  1972. y0 *= f;
  1973. z0 *= f;
  1974. w0 *= f;
  1975. }
  1976. }
  1977. dst[ dstOffset ] = x0;
  1978. dst[ dstOffset + 1 ] = y0;
  1979. dst[ dstOffset + 2 ] = z0;
  1980. dst[ dstOffset + 3 ] = w0;
  1981. }
  1982. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1983. const x0 = src0[ srcOffset0 ];
  1984. const y0 = src0[ srcOffset0 + 1 ];
  1985. const z0 = src0[ srcOffset0 + 2 ];
  1986. const w0 = src0[ srcOffset0 + 3 ];
  1987. const x1 = src1[ srcOffset1 ];
  1988. const y1 = src1[ srcOffset1 + 1 ];
  1989. const z1 = src1[ srcOffset1 + 2 ];
  1990. const w1 = src1[ srcOffset1 + 3 ];
  1991. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1992. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1993. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1994. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1995. return dst;
  1996. }
  1997. get x() {
  1998. return this._x;
  1999. }
  2000. set x( value ) {
  2001. this._x = value;
  2002. this._onChangeCallback();
  2003. }
  2004. get y() {
  2005. return this._y;
  2006. }
  2007. set y( value ) {
  2008. this._y = value;
  2009. this._onChangeCallback();
  2010. }
  2011. get z() {
  2012. return this._z;
  2013. }
  2014. set z( value ) {
  2015. this._z = value;
  2016. this._onChangeCallback();
  2017. }
  2018. get w() {
  2019. return this._w;
  2020. }
  2021. set w( value ) {
  2022. this._w = value;
  2023. this._onChangeCallback();
  2024. }
  2025. set( x, y, z, w ) {
  2026. this._x = x;
  2027. this._y = y;
  2028. this._z = z;
  2029. this._w = w;
  2030. this._onChangeCallback();
  2031. return this;
  2032. }
  2033. clone() {
  2034. return new this.constructor( this._x, this._y, this._z, this._w );
  2035. }
  2036. copy( quaternion ) {
  2037. this._x = quaternion.x;
  2038. this._y = quaternion.y;
  2039. this._z = quaternion.z;
  2040. this._w = quaternion.w;
  2041. this._onChangeCallback();
  2042. return this;
  2043. }
  2044. setFromEuler( euler, update ) {
  2045. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2046. // http://www.mathworks.com/matlabcentral/fileexchange/
  2047. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2048. // content/SpinCalc.m
  2049. const cos = Math.cos;
  2050. const sin = Math.sin;
  2051. const c1 = cos( x / 2 );
  2052. const c2 = cos( y / 2 );
  2053. const c3 = cos( z / 2 );
  2054. const s1 = sin( x / 2 );
  2055. const s2 = sin( y / 2 );
  2056. const s3 = sin( z / 2 );
  2057. switch ( order ) {
  2058. case 'XYZ':
  2059. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2060. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2061. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2062. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2063. break;
  2064. case 'YXZ':
  2065. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2066. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2067. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2068. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2069. break;
  2070. case 'ZXY':
  2071. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2072. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2073. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2074. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2075. break;
  2076. case 'ZYX':
  2077. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2078. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2079. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2080. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2081. break;
  2082. case 'YZX':
  2083. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2084. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2085. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2086. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2087. break;
  2088. case 'XZY':
  2089. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2090. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2091. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2092. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2093. break;
  2094. default:
  2095. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2096. }
  2097. if ( update !== false ) this._onChangeCallback();
  2098. return this;
  2099. }
  2100. setFromAxisAngle( axis, angle ) {
  2101. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2102. // assumes axis is normalized
  2103. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2104. this._x = axis.x * s;
  2105. this._y = axis.y * s;
  2106. this._z = axis.z * s;
  2107. this._w = Math.cos( halfAngle );
  2108. this._onChangeCallback();
  2109. return this;
  2110. }
  2111. setFromRotationMatrix( m ) {
  2112. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2113. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2114. const te = m.elements,
  2115. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2116. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2117. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2118. trace = m11 + m22 + m33;
  2119. if ( trace > 0 ) {
  2120. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2121. this._w = 0.25 / s;
  2122. this._x = ( m32 - m23 ) * s;
  2123. this._y = ( m13 - m31 ) * s;
  2124. this._z = ( m21 - m12 ) * s;
  2125. } else if ( m11 > m22 && m11 > m33 ) {
  2126. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2127. this._w = ( m32 - m23 ) / s;
  2128. this._x = 0.25 * s;
  2129. this._y = ( m12 + m21 ) / s;
  2130. this._z = ( m13 + m31 ) / s;
  2131. } else if ( m22 > m33 ) {
  2132. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2133. this._w = ( m13 - m31 ) / s;
  2134. this._x = ( m12 + m21 ) / s;
  2135. this._y = 0.25 * s;
  2136. this._z = ( m23 + m32 ) / s;
  2137. } else {
  2138. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2139. this._w = ( m21 - m12 ) / s;
  2140. this._x = ( m13 + m31 ) / s;
  2141. this._y = ( m23 + m32 ) / s;
  2142. this._z = 0.25 * s;
  2143. }
  2144. this._onChangeCallback();
  2145. return this;
  2146. }
  2147. setFromUnitVectors( vFrom, vTo ) {
  2148. // assumes direction vectors vFrom and vTo are normalized
  2149. let r = vFrom.dot( vTo ) + 1;
  2150. if ( r < Number.EPSILON ) {
  2151. // vFrom and vTo point in opposite directions
  2152. r = 0;
  2153. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2154. this._x = - vFrom.y;
  2155. this._y = vFrom.x;
  2156. this._z = 0;
  2157. this._w = r;
  2158. } else {
  2159. this._x = 0;
  2160. this._y = - vFrom.z;
  2161. this._z = vFrom.y;
  2162. this._w = r;
  2163. }
  2164. } else {
  2165. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2166. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2167. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2168. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2169. this._w = r;
  2170. }
  2171. return this.normalize();
  2172. }
  2173. angleTo( q ) {
  2174. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2175. }
  2176. rotateTowards( q, step ) {
  2177. const angle = this.angleTo( q );
  2178. if ( angle === 0 ) return this;
  2179. const t = Math.min( 1, step / angle );
  2180. this.slerp( q, t );
  2181. return this;
  2182. }
  2183. identity() {
  2184. return this.set( 0, 0, 0, 1 );
  2185. }
  2186. invert() {
  2187. // quaternion is assumed to have unit length
  2188. return this.conjugate();
  2189. }
  2190. conjugate() {
  2191. this._x *= - 1;
  2192. this._y *= - 1;
  2193. this._z *= - 1;
  2194. this._onChangeCallback();
  2195. return this;
  2196. }
  2197. dot( v ) {
  2198. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2199. }
  2200. lengthSq() {
  2201. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2202. }
  2203. length() {
  2204. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2205. }
  2206. normalize() {
  2207. let l = this.length();
  2208. if ( l === 0 ) {
  2209. this._x = 0;
  2210. this._y = 0;
  2211. this._z = 0;
  2212. this._w = 1;
  2213. } else {
  2214. l = 1 / l;
  2215. this._x = this._x * l;
  2216. this._y = this._y * l;
  2217. this._z = this._z * l;
  2218. this._w = this._w * l;
  2219. }
  2220. this._onChangeCallback();
  2221. return this;
  2222. }
  2223. multiply( q ) {
  2224. return this.multiplyQuaternions( this, q );
  2225. }
  2226. premultiply( q ) {
  2227. return this.multiplyQuaternions( q, this );
  2228. }
  2229. multiplyQuaternions( a, b ) {
  2230. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2231. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2232. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2233. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2234. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2235. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2236. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2237. this._onChangeCallback();
  2238. return this;
  2239. }
  2240. slerp( qb, t ) {
  2241. if ( t === 0 ) return this;
  2242. if ( t === 1 ) return this.copy( qb );
  2243. const x = this._x, y = this._y, z = this._z, w = this._w;
  2244. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2245. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2246. if ( cosHalfTheta < 0 ) {
  2247. this._w = - qb._w;
  2248. this._x = - qb._x;
  2249. this._y = - qb._y;
  2250. this._z = - qb._z;
  2251. cosHalfTheta = - cosHalfTheta;
  2252. } else {
  2253. this.copy( qb );
  2254. }
  2255. if ( cosHalfTheta >= 1.0 ) {
  2256. this._w = w;
  2257. this._x = x;
  2258. this._y = y;
  2259. this._z = z;
  2260. return this;
  2261. }
  2262. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2263. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2264. const s = 1 - t;
  2265. this._w = s * w + t * this._w;
  2266. this._x = s * x + t * this._x;
  2267. this._y = s * y + t * this._y;
  2268. this._z = s * z + t * this._z;
  2269. this.normalize();
  2270. this._onChangeCallback();
  2271. return this;
  2272. }
  2273. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2274. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2275. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2276. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2277. this._w = ( w * ratioA + this._w * ratioB );
  2278. this._x = ( x * ratioA + this._x * ratioB );
  2279. this._y = ( y * ratioA + this._y * ratioB );
  2280. this._z = ( z * ratioA + this._z * ratioB );
  2281. this._onChangeCallback();
  2282. return this;
  2283. }
  2284. slerpQuaternions( qa, qb, t ) {
  2285. return this.copy( qa ).slerp( qb, t );
  2286. }
  2287. random() {
  2288. // Derived from http://planning.cs.uiuc.edu/node198.html
  2289. // Note, this source uses w, x, y, z ordering,
  2290. // so we swap the order below.
  2291. const u1 = Math.random();
  2292. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2293. const sqrtu1 = Math.sqrt( u1 );
  2294. const u2 = 2 * Math.PI * Math.random();
  2295. const u3 = 2 * Math.PI * Math.random();
  2296. return this.set(
  2297. sqrt1u1 * Math.cos( u2 ),
  2298. sqrtu1 * Math.sin( u3 ),
  2299. sqrtu1 * Math.cos( u3 ),
  2300. sqrt1u1 * Math.sin( u2 ),
  2301. );
  2302. }
  2303. equals( quaternion ) {
  2304. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2305. }
  2306. fromArray( array, offset = 0 ) {
  2307. this._x = array[ offset ];
  2308. this._y = array[ offset + 1 ];
  2309. this._z = array[ offset + 2 ];
  2310. this._w = array[ offset + 3 ];
  2311. this._onChangeCallback();
  2312. return this;
  2313. }
  2314. toArray( array = [], offset = 0 ) {
  2315. array[ offset ] = this._x;
  2316. array[ offset + 1 ] = this._y;
  2317. array[ offset + 2 ] = this._z;
  2318. array[ offset + 3 ] = this._w;
  2319. return array;
  2320. }
  2321. fromBufferAttribute( attribute, index ) {
  2322. this._x = attribute.getX( index );
  2323. this._y = attribute.getY( index );
  2324. this._z = attribute.getZ( index );
  2325. this._w = attribute.getW( index );
  2326. return this;
  2327. }
  2328. toJSON() {
  2329. return this.toArray();
  2330. }
  2331. _onChange( callback ) {
  2332. this._onChangeCallback = callback;
  2333. return this;
  2334. }
  2335. _onChangeCallback() {}
  2336. *[ Symbol.iterator ]() {
  2337. yield this._x;
  2338. yield this._y;
  2339. yield this._z;
  2340. yield this._w;
  2341. }
  2342. }
  2343. class Vector3 {
  2344. constructor( x = 0, y = 0, z = 0 ) {
  2345. Vector3.prototype.isVector3 = true;
  2346. this.x = x;
  2347. this.y = y;
  2348. this.z = z;
  2349. }
  2350. set( x, y, z ) {
  2351. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2352. this.x = x;
  2353. this.y = y;
  2354. this.z = z;
  2355. return this;
  2356. }
  2357. setScalar( scalar ) {
  2358. this.x = scalar;
  2359. this.y = scalar;
  2360. this.z = scalar;
  2361. return this;
  2362. }
  2363. setX( x ) {
  2364. this.x = x;
  2365. return this;
  2366. }
  2367. setY( y ) {
  2368. this.y = y;
  2369. return this;
  2370. }
  2371. setZ( z ) {
  2372. this.z = z;
  2373. return this;
  2374. }
  2375. setComponent( index, value ) {
  2376. switch ( index ) {
  2377. case 0: this.x = value; break;
  2378. case 1: this.y = value; break;
  2379. case 2: this.z = value; break;
  2380. default: throw new Error( 'index is out of range: ' + index );
  2381. }
  2382. return this;
  2383. }
  2384. getComponent( index ) {
  2385. switch ( index ) {
  2386. case 0: return this.x;
  2387. case 1: return this.y;
  2388. case 2: return this.z;
  2389. default: throw new Error( 'index is out of range: ' + index );
  2390. }
  2391. }
  2392. clone() {
  2393. return new this.constructor( this.x, this.y, this.z );
  2394. }
  2395. copy( v ) {
  2396. this.x = v.x;
  2397. this.y = v.y;
  2398. this.z = v.z;
  2399. return this;
  2400. }
  2401. add( v ) {
  2402. this.x += v.x;
  2403. this.y += v.y;
  2404. this.z += v.z;
  2405. return this;
  2406. }
  2407. addScalar( s ) {
  2408. this.x += s;
  2409. this.y += s;
  2410. this.z += s;
  2411. return this;
  2412. }
  2413. addVectors( a, b ) {
  2414. this.x = a.x + b.x;
  2415. this.y = a.y + b.y;
  2416. this.z = a.z + b.z;
  2417. return this;
  2418. }
  2419. addScaledVector( v, s ) {
  2420. this.x += v.x * s;
  2421. this.y += v.y * s;
  2422. this.z += v.z * s;
  2423. return this;
  2424. }
  2425. sub( v ) {
  2426. this.x -= v.x;
  2427. this.y -= v.y;
  2428. this.z -= v.z;
  2429. return this;
  2430. }
  2431. subScalar( s ) {
  2432. this.x -= s;
  2433. this.y -= s;
  2434. this.z -= s;
  2435. return this;
  2436. }
  2437. subVectors( a, b ) {
  2438. this.x = a.x - b.x;
  2439. this.y = a.y - b.y;
  2440. this.z = a.z - b.z;
  2441. return this;
  2442. }
  2443. multiply( v ) {
  2444. this.x *= v.x;
  2445. this.y *= v.y;
  2446. this.z *= v.z;
  2447. return this;
  2448. }
  2449. multiplyScalar( scalar ) {
  2450. this.x *= scalar;
  2451. this.y *= scalar;
  2452. this.z *= scalar;
  2453. return this;
  2454. }
  2455. multiplyVectors( a, b ) {
  2456. this.x = a.x * b.x;
  2457. this.y = a.y * b.y;
  2458. this.z = a.z * b.z;
  2459. return this;
  2460. }
  2461. applyEuler( euler ) {
  2462. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2463. }
  2464. applyAxisAngle( axis, angle ) {
  2465. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2466. }
  2467. applyMatrix3( m ) {
  2468. const x = this.x, y = this.y, z = this.z;
  2469. const e = m.elements;
  2470. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2471. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2472. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2473. return this;
  2474. }
  2475. applyNormalMatrix( m ) {
  2476. return this.applyMatrix3( m ).normalize();
  2477. }
  2478. applyMatrix4( m ) {
  2479. const x = this.x, y = this.y, z = this.z;
  2480. const e = m.elements;
  2481. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2482. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2483. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2484. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2485. return this;
  2486. }
  2487. applyQuaternion( q ) {
  2488. const x = this.x, y = this.y, z = this.z;
  2489. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2490. // calculate quat * vector
  2491. const ix = qw * x + qy * z - qz * y;
  2492. const iy = qw * y + qz * x - qx * z;
  2493. const iz = qw * z + qx * y - qy * x;
  2494. const iw = - qx * x - qy * y - qz * z;
  2495. // calculate result * inverse quat
  2496. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2497. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2498. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2499. return this;
  2500. }
  2501. project( camera ) {
  2502. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2503. }
  2504. unproject( camera ) {
  2505. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2506. }
  2507. transformDirection( m ) {
  2508. // input: THREE.Matrix4 affine matrix
  2509. // vector interpreted as a direction
  2510. const x = this.x, y = this.y, z = this.z;
  2511. const e = m.elements;
  2512. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2513. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2514. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2515. return this.normalize();
  2516. }
  2517. divide( v ) {
  2518. this.x /= v.x;
  2519. this.y /= v.y;
  2520. this.z /= v.z;
  2521. return this;
  2522. }
  2523. divideScalar( scalar ) {
  2524. return this.multiplyScalar( 1 / scalar );
  2525. }
  2526. min( v ) {
  2527. this.x = Math.min( this.x, v.x );
  2528. this.y = Math.min( this.y, v.y );
  2529. this.z = Math.min( this.z, v.z );
  2530. return this;
  2531. }
  2532. max( v ) {
  2533. this.x = Math.max( this.x, v.x );
  2534. this.y = Math.max( this.y, v.y );
  2535. this.z = Math.max( this.z, v.z );
  2536. return this;
  2537. }
  2538. clamp( min, max ) {
  2539. // assumes min < max, componentwise
  2540. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2541. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2542. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2543. return this;
  2544. }
  2545. clampScalar( minVal, maxVal ) {
  2546. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2547. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2548. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2549. return this;
  2550. }
  2551. clampLength( min, max ) {
  2552. const length = this.length();
  2553. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2554. }
  2555. floor() {
  2556. this.x = Math.floor( this.x );
  2557. this.y = Math.floor( this.y );
  2558. this.z = Math.floor( this.z );
  2559. return this;
  2560. }
  2561. ceil() {
  2562. this.x = Math.ceil( this.x );
  2563. this.y = Math.ceil( this.y );
  2564. this.z = Math.ceil( this.z );
  2565. return this;
  2566. }
  2567. round() {
  2568. this.x = Math.round( this.x );
  2569. this.y = Math.round( this.y );
  2570. this.z = Math.round( this.z );
  2571. return this;
  2572. }
  2573. roundToZero() {
  2574. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2575. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2576. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2577. return this;
  2578. }
  2579. negate() {
  2580. this.x = - this.x;
  2581. this.y = - this.y;
  2582. this.z = - this.z;
  2583. return this;
  2584. }
  2585. dot( v ) {
  2586. return this.x * v.x + this.y * v.y + this.z * v.z;
  2587. }
  2588. // TODO lengthSquared?
  2589. lengthSq() {
  2590. return this.x * this.x + this.y * this.y + this.z * this.z;
  2591. }
  2592. length() {
  2593. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2594. }
  2595. manhattanLength() {
  2596. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2597. }
  2598. normalize() {
  2599. return this.divideScalar( this.length() || 1 );
  2600. }
  2601. setLength( length ) {
  2602. return this.normalize().multiplyScalar( length );
  2603. }
  2604. lerp( v, alpha ) {
  2605. this.x += ( v.x - this.x ) * alpha;
  2606. this.y += ( v.y - this.y ) * alpha;
  2607. this.z += ( v.z - this.z ) * alpha;
  2608. return this;
  2609. }
  2610. lerpVectors( v1, v2, alpha ) {
  2611. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2612. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2613. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2614. return this;
  2615. }
  2616. cross( v ) {
  2617. return this.crossVectors( this, v );
  2618. }
  2619. crossVectors( a, b ) {
  2620. const ax = a.x, ay = a.y, az = a.z;
  2621. const bx = b.x, by = b.y, bz = b.z;
  2622. this.x = ay * bz - az * by;
  2623. this.y = az * bx - ax * bz;
  2624. this.z = ax * by - ay * bx;
  2625. return this;
  2626. }
  2627. projectOnVector( v ) {
  2628. const denominator = v.lengthSq();
  2629. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2630. const scalar = v.dot( this ) / denominator;
  2631. return this.copy( v ).multiplyScalar( scalar );
  2632. }
  2633. projectOnPlane( planeNormal ) {
  2634. _vector$b.copy( this ).projectOnVector( planeNormal );
  2635. return this.sub( _vector$b );
  2636. }
  2637. reflect( normal ) {
  2638. // reflect incident vector off plane orthogonal to normal
  2639. // normal is assumed to have unit length
  2640. return this.sub( _vector$b.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2641. }
  2642. angleTo( v ) {
  2643. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2644. if ( denominator === 0 ) return Math.PI / 2;
  2645. const theta = this.dot( v ) / denominator;
  2646. // clamp, to handle numerical problems
  2647. return Math.acos( clamp( theta, - 1, 1 ) );
  2648. }
  2649. distanceTo( v ) {
  2650. return Math.sqrt( this.distanceToSquared( v ) );
  2651. }
  2652. distanceToSquared( v ) {
  2653. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2654. return dx * dx + dy * dy + dz * dz;
  2655. }
  2656. manhattanDistanceTo( v ) {
  2657. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2658. }
  2659. setFromSpherical( s ) {
  2660. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2661. }
  2662. setFromSphericalCoords( radius, phi, theta ) {
  2663. const sinPhiRadius = Math.sin( phi ) * radius;
  2664. this.x = sinPhiRadius * Math.sin( theta );
  2665. this.y = Math.cos( phi ) * radius;
  2666. this.z = sinPhiRadius * Math.cos( theta );
  2667. return this;
  2668. }
  2669. setFromCylindrical( c ) {
  2670. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2671. }
  2672. setFromCylindricalCoords( radius, theta, y ) {
  2673. this.x = radius * Math.sin( theta );
  2674. this.y = y;
  2675. this.z = radius * Math.cos( theta );
  2676. return this;
  2677. }
  2678. setFromMatrixPosition( m ) {
  2679. const e = m.elements;
  2680. this.x = e[ 12 ];
  2681. this.y = e[ 13 ];
  2682. this.z = e[ 14 ];
  2683. return this;
  2684. }
  2685. setFromMatrixScale( m ) {
  2686. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2687. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2688. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2689. this.x = sx;
  2690. this.y = sy;
  2691. this.z = sz;
  2692. return this;
  2693. }
  2694. setFromMatrixColumn( m, index ) {
  2695. return this.fromArray( m.elements, index * 4 );
  2696. }
  2697. setFromMatrix3Column( m, index ) {
  2698. return this.fromArray( m.elements, index * 3 );
  2699. }
  2700. setFromEuler( e ) {
  2701. this.x = e._x;
  2702. this.y = e._y;
  2703. this.z = e._z;
  2704. return this;
  2705. }
  2706. setFromColor( c ) {
  2707. this.x = c.r;
  2708. this.y = c.g;
  2709. this.z = c.b;
  2710. return this;
  2711. }
  2712. equals( v ) {
  2713. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2714. }
  2715. fromArray( array, offset = 0 ) {
  2716. this.x = array[ offset ];
  2717. this.y = array[ offset + 1 ];
  2718. this.z = array[ offset + 2 ];
  2719. return this;
  2720. }
  2721. toArray( array = [], offset = 0 ) {
  2722. array[ offset ] = this.x;
  2723. array[ offset + 1 ] = this.y;
  2724. array[ offset + 2 ] = this.z;
  2725. return array;
  2726. }
  2727. fromBufferAttribute( attribute, index ) {
  2728. this.x = attribute.getX( index );
  2729. this.y = attribute.getY( index );
  2730. this.z = attribute.getZ( index );
  2731. return this;
  2732. }
  2733. random() {
  2734. this.x = Math.random();
  2735. this.y = Math.random();
  2736. this.z = Math.random();
  2737. return this;
  2738. }
  2739. randomDirection() {
  2740. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2741. const u = ( Math.random() - 0.5 ) * 2;
  2742. const t = Math.random() * Math.PI * 2;
  2743. const f = Math.sqrt( 1 - u ** 2 );
  2744. this.x = f * Math.cos( t );
  2745. this.y = f * Math.sin( t );
  2746. this.z = u;
  2747. return this;
  2748. }
  2749. *[ Symbol.iterator ]() {
  2750. yield this.x;
  2751. yield this.y;
  2752. yield this.z;
  2753. }
  2754. }
  2755. const _vector$b = /*@__PURE__*/ new Vector3();
  2756. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2757. class Box3 {
  2758. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2759. this.isBox3 = true;
  2760. this.min = min;
  2761. this.max = max;
  2762. }
  2763. set( min, max ) {
  2764. this.min.copy( min );
  2765. this.max.copy( max );
  2766. return this;
  2767. }
  2768. setFromArray( array ) {
  2769. this.makeEmpty();
  2770. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2771. this.expandByPoint( _vector$a.fromArray( array, i ) );
  2772. }
  2773. return this;
  2774. }
  2775. setFromBufferAttribute( attribute ) {
  2776. this.makeEmpty();
  2777. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2778. this.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );
  2779. }
  2780. return this;
  2781. }
  2782. setFromPoints( points ) {
  2783. this.makeEmpty();
  2784. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2785. this.expandByPoint( points[ i ] );
  2786. }
  2787. return this;
  2788. }
  2789. setFromCenterAndSize( center, size ) {
  2790. const halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );
  2791. this.min.copy( center ).sub( halfSize );
  2792. this.max.copy( center ).add( halfSize );
  2793. return this;
  2794. }
  2795. setFromObject( object, precise = false ) {
  2796. this.makeEmpty();
  2797. return this.expandByObject( object, precise );
  2798. }
  2799. clone() {
  2800. return new this.constructor().copy( this );
  2801. }
  2802. copy( box ) {
  2803. this.min.copy( box.min );
  2804. this.max.copy( box.max );
  2805. return this;
  2806. }
  2807. makeEmpty() {
  2808. this.min.x = this.min.y = this.min.z = + Infinity;
  2809. this.max.x = this.max.y = this.max.z = - Infinity;
  2810. return this;
  2811. }
  2812. isEmpty() {
  2813. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2814. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2815. }
  2816. getCenter( target ) {
  2817. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2818. }
  2819. getSize( target ) {
  2820. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2821. }
  2822. expandByPoint( point ) {
  2823. this.min.min( point );
  2824. this.max.max( point );
  2825. return this;
  2826. }
  2827. expandByVector( vector ) {
  2828. this.min.sub( vector );
  2829. this.max.add( vector );
  2830. return this;
  2831. }
  2832. expandByScalar( scalar ) {
  2833. this.min.addScalar( - scalar );
  2834. this.max.addScalar( scalar );
  2835. return this;
  2836. }
  2837. expandByObject( object, precise = false ) {
  2838. // Computes the world-axis-aligned bounding box of an object (including its children),
  2839. // accounting for both the object's, and children's, world transforms
  2840. object.updateWorldMatrix( false, false );
  2841. if ( object.boundingBox !== undefined ) {
  2842. if ( object.boundingBox === null ) {
  2843. object.computeBoundingBox();
  2844. }
  2845. _box$3.copy( object.boundingBox );
  2846. _box$3.applyMatrix4( object.matrixWorld );
  2847. this.union( _box$3 );
  2848. } else {
  2849. const geometry = object.geometry;
  2850. if ( geometry !== undefined ) {
  2851. if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {
  2852. const position = geometry.attributes.position;
  2853. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2854. _vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2855. this.expandByPoint( _vector$a );
  2856. }
  2857. } else {
  2858. if ( geometry.boundingBox === null ) {
  2859. geometry.computeBoundingBox();
  2860. }
  2861. _box$3.copy( geometry.boundingBox );
  2862. _box$3.applyMatrix4( object.matrixWorld );
  2863. this.union( _box$3 );
  2864. }
  2865. }
  2866. }
  2867. const children = object.children;
  2868. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2869. this.expandByObject( children[ i ], precise );
  2870. }
  2871. return this;
  2872. }
  2873. containsPoint( point ) {
  2874. return point.x < this.min.x || point.x > this.max.x ||
  2875. point.y < this.min.y || point.y > this.max.y ||
  2876. point.z < this.min.z || point.z > this.max.z ? false : true;
  2877. }
  2878. containsBox( box ) {
  2879. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2880. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2881. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2882. }
  2883. getParameter( point, target ) {
  2884. // This can potentially have a divide by zero if the box
  2885. // has a size dimension of 0.
  2886. return target.set(
  2887. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2888. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2889. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2890. );
  2891. }
  2892. intersectsBox( box ) {
  2893. // using 6 splitting planes to rule out intersections.
  2894. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2895. box.max.y < this.min.y || box.min.y > this.max.y ||
  2896. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2897. }
  2898. intersectsSphere( sphere ) {
  2899. // Find the point on the AABB closest to the sphere center.
  2900. this.clampPoint( sphere.center, _vector$a );
  2901. // If that point is inside the sphere, the AABB and sphere intersect.
  2902. return _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2903. }
  2904. intersectsPlane( plane ) {
  2905. // We compute the minimum and maximum dot product values. If those values
  2906. // are on the same side (back or front) of the plane, then there is no intersection.
  2907. let min, max;
  2908. if ( plane.normal.x > 0 ) {
  2909. min = plane.normal.x * this.min.x;
  2910. max = plane.normal.x * this.max.x;
  2911. } else {
  2912. min = plane.normal.x * this.max.x;
  2913. max = plane.normal.x * this.min.x;
  2914. }
  2915. if ( plane.normal.y > 0 ) {
  2916. min += plane.normal.y * this.min.y;
  2917. max += plane.normal.y * this.max.y;
  2918. } else {
  2919. min += plane.normal.y * this.max.y;
  2920. max += plane.normal.y * this.min.y;
  2921. }
  2922. if ( plane.normal.z > 0 ) {
  2923. min += plane.normal.z * this.min.z;
  2924. max += plane.normal.z * this.max.z;
  2925. } else {
  2926. min += plane.normal.z * this.max.z;
  2927. max += plane.normal.z * this.min.z;
  2928. }
  2929. return ( min <= - plane.constant && max >= - plane.constant );
  2930. }
  2931. intersectsTriangle( triangle ) {
  2932. if ( this.isEmpty() ) {
  2933. return false;
  2934. }
  2935. // compute box center and extents
  2936. this.getCenter( _center );
  2937. _extents.subVectors( this.max, _center );
  2938. // translate triangle to aabb origin
  2939. _v0$2.subVectors( triangle.a, _center );
  2940. _v1$7.subVectors( triangle.b, _center );
  2941. _v2$4.subVectors( triangle.c, _center );
  2942. // compute edge vectors for triangle
  2943. _f0.subVectors( _v1$7, _v0$2 );
  2944. _f1.subVectors( _v2$4, _v1$7 );
  2945. _f2.subVectors( _v0$2, _v2$4 );
  2946. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2947. // 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
  2948. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2949. let axes = [
  2950. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2951. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2952. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2953. ];
  2954. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2955. return false;
  2956. }
  2957. // test 3 face normals from the aabb
  2958. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2959. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2960. return false;
  2961. }
  2962. // finally testing the face normal of the triangle
  2963. // use already existing triangle edge vectors here
  2964. _triangleNormal.crossVectors( _f0, _f1 );
  2965. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2966. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2967. }
  2968. clampPoint( point, target ) {
  2969. return target.copy( point ).clamp( this.min, this.max );
  2970. }
  2971. distanceToPoint( point ) {
  2972. return this.clampPoint( point, _vector$a ).distanceTo( point );
  2973. }
  2974. getBoundingSphere( target ) {
  2975. if ( this.isEmpty() ) {
  2976. target.makeEmpty();
  2977. } else {
  2978. this.getCenter( target.center );
  2979. target.radius = this.getSize( _vector$a ).length() * 0.5;
  2980. }
  2981. return target;
  2982. }
  2983. intersect( box ) {
  2984. this.min.max( box.min );
  2985. this.max.min( box.max );
  2986. // 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.
  2987. if ( this.isEmpty() ) this.makeEmpty();
  2988. return this;
  2989. }
  2990. union( box ) {
  2991. this.min.min( box.min );
  2992. this.max.max( box.max );
  2993. return this;
  2994. }
  2995. applyMatrix4( matrix ) {
  2996. // transform of empty box is an empty box.
  2997. if ( this.isEmpty() ) return this;
  2998. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2999. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3000. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3001. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3002. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3003. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3004. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3005. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3006. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3007. this.setFromPoints( _points );
  3008. return this;
  3009. }
  3010. translate( offset ) {
  3011. this.min.add( offset );
  3012. this.max.add( offset );
  3013. return this;
  3014. }
  3015. equals( box ) {
  3016. return box.min.equals( this.min ) && box.max.equals( this.max );
  3017. }
  3018. }
  3019. const _points = [
  3020. /*@__PURE__*/ new Vector3(),
  3021. /*@__PURE__*/ new Vector3(),
  3022. /*@__PURE__*/ new Vector3(),
  3023. /*@__PURE__*/ new Vector3(),
  3024. /*@__PURE__*/ new Vector3(),
  3025. /*@__PURE__*/ new Vector3(),
  3026. /*@__PURE__*/ new Vector3(),
  3027. /*@__PURE__*/ new Vector3()
  3028. ];
  3029. const _vector$a = /*@__PURE__*/ new Vector3();
  3030. const _box$3 = /*@__PURE__*/ new Box3();
  3031. // triangle centered vertices
  3032. const _v0$2 = /*@__PURE__*/ new Vector3();
  3033. const _v1$7 = /*@__PURE__*/ new Vector3();
  3034. const _v2$4 = /*@__PURE__*/ new Vector3();
  3035. // triangle edge vectors
  3036. const _f0 = /*@__PURE__*/ new Vector3();
  3037. const _f1 = /*@__PURE__*/ new Vector3();
  3038. const _f2 = /*@__PURE__*/ new Vector3();
  3039. const _center = /*@__PURE__*/ new Vector3();
  3040. const _extents = /*@__PURE__*/ new Vector3();
  3041. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3042. const _testAxis = /*@__PURE__*/ new Vector3();
  3043. function satForAxes( axes, v0, v1, v2, extents ) {
  3044. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3045. _testAxis.fromArray( axes, i );
  3046. // project the aabb onto the separating axis
  3047. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3048. // project all 3 vertices of the triangle onto the separating axis
  3049. const p0 = v0.dot( _testAxis );
  3050. const p1 = v1.dot( _testAxis );
  3051. const p2 = v2.dot( _testAxis );
  3052. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3053. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3054. // points of the projected triangle are outside the projected half-length of the aabb
  3055. // the axis is separating and we can exit
  3056. return false;
  3057. }
  3058. }
  3059. return true;
  3060. }
  3061. const _box$2 = /*@__PURE__*/ new Box3();
  3062. const _v1$6 = /*@__PURE__*/ new Vector3();
  3063. const _v2$3 = /*@__PURE__*/ new Vector3();
  3064. class Sphere {
  3065. constructor( center = new Vector3(), radius = - 1 ) {
  3066. this.center = center;
  3067. this.radius = radius;
  3068. }
  3069. set( center, radius ) {
  3070. this.center.copy( center );
  3071. this.radius = radius;
  3072. return this;
  3073. }
  3074. setFromPoints( points, optionalCenter ) {
  3075. const center = this.center;
  3076. if ( optionalCenter !== undefined ) {
  3077. center.copy( optionalCenter );
  3078. } else {
  3079. _box$2.setFromPoints( points ).getCenter( center );
  3080. }
  3081. let maxRadiusSq = 0;
  3082. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3083. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3084. }
  3085. this.radius = Math.sqrt( maxRadiusSq );
  3086. return this;
  3087. }
  3088. copy( sphere ) {
  3089. this.center.copy( sphere.center );
  3090. this.radius = sphere.radius;
  3091. return this;
  3092. }
  3093. isEmpty() {
  3094. return ( this.radius < 0 );
  3095. }
  3096. makeEmpty() {
  3097. this.center.set( 0, 0, 0 );
  3098. this.radius = - 1;
  3099. return this;
  3100. }
  3101. containsPoint( point ) {
  3102. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3103. }
  3104. distanceToPoint( point ) {
  3105. return ( point.distanceTo( this.center ) - this.radius );
  3106. }
  3107. intersectsSphere( sphere ) {
  3108. const radiusSum = this.radius + sphere.radius;
  3109. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3110. }
  3111. intersectsBox( box ) {
  3112. return box.intersectsSphere( this );
  3113. }
  3114. intersectsPlane( plane ) {
  3115. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3116. }
  3117. clampPoint( point, target ) {
  3118. const deltaLengthSq = this.center.distanceToSquared( point );
  3119. target.copy( point );
  3120. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3121. target.sub( this.center ).normalize();
  3122. target.multiplyScalar( this.radius ).add( this.center );
  3123. }
  3124. return target;
  3125. }
  3126. getBoundingBox( target ) {
  3127. if ( this.isEmpty() ) {
  3128. // Empty sphere produces empty bounding box
  3129. target.makeEmpty();
  3130. return target;
  3131. }
  3132. target.set( this.center, this.center );
  3133. target.expandByScalar( this.radius );
  3134. return target;
  3135. }
  3136. applyMatrix4( matrix ) {
  3137. this.center.applyMatrix4( matrix );
  3138. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3139. return this;
  3140. }
  3141. translate( offset ) {
  3142. this.center.add( offset );
  3143. return this;
  3144. }
  3145. expandByPoint( point ) {
  3146. if ( this.isEmpty() ) {
  3147. this.center.copy( point );
  3148. this.radius = 0;
  3149. return this;
  3150. }
  3151. _v1$6.subVectors( point, this.center );
  3152. const lengthSq = _v1$6.lengthSq();
  3153. if ( lengthSq > ( this.radius * this.radius ) ) {
  3154. // calculate the minimal sphere
  3155. const length = Math.sqrt( lengthSq );
  3156. const delta = ( length - this.radius ) * 0.5;
  3157. this.center.addScaledVector( _v1$6, delta / length );
  3158. this.radius += delta;
  3159. }
  3160. return this;
  3161. }
  3162. union( sphere ) {
  3163. if ( sphere.isEmpty() ) {
  3164. return this;
  3165. }
  3166. if ( this.isEmpty() ) {
  3167. this.copy( sphere );
  3168. return this;
  3169. }
  3170. if ( this.center.equals( sphere.center ) === true ) {
  3171. this.radius = Math.max( this.radius, sphere.radius );
  3172. } else {
  3173. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3174. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3175. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3176. }
  3177. return this;
  3178. }
  3179. equals( sphere ) {
  3180. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3181. }
  3182. clone() {
  3183. return new this.constructor().copy( this );
  3184. }
  3185. }
  3186. const _vector$9 = /*@__PURE__*/ new Vector3();
  3187. const _segCenter = /*@__PURE__*/ new Vector3();
  3188. const _segDir = /*@__PURE__*/ new Vector3();
  3189. const _diff = /*@__PURE__*/ new Vector3();
  3190. const _edge1 = /*@__PURE__*/ new Vector3();
  3191. const _edge2 = /*@__PURE__*/ new Vector3();
  3192. const _normal$1 = /*@__PURE__*/ new Vector3();
  3193. class Ray {
  3194. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3195. this.origin = origin;
  3196. this.direction = direction;
  3197. }
  3198. set( origin, direction ) {
  3199. this.origin.copy( origin );
  3200. this.direction.copy( direction );
  3201. return this;
  3202. }
  3203. copy( ray ) {
  3204. this.origin.copy( ray.origin );
  3205. this.direction.copy( ray.direction );
  3206. return this;
  3207. }
  3208. at( t, target ) {
  3209. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3210. }
  3211. lookAt( v ) {
  3212. this.direction.copy( v ).sub( this.origin ).normalize();
  3213. return this;
  3214. }
  3215. recast( t ) {
  3216. this.origin.copy( this.at( t, _vector$9 ) );
  3217. return this;
  3218. }
  3219. closestPointToPoint( point, target ) {
  3220. target.subVectors( point, this.origin );
  3221. const directionDistance = target.dot( this.direction );
  3222. if ( directionDistance < 0 ) {
  3223. return target.copy( this.origin );
  3224. }
  3225. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3226. }
  3227. distanceToPoint( point ) {
  3228. return Math.sqrt( this.distanceSqToPoint( point ) );
  3229. }
  3230. distanceSqToPoint( point ) {
  3231. const directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );
  3232. // point behind the ray
  3233. if ( directionDistance < 0 ) {
  3234. return this.origin.distanceToSquared( point );
  3235. }
  3236. _vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3237. return _vector$9.distanceToSquared( point );
  3238. }
  3239. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3240. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3241. // It returns the min distance between the ray and the segment
  3242. // defined by v0 and v1
  3243. // It can also set two optional targets :
  3244. // - The closest point on the ray
  3245. // - The closest point on the segment
  3246. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3247. _segDir.copy( v1 ).sub( v0 ).normalize();
  3248. _diff.copy( this.origin ).sub( _segCenter );
  3249. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3250. const a01 = - this.direction.dot( _segDir );
  3251. const b0 = _diff.dot( this.direction );
  3252. const b1 = - _diff.dot( _segDir );
  3253. const c = _diff.lengthSq();
  3254. const det = Math.abs( 1 - a01 * a01 );
  3255. let s0, s1, sqrDist, extDet;
  3256. if ( det > 0 ) {
  3257. // The ray and segment are not parallel.
  3258. s0 = a01 * b1 - b0;
  3259. s1 = a01 * b0 - b1;
  3260. extDet = segExtent * det;
  3261. if ( s0 >= 0 ) {
  3262. if ( s1 >= - extDet ) {
  3263. if ( s1 <= extDet ) {
  3264. // region 0
  3265. // Minimum at interior points of ray and segment.
  3266. const invDet = 1 / det;
  3267. s0 *= invDet;
  3268. s1 *= invDet;
  3269. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3270. } else {
  3271. // region 1
  3272. s1 = segExtent;
  3273. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3274. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3275. }
  3276. } else {
  3277. // region 5
  3278. s1 = - segExtent;
  3279. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3280. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3281. }
  3282. } else {
  3283. if ( s1 <= - extDet ) {
  3284. // region 4
  3285. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3286. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3287. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3288. } else if ( s1 <= extDet ) {
  3289. // region 3
  3290. s0 = 0;
  3291. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3292. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3293. } else {
  3294. // region 2
  3295. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3296. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3297. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3298. }
  3299. }
  3300. } else {
  3301. // Ray and segment are parallel.
  3302. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3303. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3304. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3305. }
  3306. if ( optionalPointOnRay ) {
  3307. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3308. }
  3309. if ( optionalPointOnSegment ) {
  3310. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3311. }
  3312. return sqrDist;
  3313. }
  3314. intersectSphere( sphere, target ) {
  3315. _vector$9.subVectors( sphere.center, this.origin );
  3316. const tca = _vector$9.dot( this.direction );
  3317. const d2 = _vector$9.dot( _vector$9 ) - tca * tca;
  3318. const radius2 = sphere.radius * sphere.radius;
  3319. if ( d2 > radius2 ) return null;
  3320. const thc = Math.sqrt( radius2 - d2 );
  3321. // t0 = first intersect point - entrance on front of sphere
  3322. const t0 = tca - thc;
  3323. // t1 = second intersect point - exit point on back of sphere
  3324. const t1 = tca + thc;
  3325. // test to see if t1 is behind the ray - if so, return null
  3326. if ( t1 < 0 ) return null;
  3327. // test to see if t0 is behind the ray:
  3328. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3329. // in order to always return an intersect point that is in front of the ray.
  3330. if ( t0 < 0 ) return this.at( t1, target );
  3331. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3332. return this.at( t0, target );
  3333. }
  3334. intersectsSphere( sphere ) {
  3335. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3336. }
  3337. distanceToPlane( plane ) {
  3338. const denominator = plane.normal.dot( this.direction );
  3339. if ( denominator === 0 ) {
  3340. // line is coplanar, return origin
  3341. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3342. return 0;
  3343. }
  3344. // Null is preferable to undefined since undefined means.... it is undefined
  3345. return null;
  3346. }
  3347. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3348. // Return if the ray never intersects the plane
  3349. return t >= 0 ? t : null;
  3350. }
  3351. intersectPlane( plane, target ) {
  3352. const t = this.distanceToPlane( plane );
  3353. if ( t === null ) {
  3354. return null;
  3355. }
  3356. return this.at( t, target );
  3357. }
  3358. intersectsPlane( plane ) {
  3359. // check if the ray lies on the plane first
  3360. const distToPoint = plane.distanceToPoint( this.origin );
  3361. if ( distToPoint === 0 ) {
  3362. return true;
  3363. }
  3364. const denominator = plane.normal.dot( this.direction );
  3365. if ( denominator * distToPoint < 0 ) {
  3366. return true;
  3367. }
  3368. // ray origin is behind the plane (and is pointing behind it)
  3369. return false;
  3370. }
  3371. intersectBox( box, target ) {
  3372. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3373. const invdirx = 1 / this.direction.x,
  3374. invdiry = 1 / this.direction.y,
  3375. invdirz = 1 / this.direction.z;
  3376. const origin = this.origin;
  3377. if ( invdirx >= 0 ) {
  3378. tmin = ( box.min.x - origin.x ) * invdirx;
  3379. tmax = ( box.max.x - origin.x ) * invdirx;
  3380. } else {
  3381. tmin = ( box.max.x - origin.x ) * invdirx;
  3382. tmax = ( box.min.x - origin.x ) * invdirx;
  3383. }
  3384. if ( invdiry >= 0 ) {
  3385. tymin = ( box.min.y - origin.y ) * invdiry;
  3386. tymax = ( box.max.y - origin.y ) * invdiry;
  3387. } else {
  3388. tymin = ( box.max.y - origin.y ) * invdiry;
  3389. tymax = ( box.min.y - origin.y ) * invdiry;
  3390. }
  3391. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3392. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3393. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3394. if ( invdirz >= 0 ) {
  3395. tzmin = ( box.min.z - origin.z ) * invdirz;
  3396. tzmax = ( box.max.z - origin.z ) * invdirz;
  3397. } else {
  3398. tzmin = ( box.max.z - origin.z ) * invdirz;
  3399. tzmax = ( box.min.z - origin.z ) * invdirz;
  3400. }
  3401. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3402. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3403. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3404. //return point closest to the ray (positive side)
  3405. if ( tmax < 0 ) return null;
  3406. return this.at( tmin >= 0 ? tmin : tmax, target );
  3407. }
  3408. intersectsBox( box ) {
  3409. return this.intersectBox( box, _vector$9 ) !== null;
  3410. }
  3411. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3412. // Compute the offset origin, edges, and normal.
  3413. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3414. _edge1.subVectors( b, a );
  3415. _edge2.subVectors( c, a );
  3416. _normal$1.crossVectors( _edge1, _edge2 );
  3417. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3418. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3419. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3420. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3421. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3422. let DdN = this.direction.dot( _normal$1 );
  3423. let sign;
  3424. if ( DdN > 0 ) {
  3425. if ( backfaceCulling ) return null;
  3426. sign = 1;
  3427. } else if ( DdN < 0 ) {
  3428. sign = - 1;
  3429. DdN = - DdN;
  3430. } else {
  3431. return null;
  3432. }
  3433. _diff.subVectors( this.origin, a );
  3434. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3435. // b1 < 0, no intersection
  3436. if ( DdQxE2 < 0 ) {
  3437. return null;
  3438. }
  3439. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3440. // b2 < 0, no intersection
  3441. if ( DdE1xQ < 0 ) {
  3442. return null;
  3443. }
  3444. // b1+b2 > 1, no intersection
  3445. if ( DdQxE2 + DdE1xQ > DdN ) {
  3446. return null;
  3447. }
  3448. // Line intersects triangle, check if ray does.
  3449. const QdN = - sign * _diff.dot( _normal$1 );
  3450. // t < 0, no intersection
  3451. if ( QdN < 0 ) {
  3452. return null;
  3453. }
  3454. // Ray intersects triangle.
  3455. return this.at( QdN / DdN, target );
  3456. }
  3457. applyMatrix4( matrix4 ) {
  3458. this.origin.applyMatrix4( matrix4 );
  3459. this.direction.transformDirection( matrix4 );
  3460. return this;
  3461. }
  3462. equals( ray ) {
  3463. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3464. }
  3465. clone() {
  3466. return new this.constructor().copy( this );
  3467. }
  3468. }
  3469. class Matrix4 {
  3470. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3471. Matrix4.prototype.isMatrix4 = true;
  3472. this.elements = [
  3473. 1, 0, 0, 0,
  3474. 0, 1, 0, 0,
  3475. 0, 0, 1, 0,
  3476. 0, 0, 0, 1
  3477. ];
  3478. if ( n11 !== undefined ) {
  3479. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3480. }
  3481. }
  3482. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3483. const te = this.elements;
  3484. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3485. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3486. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3487. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3488. return this;
  3489. }
  3490. identity() {
  3491. this.set(
  3492. 1, 0, 0, 0,
  3493. 0, 1, 0, 0,
  3494. 0, 0, 1, 0,
  3495. 0, 0, 0, 1
  3496. );
  3497. return this;
  3498. }
  3499. clone() {
  3500. return new Matrix4().fromArray( this.elements );
  3501. }
  3502. copy( m ) {
  3503. const te = this.elements;
  3504. const me = m.elements;
  3505. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3506. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3507. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3508. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3509. return this;
  3510. }
  3511. copyPosition( m ) {
  3512. const te = this.elements, me = m.elements;
  3513. te[ 12 ] = me[ 12 ];
  3514. te[ 13 ] = me[ 13 ];
  3515. te[ 14 ] = me[ 14 ];
  3516. return this;
  3517. }
  3518. setFromMatrix3( m ) {
  3519. const me = m.elements;
  3520. this.set(
  3521. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3522. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3523. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3524. 0, 0, 0, 1
  3525. );
  3526. return this;
  3527. }
  3528. extractBasis( xAxis, yAxis, zAxis ) {
  3529. xAxis.setFromMatrixColumn( this, 0 );
  3530. yAxis.setFromMatrixColumn( this, 1 );
  3531. zAxis.setFromMatrixColumn( this, 2 );
  3532. return this;
  3533. }
  3534. makeBasis( xAxis, yAxis, zAxis ) {
  3535. this.set(
  3536. xAxis.x, yAxis.x, zAxis.x, 0,
  3537. xAxis.y, yAxis.y, zAxis.y, 0,
  3538. xAxis.z, yAxis.z, zAxis.z, 0,
  3539. 0, 0, 0, 1
  3540. );
  3541. return this;
  3542. }
  3543. extractRotation( m ) {
  3544. // this method does not support reflection matrices
  3545. const te = this.elements;
  3546. const me = m.elements;
  3547. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3548. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3549. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3550. te[ 0 ] = me[ 0 ] * scaleX;
  3551. te[ 1 ] = me[ 1 ] * scaleX;
  3552. te[ 2 ] = me[ 2 ] * scaleX;
  3553. te[ 3 ] = 0;
  3554. te[ 4 ] = me[ 4 ] * scaleY;
  3555. te[ 5 ] = me[ 5 ] * scaleY;
  3556. te[ 6 ] = me[ 6 ] * scaleY;
  3557. te[ 7 ] = 0;
  3558. te[ 8 ] = me[ 8 ] * scaleZ;
  3559. te[ 9 ] = me[ 9 ] * scaleZ;
  3560. te[ 10 ] = me[ 10 ] * scaleZ;
  3561. te[ 11 ] = 0;
  3562. te[ 12 ] = 0;
  3563. te[ 13 ] = 0;
  3564. te[ 14 ] = 0;
  3565. te[ 15 ] = 1;
  3566. return this;
  3567. }
  3568. makeRotationFromEuler( euler ) {
  3569. const te = this.elements;
  3570. const x = euler.x, y = euler.y, z = euler.z;
  3571. const a = Math.cos( x ), b = Math.sin( x );
  3572. const c = Math.cos( y ), d = Math.sin( y );
  3573. const e = Math.cos( z ), f = Math.sin( z );
  3574. if ( euler.order === 'XYZ' ) {
  3575. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3576. te[ 0 ] = c * e;
  3577. te[ 4 ] = - c * f;
  3578. te[ 8 ] = d;
  3579. te[ 1 ] = af + be * d;
  3580. te[ 5 ] = ae - bf * d;
  3581. te[ 9 ] = - b * c;
  3582. te[ 2 ] = bf - ae * d;
  3583. te[ 6 ] = be + af * d;
  3584. te[ 10 ] = a * c;
  3585. } else if ( euler.order === 'YXZ' ) {
  3586. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3587. te[ 0 ] = ce + df * b;
  3588. te[ 4 ] = de * b - cf;
  3589. te[ 8 ] = a * d;
  3590. te[ 1 ] = a * f;
  3591. te[ 5 ] = a * e;
  3592. te[ 9 ] = - b;
  3593. te[ 2 ] = cf * b - de;
  3594. te[ 6 ] = df + ce * b;
  3595. te[ 10 ] = a * c;
  3596. } else if ( euler.order === 'ZXY' ) {
  3597. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3598. te[ 0 ] = ce - df * b;
  3599. te[ 4 ] = - a * f;
  3600. te[ 8 ] = de + cf * b;
  3601. te[ 1 ] = cf + de * b;
  3602. te[ 5 ] = a * e;
  3603. te[ 9 ] = df - ce * b;
  3604. te[ 2 ] = - a * d;
  3605. te[ 6 ] = b;
  3606. te[ 10 ] = a * c;
  3607. } else if ( euler.order === 'ZYX' ) {
  3608. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3609. te[ 0 ] = c * e;
  3610. te[ 4 ] = be * d - af;
  3611. te[ 8 ] = ae * d + bf;
  3612. te[ 1 ] = c * f;
  3613. te[ 5 ] = bf * d + ae;
  3614. te[ 9 ] = af * d - be;
  3615. te[ 2 ] = - d;
  3616. te[ 6 ] = b * c;
  3617. te[ 10 ] = a * c;
  3618. } else if ( euler.order === 'YZX' ) {
  3619. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3620. te[ 0 ] = c * e;
  3621. te[ 4 ] = bd - ac * f;
  3622. te[ 8 ] = bc * f + ad;
  3623. te[ 1 ] = f;
  3624. te[ 5 ] = a * e;
  3625. te[ 9 ] = - b * e;
  3626. te[ 2 ] = - d * e;
  3627. te[ 6 ] = ad * f + bc;
  3628. te[ 10 ] = ac - bd * f;
  3629. } else if ( euler.order === 'XZY' ) {
  3630. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3631. te[ 0 ] = c * e;
  3632. te[ 4 ] = - f;
  3633. te[ 8 ] = d * e;
  3634. te[ 1 ] = ac * f + bd;
  3635. te[ 5 ] = a * e;
  3636. te[ 9 ] = ad * f - bc;
  3637. te[ 2 ] = bc * f - ad;
  3638. te[ 6 ] = b * e;
  3639. te[ 10 ] = bd * f + ac;
  3640. }
  3641. // bottom row
  3642. te[ 3 ] = 0;
  3643. te[ 7 ] = 0;
  3644. te[ 11 ] = 0;
  3645. // last column
  3646. te[ 12 ] = 0;
  3647. te[ 13 ] = 0;
  3648. te[ 14 ] = 0;
  3649. te[ 15 ] = 1;
  3650. return this;
  3651. }
  3652. makeRotationFromQuaternion( q ) {
  3653. return this.compose( _zero, q, _one );
  3654. }
  3655. lookAt( eye, target, up ) {
  3656. const te = this.elements;
  3657. _z.subVectors( eye, target );
  3658. if ( _z.lengthSq() === 0 ) {
  3659. // eye and target are in the same position
  3660. _z.z = 1;
  3661. }
  3662. _z.normalize();
  3663. _x.crossVectors( up, _z );
  3664. if ( _x.lengthSq() === 0 ) {
  3665. // up and z are parallel
  3666. if ( Math.abs( up.z ) === 1 ) {
  3667. _z.x += 0.0001;
  3668. } else {
  3669. _z.z += 0.0001;
  3670. }
  3671. _z.normalize();
  3672. _x.crossVectors( up, _z );
  3673. }
  3674. _x.normalize();
  3675. _y.crossVectors( _z, _x );
  3676. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3677. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3678. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3679. return this;
  3680. }
  3681. multiply( m ) {
  3682. return this.multiplyMatrices( this, m );
  3683. }
  3684. premultiply( m ) {
  3685. return this.multiplyMatrices( m, this );
  3686. }
  3687. multiplyMatrices( a, b ) {
  3688. const ae = a.elements;
  3689. const be = b.elements;
  3690. const te = this.elements;
  3691. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3692. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3693. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3694. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3695. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3696. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3697. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3698. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3699. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3700. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3701. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3702. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3703. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3704. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3705. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3706. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3707. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3708. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3709. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3710. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3711. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3712. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3713. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3714. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3715. return this;
  3716. }
  3717. multiplyScalar( s ) {
  3718. const te = this.elements;
  3719. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3720. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3721. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3722. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3723. return this;
  3724. }
  3725. determinant() {
  3726. const te = this.elements;
  3727. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3728. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3729. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3730. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3731. //TODO: make this more efficient
  3732. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3733. return (
  3734. n41 * (
  3735. + n14 * n23 * n32
  3736. - n13 * n24 * n32
  3737. - n14 * n22 * n33
  3738. + n12 * n24 * n33
  3739. + n13 * n22 * n34
  3740. - n12 * n23 * n34
  3741. ) +
  3742. n42 * (
  3743. + n11 * n23 * n34
  3744. - n11 * n24 * n33
  3745. + n14 * n21 * n33
  3746. - n13 * n21 * n34
  3747. + n13 * n24 * n31
  3748. - n14 * n23 * n31
  3749. ) +
  3750. n43 * (
  3751. + n11 * n24 * n32
  3752. - n11 * n22 * n34
  3753. - n14 * n21 * n32
  3754. + n12 * n21 * n34
  3755. + n14 * n22 * n31
  3756. - n12 * n24 * n31
  3757. ) +
  3758. n44 * (
  3759. - n13 * n22 * n31
  3760. - n11 * n23 * n32
  3761. + n11 * n22 * n33
  3762. + n13 * n21 * n32
  3763. - n12 * n21 * n33
  3764. + n12 * n23 * n31
  3765. )
  3766. );
  3767. }
  3768. transpose() {
  3769. const te = this.elements;
  3770. let tmp;
  3771. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3772. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3773. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3774. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3775. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3776. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3777. return this;
  3778. }
  3779. setPosition( x, y, z ) {
  3780. const te = this.elements;
  3781. if ( x.isVector3 ) {
  3782. te[ 12 ] = x.x;
  3783. te[ 13 ] = x.y;
  3784. te[ 14 ] = x.z;
  3785. } else {
  3786. te[ 12 ] = x;
  3787. te[ 13 ] = y;
  3788. te[ 14 ] = z;
  3789. }
  3790. return this;
  3791. }
  3792. invert() {
  3793. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3794. const te = this.elements,
  3795. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3796. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3797. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3798. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3799. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3800. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3801. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3802. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3803. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3804. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3805. const detInv = 1 / det;
  3806. te[ 0 ] = t11 * detInv;
  3807. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3808. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3809. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3810. te[ 4 ] = t12 * detInv;
  3811. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3812. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3813. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3814. te[ 8 ] = t13 * detInv;
  3815. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3816. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3817. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3818. te[ 12 ] = t14 * detInv;
  3819. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3820. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3821. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3822. return this;
  3823. }
  3824. scale( v ) {
  3825. const te = this.elements;
  3826. const x = v.x, y = v.y, z = v.z;
  3827. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3828. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3829. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3830. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3831. return this;
  3832. }
  3833. getMaxScaleOnAxis() {
  3834. const te = this.elements;
  3835. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3836. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3837. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3838. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3839. }
  3840. makeTranslation( x, y, z ) {
  3841. if ( x.isVector3 ) {
  3842. this.set(
  3843. 1, 0, 0, x.x,
  3844. 0, 1, 0, x.y,
  3845. 0, 0, 1, x.z,
  3846. 0, 0, 0, 1
  3847. );
  3848. } else {
  3849. this.set(
  3850. 1, 0, 0, x,
  3851. 0, 1, 0, y,
  3852. 0, 0, 1, z,
  3853. 0, 0, 0, 1
  3854. );
  3855. }
  3856. return this;
  3857. }
  3858. makeRotationX( theta ) {
  3859. const c = Math.cos( theta ), s = Math.sin( theta );
  3860. this.set(
  3861. 1, 0, 0, 0,
  3862. 0, c, - s, 0,
  3863. 0, s, c, 0,
  3864. 0, 0, 0, 1
  3865. );
  3866. return this;
  3867. }
  3868. makeRotationY( theta ) {
  3869. const c = Math.cos( theta ), s = Math.sin( theta );
  3870. this.set(
  3871. c, 0, s, 0,
  3872. 0, 1, 0, 0,
  3873. - s, 0, c, 0,
  3874. 0, 0, 0, 1
  3875. );
  3876. return this;
  3877. }
  3878. makeRotationZ( theta ) {
  3879. const c = Math.cos( theta ), s = Math.sin( theta );
  3880. this.set(
  3881. c, - s, 0, 0,
  3882. s, c, 0, 0,
  3883. 0, 0, 1, 0,
  3884. 0, 0, 0, 1
  3885. );
  3886. return this;
  3887. }
  3888. makeRotationAxis( axis, angle ) {
  3889. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3890. const c = Math.cos( angle );
  3891. const s = Math.sin( angle );
  3892. const t = 1 - c;
  3893. const x = axis.x, y = axis.y, z = axis.z;
  3894. const tx = t * x, ty = t * y;
  3895. this.set(
  3896. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3897. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3898. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3899. 0, 0, 0, 1
  3900. );
  3901. return this;
  3902. }
  3903. makeScale( x, y, z ) {
  3904. this.set(
  3905. x, 0, 0, 0,
  3906. 0, y, 0, 0,
  3907. 0, 0, z, 0,
  3908. 0, 0, 0, 1
  3909. );
  3910. return this;
  3911. }
  3912. makeShear( xy, xz, yx, yz, zx, zy ) {
  3913. this.set(
  3914. 1, yx, zx, 0,
  3915. xy, 1, zy, 0,
  3916. xz, yz, 1, 0,
  3917. 0, 0, 0, 1
  3918. );
  3919. return this;
  3920. }
  3921. compose( position, quaternion, scale ) {
  3922. const te = this.elements;
  3923. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3924. const x2 = x + x, y2 = y + y, z2 = z + z;
  3925. const xx = x * x2, xy = x * y2, xz = x * z2;
  3926. const yy = y * y2, yz = y * z2, zz = z * z2;
  3927. const wx = w * x2, wy = w * y2, wz = w * z2;
  3928. const sx = scale.x, sy = scale.y, sz = scale.z;
  3929. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3930. te[ 1 ] = ( xy + wz ) * sx;
  3931. te[ 2 ] = ( xz - wy ) * sx;
  3932. te[ 3 ] = 0;
  3933. te[ 4 ] = ( xy - wz ) * sy;
  3934. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3935. te[ 6 ] = ( yz + wx ) * sy;
  3936. te[ 7 ] = 0;
  3937. te[ 8 ] = ( xz + wy ) * sz;
  3938. te[ 9 ] = ( yz - wx ) * sz;
  3939. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3940. te[ 11 ] = 0;
  3941. te[ 12 ] = position.x;
  3942. te[ 13 ] = position.y;
  3943. te[ 14 ] = position.z;
  3944. te[ 15 ] = 1;
  3945. return this;
  3946. }
  3947. decompose( position, quaternion, scale ) {
  3948. const te = this.elements;
  3949. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3950. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3951. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3952. // if determine is negative, we need to invert one scale
  3953. const det = this.determinant();
  3954. if ( det < 0 ) sx = - sx;
  3955. position.x = te[ 12 ];
  3956. position.y = te[ 13 ];
  3957. position.z = te[ 14 ];
  3958. // scale the rotation part
  3959. _m1$2.copy( this );
  3960. const invSX = 1 / sx;
  3961. const invSY = 1 / sy;
  3962. const invSZ = 1 / sz;
  3963. _m1$2.elements[ 0 ] *= invSX;
  3964. _m1$2.elements[ 1 ] *= invSX;
  3965. _m1$2.elements[ 2 ] *= invSX;
  3966. _m1$2.elements[ 4 ] *= invSY;
  3967. _m1$2.elements[ 5 ] *= invSY;
  3968. _m1$2.elements[ 6 ] *= invSY;
  3969. _m1$2.elements[ 8 ] *= invSZ;
  3970. _m1$2.elements[ 9 ] *= invSZ;
  3971. _m1$2.elements[ 10 ] *= invSZ;
  3972. quaternion.setFromRotationMatrix( _m1$2 );
  3973. scale.x = sx;
  3974. scale.y = sy;
  3975. scale.z = sz;
  3976. return this;
  3977. }
  3978. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  3979. const te = this.elements;
  3980. const x = 2 * near / ( right - left );
  3981. const y = 2 * near / ( top - bottom );
  3982. const a = ( right + left ) / ( right - left );
  3983. const b = ( top + bottom ) / ( top - bottom );
  3984. let c, d;
  3985. if ( coordinateSystem === WebGLCoordinateSystem ) {
  3986. c = - ( far + near ) / ( far - near );
  3987. d = ( - 2 * far * near ) / ( far - near );
  3988. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  3989. c = - far / ( far - near );
  3990. d = ( - far * near ) / ( far - near );
  3991. } else {
  3992. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  3993. }
  3994. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3995. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3996. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3997. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3998. return this;
  3999. }
  4000. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4001. const te = this.elements;
  4002. const w = 1.0 / ( right - left );
  4003. const h = 1.0 / ( top - bottom );
  4004. const p = 1.0 / ( far - near );
  4005. const x = ( right + left ) * w;
  4006. const y = ( top + bottom ) * h;
  4007. let z, zInv;
  4008. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4009. z = ( far + near ) * p;
  4010. zInv = - 2 * p;
  4011. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4012. z = near * p;
  4013. zInv = - 1 * p;
  4014. } else {
  4015. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4016. }
  4017. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4018. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4019. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4020. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4021. return this;
  4022. }
  4023. equals( matrix ) {
  4024. const te = this.elements;
  4025. const me = matrix.elements;
  4026. for ( let i = 0; i < 16; i ++ ) {
  4027. if ( te[ i ] !== me[ i ] ) return false;
  4028. }
  4029. return true;
  4030. }
  4031. fromArray( array, offset = 0 ) {
  4032. for ( let i = 0; i < 16; i ++ ) {
  4033. this.elements[ i ] = array[ i + offset ];
  4034. }
  4035. return this;
  4036. }
  4037. toArray( array = [], offset = 0 ) {
  4038. const te = this.elements;
  4039. array[ offset ] = te[ 0 ];
  4040. array[ offset + 1 ] = te[ 1 ];
  4041. array[ offset + 2 ] = te[ 2 ];
  4042. array[ offset + 3 ] = te[ 3 ];
  4043. array[ offset + 4 ] = te[ 4 ];
  4044. array[ offset + 5 ] = te[ 5 ];
  4045. array[ offset + 6 ] = te[ 6 ];
  4046. array[ offset + 7 ] = te[ 7 ];
  4047. array[ offset + 8 ] = te[ 8 ];
  4048. array[ offset + 9 ] = te[ 9 ];
  4049. array[ offset + 10 ] = te[ 10 ];
  4050. array[ offset + 11 ] = te[ 11 ];
  4051. array[ offset + 12 ] = te[ 12 ];
  4052. array[ offset + 13 ] = te[ 13 ];
  4053. array[ offset + 14 ] = te[ 14 ];
  4054. array[ offset + 15 ] = te[ 15 ];
  4055. return array;
  4056. }
  4057. }
  4058. const _v1$5 = /*@__PURE__*/ new Vector3();
  4059. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4060. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4061. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4062. const _x = /*@__PURE__*/ new Vector3();
  4063. const _y = /*@__PURE__*/ new Vector3();
  4064. const _z = /*@__PURE__*/ new Vector3();
  4065. const _matrix = /*@__PURE__*/ new Matrix4();
  4066. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4067. class Euler {
  4068. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4069. this.isEuler = true;
  4070. this._x = x;
  4071. this._y = y;
  4072. this._z = z;
  4073. this._order = order;
  4074. }
  4075. get x() {
  4076. return this._x;
  4077. }
  4078. set x( value ) {
  4079. this._x = value;
  4080. this._onChangeCallback();
  4081. }
  4082. get y() {
  4083. return this._y;
  4084. }
  4085. set y( value ) {
  4086. this._y = value;
  4087. this._onChangeCallback();
  4088. }
  4089. get z() {
  4090. return this._z;
  4091. }
  4092. set z( value ) {
  4093. this._z = value;
  4094. this._onChangeCallback();
  4095. }
  4096. get order() {
  4097. return this._order;
  4098. }
  4099. set order( value ) {
  4100. this._order = value;
  4101. this._onChangeCallback();
  4102. }
  4103. set( x, y, z, order = this._order ) {
  4104. this._x = x;
  4105. this._y = y;
  4106. this._z = z;
  4107. this._order = order;
  4108. this._onChangeCallback();
  4109. return this;
  4110. }
  4111. clone() {
  4112. return new this.constructor( this._x, this._y, this._z, this._order );
  4113. }
  4114. copy( euler ) {
  4115. this._x = euler._x;
  4116. this._y = euler._y;
  4117. this._z = euler._z;
  4118. this._order = euler._order;
  4119. this._onChangeCallback();
  4120. return this;
  4121. }
  4122. setFromRotationMatrix( m, order = this._order, update = true ) {
  4123. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4124. const te = m.elements;
  4125. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4126. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4127. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4128. switch ( order ) {
  4129. case 'XYZ':
  4130. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4131. if ( Math.abs( m13 ) < 0.9999999 ) {
  4132. this._x = Math.atan2( - m23, m33 );
  4133. this._z = Math.atan2( - m12, m11 );
  4134. } else {
  4135. this._x = Math.atan2( m32, m22 );
  4136. this._z = 0;
  4137. }
  4138. break;
  4139. case 'YXZ':
  4140. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4141. if ( Math.abs( m23 ) < 0.9999999 ) {
  4142. this._y = Math.atan2( m13, m33 );
  4143. this._z = Math.atan2( m21, m22 );
  4144. } else {
  4145. this._y = Math.atan2( - m31, m11 );
  4146. this._z = 0;
  4147. }
  4148. break;
  4149. case 'ZXY':
  4150. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4151. if ( Math.abs( m32 ) < 0.9999999 ) {
  4152. this._y = Math.atan2( - m31, m33 );
  4153. this._z = Math.atan2( - m12, m22 );
  4154. } else {
  4155. this._y = 0;
  4156. this._z = Math.atan2( m21, m11 );
  4157. }
  4158. break;
  4159. case 'ZYX':
  4160. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4161. if ( Math.abs( m31 ) < 0.9999999 ) {
  4162. this._x = Math.atan2( m32, m33 );
  4163. this._z = Math.atan2( m21, m11 );
  4164. } else {
  4165. this._x = 0;
  4166. this._z = Math.atan2( - m12, m22 );
  4167. }
  4168. break;
  4169. case 'YZX':
  4170. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4171. if ( Math.abs( m21 ) < 0.9999999 ) {
  4172. this._x = Math.atan2( - m23, m22 );
  4173. this._y = Math.atan2( - m31, m11 );
  4174. } else {
  4175. this._x = 0;
  4176. this._y = Math.atan2( m13, m33 );
  4177. }
  4178. break;
  4179. case 'XZY':
  4180. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4181. if ( Math.abs( m12 ) < 0.9999999 ) {
  4182. this._x = Math.atan2( m32, m22 );
  4183. this._y = Math.atan2( m13, m11 );
  4184. } else {
  4185. this._x = Math.atan2( - m23, m33 );
  4186. this._y = 0;
  4187. }
  4188. break;
  4189. default:
  4190. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4191. }
  4192. this._order = order;
  4193. if ( update === true ) this._onChangeCallback();
  4194. return this;
  4195. }
  4196. setFromQuaternion( q, order, update ) {
  4197. _matrix.makeRotationFromQuaternion( q );
  4198. return this.setFromRotationMatrix( _matrix, order, update );
  4199. }
  4200. setFromVector3( v, order = this._order ) {
  4201. return this.set( v.x, v.y, v.z, order );
  4202. }
  4203. reorder( newOrder ) {
  4204. // WARNING: this discards revolution information -bhouston
  4205. _quaternion$3.setFromEuler( this );
  4206. return this.setFromQuaternion( _quaternion$3, newOrder );
  4207. }
  4208. equals( euler ) {
  4209. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4210. }
  4211. fromArray( array ) {
  4212. this._x = array[ 0 ];
  4213. this._y = array[ 1 ];
  4214. this._z = array[ 2 ];
  4215. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4216. this._onChangeCallback();
  4217. return this;
  4218. }
  4219. toArray( array = [], offset = 0 ) {
  4220. array[ offset ] = this._x;
  4221. array[ offset + 1 ] = this._y;
  4222. array[ offset + 2 ] = this._z;
  4223. array[ offset + 3 ] = this._order;
  4224. return array;
  4225. }
  4226. _onChange( callback ) {
  4227. this._onChangeCallback = callback;
  4228. return this;
  4229. }
  4230. _onChangeCallback() {}
  4231. *[ Symbol.iterator ]() {
  4232. yield this._x;
  4233. yield this._y;
  4234. yield this._z;
  4235. yield this._order;
  4236. }
  4237. }
  4238. Euler.DEFAULT_ORDER = 'XYZ';
  4239. class Layers {
  4240. constructor() {
  4241. this.mask = 1 | 0;
  4242. }
  4243. set( channel ) {
  4244. this.mask = ( 1 << channel | 0 ) >>> 0;
  4245. }
  4246. enable( channel ) {
  4247. this.mask |= 1 << channel | 0;
  4248. }
  4249. enableAll() {
  4250. this.mask = 0xffffffff | 0;
  4251. }
  4252. toggle( channel ) {
  4253. this.mask ^= 1 << channel | 0;
  4254. }
  4255. disable( channel ) {
  4256. this.mask &= ~ ( 1 << channel | 0 );
  4257. }
  4258. disableAll() {
  4259. this.mask = 0;
  4260. }
  4261. test( layers ) {
  4262. return ( this.mask & layers.mask ) !== 0;
  4263. }
  4264. isEnabled( channel ) {
  4265. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4266. }
  4267. }
  4268. let _object3DId = 0;
  4269. const _v1$4 = /*@__PURE__*/ new Vector3();
  4270. const _q1 = /*@__PURE__*/ new Quaternion();
  4271. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4272. const _target = /*@__PURE__*/ new Vector3();
  4273. const _position$3 = /*@__PURE__*/ new Vector3();
  4274. const _scale$2 = /*@__PURE__*/ new Vector3();
  4275. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4276. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4277. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4278. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4279. const _addedEvent = { type: 'added' };
  4280. const _removedEvent = { type: 'removed' };
  4281. class Object3D extends EventDispatcher {
  4282. constructor() {
  4283. super();
  4284. this.isObject3D = true;
  4285. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4286. this.uuid = generateUUID();
  4287. this.name = '';
  4288. this.type = 'Object3D';
  4289. this.parent = null;
  4290. this.children = [];
  4291. this.up = Object3D.DEFAULT_UP.clone();
  4292. const position = new Vector3();
  4293. const rotation = new Euler();
  4294. const quaternion = new Quaternion();
  4295. const scale = new Vector3( 1, 1, 1 );
  4296. function onRotationChange() {
  4297. quaternion.setFromEuler( rotation, false );
  4298. }
  4299. function onQuaternionChange() {
  4300. rotation.setFromQuaternion( quaternion, undefined, false );
  4301. }
  4302. rotation._onChange( onRotationChange );
  4303. quaternion._onChange( onQuaternionChange );
  4304. Object.defineProperties( this, {
  4305. position: {
  4306. configurable: true,
  4307. enumerable: true,
  4308. value: position
  4309. },
  4310. rotation: {
  4311. configurable: true,
  4312. enumerable: true,
  4313. value: rotation
  4314. },
  4315. quaternion: {
  4316. configurable: true,
  4317. enumerable: true,
  4318. value: quaternion
  4319. },
  4320. scale: {
  4321. configurable: true,
  4322. enumerable: true,
  4323. value: scale
  4324. },
  4325. modelViewMatrix: {
  4326. value: new Matrix4()
  4327. },
  4328. normalMatrix: {
  4329. value: new Matrix3()
  4330. }
  4331. } );
  4332. this.matrix = new Matrix4();
  4333. this.matrixWorld = new Matrix4();
  4334. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4335. this.matrixWorldNeedsUpdate = false;
  4336. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4337. this.layers = new Layers();
  4338. this.visible = true;
  4339. this.castShadow = false;
  4340. this.receiveShadow = false;
  4341. this.frustumCulled = true;
  4342. this.renderOrder = 0;
  4343. this.animations = [];
  4344. this.userData = {};
  4345. }
  4346. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4347. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4348. applyMatrix4( matrix ) {
  4349. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4350. this.matrix.premultiply( matrix );
  4351. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4352. }
  4353. applyQuaternion( q ) {
  4354. this.quaternion.premultiply( q );
  4355. return this;
  4356. }
  4357. setRotationFromAxisAngle( axis, angle ) {
  4358. // assumes axis is normalized
  4359. this.quaternion.setFromAxisAngle( axis, angle );
  4360. }
  4361. setRotationFromEuler( euler ) {
  4362. this.quaternion.setFromEuler( euler, true );
  4363. }
  4364. setRotationFromMatrix( m ) {
  4365. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4366. this.quaternion.setFromRotationMatrix( m );
  4367. }
  4368. setRotationFromQuaternion( q ) {
  4369. // assumes q is normalized
  4370. this.quaternion.copy( q );
  4371. }
  4372. rotateOnAxis( axis, angle ) {
  4373. // rotate object on axis in object space
  4374. // axis is assumed to be normalized
  4375. _q1.setFromAxisAngle( axis, angle );
  4376. this.quaternion.multiply( _q1 );
  4377. return this;
  4378. }
  4379. rotateOnWorldAxis( axis, angle ) {
  4380. // rotate object on axis in world space
  4381. // axis is assumed to be normalized
  4382. // method assumes no rotated parent
  4383. _q1.setFromAxisAngle( axis, angle );
  4384. this.quaternion.premultiply( _q1 );
  4385. return this;
  4386. }
  4387. rotateX( angle ) {
  4388. return this.rotateOnAxis( _xAxis, angle );
  4389. }
  4390. rotateY( angle ) {
  4391. return this.rotateOnAxis( _yAxis, angle );
  4392. }
  4393. rotateZ( angle ) {
  4394. return this.rotateOnAxis( _zAxis, angle );
  4395. }
  4396. translateOnAxis( axis, distance ) {
  4397. // translate object by distance along axis in object space
  4398. // axis is assumed to be normalized
  4399. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4400. this.position.add( _v1$4.multiplyScalar( distance ) );
  4401. return this;
  4402. }
  4403. translateX( distance ) {
  4404. return this.translateOnAxis( _xAxis, distance );
  4405. }
  4406. translateY( distance ) {
  4407. return this.translateOnAxis( _yAxis, distance );
  4408. }
  4409. translateZ( distance ) {
  4410. return this.translateOnAxis( _zAxis, distance );
  4411. }
  4412. localToWorld( vector ) {
  4413. this.updateWorldMatrix( true, false );
  4414. return vector.applyMatrix4( this.matrixWorld );
  4415. }
  4416. worldToLocal( vector ) {
  4417. this.updateWorldMatrix( true, false );
  4418. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4419. }
  4420. lookAt( x, y, z ) {
  4421. // This method does not support objects having non-uniformly-scaled parent(s)
  4422. if ( x.isVector3 ) {
  4423. _target.copy( x );
  4424. } else {
  4425. _target.set( x, y, z );
  4426. }
  4427. const parent = this.parent;
  4428. this.updateWorldMatrix( true, false );
  4429. _position$3.setFromMatrixPosition( this.matrixWorld );
  4430. if ( this.isCamera || this.isLight ) {
  4431. _m1$1.lookAt( _position$3, _target, this.up );
  4432. } else {
  4433. _m1$1.lookAt( _target, _position$3, this.up );
  4434. }
  4435. this.quaternion.setFromRotationMatrix( _m1$1 );
  4436. if ( parent ) {
  4437. _m1$1.extractRotation( parent.matrixWorld );
  4438. _q1.setFromRotationMatrix( _m1$1 );
  4439. this.quaternion.premultiply( _q1.invert() );
  4440. }
  4441. }
  4442. add( object ) {
  4443. if ( arguments.length > 1 ) {
  4444. for ( let i = 0; i < arguments.length; i ++ ) {
  4445. this.add( arguments[ i ] );
  4446. }
  4447. return this;
  4448. }
  4449. if ( object === this ) {
  4450. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4451. return this;
  4452. }
  4453. if ( object && object.isObject3D ) {
  4454. if ( object.parent !== null ) {
  4455. object.parent.remove( object );
  4456. }
  4457. object.parent = this;
  4458. this.children.push( object );
  4459. object.dispatchEvent( _addedEvent );
  4460. } else {
  4461. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4462. }
  4463. return this;
  4464. }
  4465. remove( object ) {
  4466. if ( arguments.length > 1 ) {
  4467. for ( let i = 0; i < arguments.length; i ++ ) {
  4468. this.remove( arguments[ i ] );
  4469. }
  4470. return this;
  4471. }
  4472. const index = this.children.indexOf( object );
  4473. if ( index !== - 1 ) {
  4474. object.parent = null;
  4475. this.children.splice( index, 1 );
  4476. object.dispatchEvent( _removedEvent );
  4477. }
  4478. return this;
  4479. }
  4480. removeFromParent() {
  4481. const parent = this.parent;
  4482. if ( parent !== null ) {
  4483. parent.remove( this );
  4484. }
  4485. return this;
  4486. }
  4487. clear() {
  4488. for ( let i = 0; i < this.children.length; i ++ ) {
  4489. const object = this.children[ i ];
  4490. object.parent = null;
  4491. object.dispatchEvent( _removedEvent );
  4492. }
  4493. this.children.length = 0;
  4494. return this;
  4495. }
  4496. attach( object ) {
  4497. // adds object as a child of this, while maintaining the object's world transform
  4498. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4499. this.updateWorldMatrix( true, false );
  4500. _m1$1.copy( this.matrixWorld ).invert();
  4501. if ( object.parent !== null ) {
  4502. object.parent.updateWorldMatrix( true, false );
  4503. _m1$1.multiply( object.parent.matrixWorld );
  4504. }
  4505. object.applyMatrix4( _m1$1 );
  4506. this.add( object );
  4507. object.updateWorldMatrix( false, true );
  4508. return this;
  4509. }
  4510. getObjectById( id ) {
  4511. return this.getObjectByProperty( 'id', id );
  4512. }
  4513. getObjectByName( name ) {
  4514. return this.getObjectByProperty( 'name', name );
  4515. }
  4516. getObjectByProperty( name, value ) {
  4517. if ( this[ name ] === value ) return this;
  4518. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4519. const child = this.children[ i ];
  4520. const object = child.getObjectByProperty( name, value );
  4521. if ( object !== undefined ) {
  4522. return object;
  4523. }
  4524. }
  4525. return undefined;
  4526. }
  4527. getObjectsByProperty( name, value ) {
  4528. let result = [];
  4529. if ( this[ name ] === value ) result.push( this );
  4530. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4531. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4532. if ( childResult.length > 0 ) {
  4533. result = result.concat( childResult );
  4534. }
  4535. }
  4536. return result;
  4537. }
  4538. getWorldPosition( target ) {
  4539. this.updateWorldMatrix( true, false );
  4540. return target.setFromMatrixPosition( this.matrixWorld );
  4541. }
  4542. getWorldQuaternion( target ) {
  4543. this.updateWorldMatrix( true, false );
  4544. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4545. return target;
  4546. }
  4547. getWorldScale( target ) {
  4548. this.updateWorldMatrix( true, false );
  4549. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4550. return target;
  4551. }
  4552. getWorldDirection( target ) {
  4553. this.updateWorldMatrix( true, false );
  4554. const e = this.matrixWorld.elements;
  4555. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4556. }
  4557. raycast( /* raycaster, intersects */ ) {}
  4558. traverse( callback ) {
  4559. callback( this );
  4560. const children = this.children;
  4561. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4562. children[ i ].traverse( callback );
  4563. }
  4564. }
  4565. traverseVisible( callback ) {
  4566. if ( this.visible === false ) return;
  4567. callback( this );
  4568. const children = this.children;
  4569. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4570. children[ i ].traverseVisible( callback );
  4571. }
  4572. }
  4573. traverseAncestors( callback ) {
  4574. const parent = this.parent;
  4575. if ( parent !== null ) {
  4576. callback( parent );
  4577. parent.traverseAncestors( callback );
  4578. }
  4579. }
  4580. updateMatrix() {
  4581. this.matrix.compose( this.position, this.quaternion, this.scale );
  4582. this.matrixWorldNeedsUpdate = true;
  4583. }
  4584. updateMatrixWorld( force ) {
  4585. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4586. if ( this.matrixWorldNeedsUpdate || force ) {
  4587. if ( this.parent === null ) {
  4588. this.matrixWorld.copy( this.matrix );
  4589. } else {
  4590. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4591. }
  4592. this.matrixWorldNeedsUpdate = false;
  4593. force = true;
  4594. }
  4595. // update children
  4596. const children = this.children;
  4597. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4598. const child = children[ i ];
  4599. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4600. child.updateMatrixWorld( force );
  4601. }
  4602. }
  4603. }
  4604. updateWorldMatrix( updateParents, updateChildren ) {
  4605. const parent = this.parent;
  4606. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4607. parent.updateWorldMatrix( true, false );
  4608. }
  4609. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4610. if ( this.parent === null ) {
  4611. this.matrixWorld.copy( this.matrix );
  4612. } else {
  4613. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4614. }
  4615. // update children
  4616. if ( updateChildren === true ) {
  4617. const children = this.children;
  4618. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4619. const child = children[ i ];
  4620. if ( child.matrixWorldAutoUpdate === true ) {
  4621. child.updateWorldMatrix( false, true );
  4622. }
  4623. }
  4624. }
  4625. }
  4626. toJSON( meta ) {
  4627. // meta is a string when called from JSON.stringify
  4628. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4629. const output = {};
  4630. // meta is a hash used to collect geometries, materials.
  4631. // not providing it implies that this is the root object
  4632. // being serialized.
  4633. if ( isRootObject ) {
  4634. // initialize meta obj
  4635. meta = {
  4636. geometries: {},
  4637. materials: {},
  4638. textures: {},
  4639. images: {},
  4640. shapes: {},
  4641. skeletons: {},
  4642. animations: {},
  4643. nodes: {}
  4644. };
  4645. output.metadata = {
  4646. version: 4.6,
  4647. type: 'Object',
  4648. generator: 'Object3D.toJSON'
  4649. };
  4650. }
  4651. // standard Object3D serialization
  4652. const object = {};
  4653. object.uuid = this.uuid;
  4654. object.type = this.type;
  4655. if ( this.name !== '' ) object.name = this.name;
  4656. if ( this.castShadow === true ) object.castShadow = true;
  4657. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4658. if ( this.visible === false ) object.visible = false;
  4659. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4660. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4661. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4662. object.layers = this.layers.mask;
  4663. object.matrix = this.matrix.toArray();
  4664. object.up = this.up.toArray();
  4665. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4666. // object specific properties
  4667. if ( this.isInstancedMesh ) {
  4668. object.type = 'InstancedMesh';
  4669. object.count = this.count;
  4670. object.instanceMatrix = this.instanceMatrix.toJSON();
  4671. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4672. }
  4673. //
  4674. function serialize( library, element ) {
  4675. if ( library[ element.uuid ] === undefined ) {
  4676. library[ element.uuid ] = element.toJSON( meta );
  4677. }
  4678. return element.uuid;
  4679. }
  4680. if ( this.isScene ) {
  4681. if ( this.background ) {
  4682. if ( this.background.isColor ) {
  4683. object.background = this.background.toJSON();
  4684. } else if ( this.background.isTexture ) {
  4685. object.background = this.background.toJSON( meta ).uuid;
  4686. }
  4687. }
  4688. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4689. object.environment = this.environment.toJSON( meta ).uuid;
  4690. }
  4691. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4692. object.geometry = serialize( meta.geometries, this.geometry );
  4693. const parameters = this.geometry.parameters;
  4694. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4695. const shapes = parameters.shapes;
  4696. if ( Array.isArray( shapes ) ) {
  4697. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4698. const shape = shapes[ i ];
  4699. serialize( meta.shapes, shape );
  4700. }
  4701. } else {
  4702. serialize( meta.shapes, shapes );
  4703. }
  4704. }
  4705. }
  4706. if ( this.isSkinnedMesh ) {
  4707. object.bindMode = this.bindMode;
  4708. object.bindMatrix = this.bindMatrix.toArray();
  4709. if ( this.skeleton !== undefined ) {
  4710. serialize( meta.skeletons, this.skeleton );
  4711. object.skeleton = this.skeleton.uuid;
  4712. }
  4713. }
  4714. if ( this.material !== undefined ) {
  4715. if ( Array.isArray( this.material ) ) {
  4716. const uuids = [];
  4717. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4718. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4719. }
  4720. object.material = uuids;
  4721. } else {
  4722. object.material = serialize( meta.materials, this.material );
  4723. }
  4724. }
  4725. //
  4726. if ( this.children.length > 0 ) {
  4727. object.children = [];
  4728. for ( let i = 0; i < this.children.length; i ++ ) {
  4729. object.children.push( this.children[ i ].toJSON( meta ).object );
  4730. }
  4731. }
  4732. //
  4733. if ( this.animations.length > 0 ) {
  4734. object.animations = [];
  4735. for ( let i = 0; i < this.animations.length; i ++ ) {
  4736. const animation = this.animations[ i ];
  4737. object.animations.push( serialize( meta.animations, animation ) );
  4738. }
  4739. }
  4740. if ( isRootObject ) {
  4741. const geometries = extractFromCache( meta.geometries );
  4742. const materials = extractFromCache( meta.materials );
  4743. const textures = extractFromCache( meta.textures );
  4744. const images = extractFromCache( meta.images );
  4745. const shapes = extractFromCache( meta.shapes );
  4746. const skeletons = extractFromCache( meta.skeletons );
  4747. const animations = extractFromCache( meta.animations );
  4748. const nodes = extractFromCache( meta.nodes );
  4749. if ( geometries.length > 0 ) output.geometries = geometries;
  4750. if ( materials.length > 0 ) output.materials = materials;
  4751. if ( textures.length > 0 ) output.textures = textures;
  4752. if ( images.length > 0 ) output.images = images;
  4753. if ( shapes.length > 0 ) output.shapes = shapes;
  4754. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4755. if ( animations.length > 0 ) output.animations = animations;
  4756. if ( nodes.length > 0 ) output.nodes = nodes;
  4757. }
  4758. output.object = object;
  4759. return output;
  4760. // extract data from the cache hash
  4761. // remove metadata on each item
  4762. // and return as array
  4763. function extractFromCache( cache ) {
  4764. const values = [];
  4765. for ( const key in cache ) {
  4766. const data = cache[ key ];
  4767. delete data.metadata;
  4768. values.push( data );
  4769. }
  4770. return values;
  4771. }
  4772. }
  4773. clone( recursive ) {
  4774. return new this.constructor().copy( this, recursive );
  4775. }
  4776. copy( source, recursive = true ) {
  4777. this.name = source.name;
  4778. this.up.copy( source.up );
  4779. this.position.copy( source.position );
  4780. this.rotation.order = source.rotation.order;
  4781. this.quaternion.copy( source.quaternion );
  4782. this.scale.copy( source.scale );
  4783. this.matrix.copy( source.matrix );
  4784. this.matrixWorld.copy( source.matrixWorld );
  4785. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4786. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4787. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4788. this.layers.mask = source.layers.mask;
  4789. this.visible = source.visible;
  4790. this.castShadow = source.castShadow;
  4791. this.receiveShadow = source.receiveShadow;
  4792. this.frustumCulled = source.frustumCulled;
  4793. this.renderOrder = source.renderOrder;
  4794. this.animations = source.animations;
  4795. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4796. if ( recursive === true ) {
  4797. for ( let i = 0; i < source.children.length; i ++ ) {
  4798. const child = source.children[ i ];
  4799. this.add( child.clone() );
  4800. }
  4801. }
  4802. return this;
  4803. }
  4804. }
  4805. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4806. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4807. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4808. const _v0$1 = /*@__PURE__*/ new Vector3();
  4809. const _v1$3 = /*@__PURE__*/ new Vector3();
  4810. const _v2$2 = /*@__PURE__*/ new Vector3();
  4811. const _v3$1 = /*@__PURE__*/ new Vector3();
  4812. const _vab = /*@__PURE__*/ new Vector3();
  4813. const _vac = /*@__PURE__*/ new Vector3();
  4814. const _vbc = /*@__PURE__*/ new Vector3();
  4815. const _vap = /*@__PURE__*/ new Vector3();
  4816. const _vbp = /*@__PURE__*/ new Vector3();
  4817. const _vcp = /*@__PURE__*/ new Vector3();
  4818. let warnedGetUV = false;
  4819. class Triangle {
  4820. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4821. this.a = a;
  4822. this.b = b;
  4823. this.c = c;
  4824. }
  4825. static getNormal( a, b, c, target ) {
  4826. target.subVectors( c, b );
  4827. _v0$1.subVectors( a, b );
  4828. target.cross( _v0$1 );
  4829. const targetLengthSq = target.lengthSq();
  4830. if ( targetLengthSq > 0 ) {
  4831. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4832. }
  4833. return target.set( 0, 0, 0 );
  4834. }
  4835. // static/instance method to calculate barycentric coordinates
  4836. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4837. static getBarycoord( point, a, b, c, target ) {
  4838. _v0$1.subVectors( c, a );
  4839. _v1$3.subVectors( b, a );
  4840. _v2$2.subVectors( point, a );
  4841. const dot00 = _v0$1.dot( _v0$1 );
  4842. const dot01 = _v0$1.dot( _v1$3 );
  4843. const dot02 = _v0$1.dot( _v2$2 );
  4844. const dot11 = _v1$3.dot( _v1$3 );
  4845. const dot12 = _v1$3.dot( _v2$2 );
  4846. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4847. // collinear or singular triangle
  4848. if ( denom === 0 ) {
  4849. // arbitrary location outside of triangle?
  4850. // not sure if this is the best idea, maybe should be returning undefined
  4851. return target.set( - 2, - 1, - 1 );
  4852. }
  4853. const invDenom = 1 / denom;
  4854. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4855. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4856. // barycentric coordinates must always sum to 1
  4857. return target.set( 1 - u - v, v, u );
  4858. }
  4859. static containsPoint( point, a, b, c ) {
  4860. this.getBarycoord( point, a, b, c, _v3$1 );
  4861. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4862. }
  4863. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151
  4864. if ( warnedGetUV === false ) {
  4865. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4866. warnedGetUV = true;
  4867. }
  4868. return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );
  4869. }
  4870. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4871. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4872. target.setScalar( 0 );
  4873. target.addScaledVector( v1, _v3$1.x );
  4874. target.addScaledVector( v2, _v3$1.y );
  4875. target.addScaledVector( v3, _v3$1.z );
  4876. return target;
  4877. }
  4878. static isFrontFacing( a, b, c, direction ) {
  4879. _v0$1.subVectors( c, b );
  4880. _v1$3.subVectors( a, b );
  4881. // strictly front facing
  4882. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4883. }
  4884. set( a, b, c ) {
  4885. this.a.copy( a );
  4886. this.b.copy( b );
  4887. this.c.copy( c );
  4888. return this;
  4889. }
  4890. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4891. this.a.copy( points[ i0 ] );
  4892. this.b.copy( points[ i1 ] );
  4893. this.c.copy( points[ i2 ] );
  4894. return this;
  4895. }
  4896. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4897. this.a.fromBufferAttribute( attribute, i0 );
  4898. this.b.fromBufferAttribute( attribute, i1 );
  4899. this.c.fromBufferAttribute( attribute, i2 );
  4900. return this;
  4901. }
  4902. clone() {
  4903. return new this.constructor().copy( this );
  4904. }
  4905. copy( triangle ) {
  4906. this.a.copy( triangle.a );
  4907. this.b.copy( triangle.b );
  4908. this.c.copy( triangle.c );
  4909. return this;
  4910. }
  4911. getArea() {
  4912. _v0$1.subVectors( this.c, this.b );
  4913. _v1$3.subVectors( this.a, this.b );
  4914. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4915. }
  4916. getMidpoint( target ) {
  4917. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4918. }
  4919. getNormal( target ) {
  4920. return Triangle.getNormal( this.a, this.b, this.c, target );
  4921. }
  4922. getPlane( target ) {
  4923. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4924. }
  4925. getBarycoord( point, target ) {
  4926. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4927. }
  4928. getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151
  4929. if ( warnedGetUV === false ) {
  4930. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4931. warnedGetUV = true;
  4932. }
  4933. return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4934. }
  4935. getInterpolation( point, v1, v2, v3, target ) {
  4936. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4937. }
  4938. containsPoint( point ) {
  4939. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4940. }
  4941. isFrontFacing( direction ) {
  4942. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4943. }
  4944. intersectsBox( box ) {
  4945. return box.intersectsTriangle( this );
  4946. }
  4947. closestPointToPoint( p, target ) {
  4948. const a = this.a, b = this.b, c = this.c;
  4949. let v, w;
  4950. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4951. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4952. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4953. // basically, we're distinguishing which of the voronoi regions of the triangle
  4954. // the point lies in with the minimum amount of redundant computation.
  4955. _vab.subVectors( b, a );
  4956. _vac.subVectors( c, a );
  4957. _vap.subVectors( p, a );
  4958. const d1 = _vab.dot( _vap );
  4959. const d2 = _vac.dot( _vap );
  4960. if ( d1 <= 0 && d2 <= 0 ) {
  4961. // vertex region of A; barycentric coords (1, 0, 0)
  4962. return target.copy( a );
  4963. }
  4964. _vbp.subVectors( p, b );
  4965. const d3 = _vab.dot( _vbp );
  4966. const d4 = _vac.dot( _vbp );
  4967. if ( d3 >= 0 && d4 <= d3 ) {
  4968. // vertex region of B; barycentric coords (0, 1, 0)
  4969. return target.copy( b );
  4970. }
  4971. const vc = d1 * d4 - d3 * d2;
  4972. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4973. v = d1 / ( d1 - d3 );
  4974. // edge region of AB; barycentric coords (1-v, v, 0)
  4975. return target.copy( a ).addScaledVector( _vab, v );
  4976. }
  4977. _vcp.subVectors( p, c );
  4978. const d5 = _vab.dot( _vcp );
  4979. const d6 = _vac.dot( _vcp );
  4980. if ( d6 >= 0 && d5 <= d6 ) {
  4981. // vertex region of C; barycentric coords (0, 0, 1)
  4982. return target.copy( c );
  4983. }
  4984. const vb = d5 * d2 - d1 * d6;
  4985. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4986. w = d2 / ( d2 - d6 );
  4987. // edge region of AC; barycentric coords (1-w, 0, w)
  4988. return target.copy( a ).addScaledVector( _vac, w );
  4989. }
  4990. const va = d3 * d6 - d5 * d4;
  4991. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4992. _vbc.subVectors( c, b );
  4993. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4994. // edge region of BC; barycentric coords (0, 1-w, w)
  4995. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4996. }
  4997. // face region
  4998. const denom = 1 / ( va + vb + vc );
  4999. // u = va * denom
  5000. v = vb * denom;
  5001. w = vc * denom;
  5002. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5003. }
  5004. equals( triangle ) {
  5005. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5006. }
  5007. }
  5008. let materialId = 0;
  5009. class Material extends EventDispatcher {
  5010. constructor() {
  5011. super();
  5012. this.isMaterial = true;
  5013. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5014. this.uuid = generateUUID();
  5015. this.name = '';
  5016. this.type = 'Material';
  5017. this.blending = NormalBlending;
  5018. this.side = FrontSide;
  5019. this.vertexColors = false;
  5020. this.opacity = 1;
  5021. this.transparent = false;
  5022. this.blendSrc = SrcAlphaFactor;
  5023. this.blendDst = OneMinusSrcAlphaFactor;
  5024. this.blendEquation = AddEquation;
  5025. this.blendSrcAlpha = null;
  5026. this.blendDstAlpha = null;
  5027. this.blendEquationAlpha = null;
  5028. this.depthFunc = LessEqualDepth;
  5029. this.depthTest = true;
  5030. this.depthWrite = true;
  5031. this.stencilWriteMask = 0xff;
  5032. this.stencilFunc = AlwaysStencilFunc;
  5033. this.stencilRef = 0;
  5034. this.stencilFuncMask = 0xff;
  5035. this.stencilFail = KeepStencilOp;
  5036. this.stencilZFail = KeepStencilOp;
  5037. this.stencilZPass = KeepStencilOp;
  5038. this.stencilWrite = false;
  5039. this.clippingPlanes = null;
  5040. this.clipIntersection = false;
  5041. this.clipShadows = false;
  5042. this.shadowSide = null;
  5043. this.colorWrite = true;
  5044. this.precision = null; // override the renderer's default precision for this material
  5045. this.polygonOffset = false;
  5046. this.polygonOffsetFactor = 0;
  5047. this.polygonOffsetUnits = 0;
  5048. this.dithering = false;
  5049. this.alphaToCoverage = false;
  5050. this.premultipliedAlpha = false;
  5051. this.forceSinglePass = false;
  5052. this.visible = true;
  5053. this.toneMapped = true;
  5054. this.userData = {};
  5055. this.version = 0;
  5056. this._alphaTest = 0;
  5057. }
  5058. get alphaTest() {
  5059. return this._alphaTest;
  5060. }
  5061. set alphaTest( value ) {
  5062. if ( this._alphaTest > 0 !== value > 0 ) {
  5063. this.version ++;
  5064. }
  5065. this._alphaTest = value;
  5066. }
  5067. onBuild( /* shaderobject, renderer */ ) {}
  5068. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5069. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5070. customProgramCacheKey() {
  5071. return this.onBeforeCompile.toString();
  5072. }
  5073. setValues( values ) {
  5074. if ( values === undefined ) return;
  5075. for ( const key in values ) {
  5076. const newValue = values[ key ];
  5077. if ( newValue === undefined ) {
  5078. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5079. continue;
  5080. }
  5081. const currentValue = this[ key ];
  5082. if ( currentValue === undefined ) {
  5083. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5084. continue;
  5085. }
  5086. if ( currentValue && currentValue.isColor ) {
  5087. currentValue.set( newValue );
  5088. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5089. currentValue.copy( newValue );
  5090. } else {
  5091. this[ key ] = newValue;
  5092. }
  5093. }
  5094. }
  5095. toJSON( meta ) {
  5096. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5097. if ( isRootObject ) {
  5098. meta = {
  5099. textures: {},
  5100. images: {}
  5101. };
  5102. }
  5103. const data = {
  5104. metadata: {
  5105. version: 4.6,
  5106. type: 'Material',
  5107. generator: 'Material.toJSON'
  5108. }
  5109. };
  5110. // standard Material serialization
  5111. data.uuid = this.uuid;
  5112. data.type = this.type;
  5113. if ( this.name !== '' ) data.name = this.name;
  5114. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5115. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5116. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5117. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5118. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5119. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5120. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5121. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5122. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5123. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5124. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5125. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5126. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5127. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5128. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5129. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5130. }
  5131. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5132. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5133. }
  5134. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5135. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5136. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5137. }
  5138. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5139. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5140. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5141. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5142. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5143. }
  5144. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5145. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5146. }
  5147. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5148. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5149. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5150. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5151. }
  5152. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5153. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5154. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5155. if ( this.lightMap && this.lightMap.isTexture ) {
  5156. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5157. data.lightMapIntensity = this.lightMapIntensity;
  5158. }
  5159. if ( this.aoMap && this.aoMap.isTexture ) {
  5160. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5161. data.aoMapIntensity = this.aoMapIntensity;
  5162. }
  5163. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5164. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5165. data.bumpScale = this.bumpScale;
  5166. }
  5167. if ( this.normalMap && this.normalMap.isTexture ) {
  5168. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5169. data.normalMapType = this.normalMapType;
  5170. data.normalScale = this.normalScale.toArray();
  5171. }
  5172. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5173. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5174. data.displacementScale = this.displacementScale;
  5175. data.displacementBias = this.displacementBias;
  5176. }
  5177. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5178. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5179. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5180. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5181. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5182. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5183. if ( this.envMap && this.envMap.isTexture ) {
  5184. data.envMap = this.envMap.toJSON( meta ).uuid;
  5185. if ( this.combine !== undefined ) data.combine = this.combine;
  5186. }
  5187. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5188. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5189. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5190. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5191. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5192. }
  5193. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5194. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5195. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5196. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5197. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5198. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5199. if ( this.size !== undefined ) data.size = this.size;
  5200. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5201. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5202. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5203. if ( this.side !== FrontSide ) data.side = this.side;
  5204. if ( this.vertexColors ) data.vertexColors = true;
  5205. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5206. if ( this.transparent === true ) data.transparent = this.transparent;
  5207. data.depthFunc = this.depthFunc;
  5208. data.depthTest = this.depthTest;
  5209. data.depthWrite = this.depthWrite;
  5210. data.colorWrite = this.colorWrite;
  5211. data.stencilWrite = this.stencilWrite;
  5212. data.stencilWriteMask = this.stencilWriteMask;
  5213. data.stencilFunc = this.stencilFunc;
  5214. data.stencilRef = this.stencilRef;
  5215. data.stencilFuncMask = this.stencilFuncMask;
  5216. data.stencilFail = this.stencilFail;
  5217. data.stencilZFail = this.stencilZFail;
  5218. data.stencilZPass = this.stencilZPass;
  5219. // rotation (SpriteMaterial)
  5220. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5221. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5222. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5223. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5224. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5225. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5226. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5227. if ( this.scale !== undefined ) data.scale = this.scale;
  5228. if ( this.dithering === true ) data.dithering = true;
  5229. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5230. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5231. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5232. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5233. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5234. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5235. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5236. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5237. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5238. if ( this.visible === false ) data.visible = false;
  5239. if ( this.toneMapped === false ) data.toneMapped = false;
  5240. if ( this.fog === false ) data.fog = false;
  5241. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5242. // TODO: Copied from Object3D.toJSON
  5243. function extractFromCache( cache ) {
  5244. const values = [];
  5245. for ( const key in cache ) {
  5246. const data = cache[ key ];
  5247. delete data.metadata;
  5248. values.push( data );
  5249. }
  5250. return values;
  5251. }
  5252. if ( isRootObject ) {
  5253. const textures = extractFromCache( meta.textures );
  5254. const images = extractFromCache( meta.images );
  5255. if ( textures.length > 0 ) data.textures = textures;
  5256. if ( images.length > 0 ) data.images = images;
  5257. }
  5258. return data;
  5259. }
  5260. clone() {
  5261. return new this.constructor().copy( this );
  5262. }
  5263. copy( source ) {
  5264. this.name = source.name;
  5265. this.blending = source.blending;
  5266. this.side = source.side;
  5267. this.vertexColors = source.vertexColors;
  5268. this.opacity = source.opacity;
  5269. this.transparent = source.transparent;
  5270. this.blendSrc = source.blendSrc;
  5271. this.blendDst = source.blendDst;
  5272. this.blendEquation = source.blendEquation;
  5273. this.blendSrcAlpha = source.blendSrcAlpha;
  5274. this.blendDstAlpha = source.blendDstAlpha;
  5275. this.blendEquationAlpha = source.blendEquationAlpha;
  5276. this.depthFunc = source.depthFunc;
  5277. this.depthTest = source.depthTest;
  5278. this.depthWrite = source.depthWrite;
  5279. this.stencilWriteMask = source.stencilWriteMask;
  5280. this.stencilFunc = source.stencilFunc;
  5281. this.stencilRef = source.stencilRef;
  5282. this.stencilFuncMask = source.stencilFuncMask;
  5283. this.stencilFail = source.stencilFail;
  5284. this.stencilZFail = source.stencilZFail;
  5285. this.stencilZPass = source.stencilZPass;
  5286. this.stencilWrite = source.stencilWrite;
  5287. const srcPlanes = source.clippingPlanes;
  5288. let dstPlanes = null;
  5289. if ( srcPlanes !== null ) {
  5290. const n = srcPlanes.length;
  5291. dstPlanes = new Array( n );
  5292. for ( let i = 0; i !== n; ++ i ) {
  5293. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5294. }
  5295. }
  5296. this.clippingPlanes = dstPlanes;
  5297. this.clipIntersection = source.clipIntersection;
  5298. this.clipShadows = source.clipShadows;
  5299. this.shadowSide = source.shadowSide;
  5300. this.colorWrite = source.colorWrite;
  5301. this.precision = source.precision;
  5302. this.polygonOffset = source.polygonOffset;
  5303. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5304. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5305. this.dithering = source.dithering;
  5306. this.alphaTest = source.alphaTest;
  5307. this.alphaToCoverage = source.alphaToCoverage;
  5308. this.premultipliedAlpha = source.premultipliedAlpha;
  5309. this.forceSinglePass = source.forceSinglePass;
  5310. this.visible = source.visible;
  5311. this.toneMapped = source.toneMapped;
  5312. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5313. return this;
  5314. }
  5315. dispose() {
  5316. this.dispatchEvent( { type: 'dispose' } );
  5317. }
  5318. set needsUpdate( value ) {
  5319. if ( value === true ) this.version ++;
  5320. }
  5321. }
  5322. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5323. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5324. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5325. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5326. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5327. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5328. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5329. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5330. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5331. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5332. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5333. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5334. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5335. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5336. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5337. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5338. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5339. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5340. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5341. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5342. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5343. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5344. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5345. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5346. const _hslA = { h: 0, s: 0, l: 0 };
  5347. const _hslB = { h: 0, s: 0, l: 0 };
  5348. function hue2rgb( p, q, t ) {
  5349. if ( t < 0 ) t += 1;
  5350. if ( t > 1 ) t -= 1;
  5351. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5352. if ( t < 1 / 2 ) return q;
  5353. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5354. return p;
  5355. }
  5356. class Color {
  5357. constructor( r, g, b ) {
  5358. this.isColor = true;
  5359. this.r = 1;
  5360. this.g = 1;
  5361. this.b = 1;
  5362. return this.set( r, g, b );
  5363. }
  5364. set( r, g, b ) {
  5365. if ( g === undefined && b === undefined ) {
  5366. // r is THREE.Color, hex or string
  5367. const value = r;
  5368. if ( value && value.isColor ) {
  5369. this.copy( value );
  5370. } else if ( typeof value === 'number' ) {
  5371. this.setHex( value );
  5372. } else if ( typeof value === 'string' ) {
  5373. this.setStyle( value );
  5374. }
  5375. } else {
  5376. this.setRGB( r, g, b );
  5377. }
  5378. return this;
  5379. }
  5380. setScalar( scalar ) {
  5381. this.r = scalar;
  5382. this.g = scalar;
  5383. this.b = scalar;
  5384. return this;
  5385. }
  5386. setHex( hex, colorSpace = SRGBColorSpace ) {
  5387. hex = Math.floor( hex );
  5388. this.r = ( hex >> 16 & 255 ) / 255;
  5389. this.g = ( hex >> 8 & 255 ) / 255;
  5390. this.b = ( hex & 255 ) / 255;
  5391. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5392. return this;
  5393. }
  5394. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5395. this.r = r;
  5396. this.g = g;
  5397. this.b = b;
  5398. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5399. return this;
  5400. }
  5401. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5402. // h,s,l ranges are in 0.0 - 1.0
  5403. h = euclideanModulo( h, 1 );
  5404. s = clamp( s, 0, 1 );
  5405. l = clamp( l, 0, 1 );
  5406. if ( s === 0 ) {
  5407. this.r = this.g = this.b = l;
  5408. } else {
  5409. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5410. const q = ( 2 * l ) - p;
  5411. this.r = hue2rgb( q, p, h + 1 / 3 );
  5412. this.g = hue2rgb( q, p, h );
  5413. this.b = hue2rgb( q, p, h - 1 / 3 );
  5414. }
  5415. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5416. return this;
  5417. }
  5418. setStyle( style, colorSpace = SRGBColorSpace ) {
  5419. function handleAlpha( string ) {
  5420. if ( string === undefined ) return;
  5421. if ( parseFloat( string ) < 1 ) {
  5422. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5423. }
  5424. }
  5425. let m;
  5426. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5427. // rgb / hsl
  5428. let color;
  5429. const name = m[ 1 ];
  5430. const components = m[ 2 ];
  5431. switch ( name ) {
  5432. case 'rgb':
  5433. case 'rgba':
  5434. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5435. // rgb(255,0,0) rgba(255,0,0,0.5)
  5436. handleAlpha( color[ 4 ] );
  5437. return this.setRGB(
  5438. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5439. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5440. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5441. colorSpace
  5442. );
  5443. }
  5444. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5445. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5446. handleAlpha( color[ 4 ] );
  5447. return this.setRGB(
  5448. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5449. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5450. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5451. colorSpace
  5452. );
  5453. }
  5454. break;
  5455. case 'hsl':
  5456. case 'hsla':
  5457. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5458. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5459. handleAlpha( color[ 4 ] );
  5460. return this.setHSL(
  5461. parseFloat( color[ 1 ] ) / 360,
  5462. parseFloat( color[ 2 ] ) / 100,
  5463. parseFloat( color[ 3 ] ) / 100,
  5464. colorSpace
  5465. );
  5466. }
  5467. break;
  5468. default:
  5469. console.warn( 'THREE.Color: Unknown color model ' + style );
  5470. }
  5471. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5472. // hex color
  5473. const hex = m[ 1 ];
  5474. const size = hex.length;
  5475. if ( size === 3 ) {
  5476. // #ff0
  5477. return this.setRGB(
  5478. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5479. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5480. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5481. colorSpace
  5482. );
  5483. } else if ( size === 6 ) {
  5484. // #ff0000
  5485. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5486. } else {
  5487. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5488. }
  5489. } else if ( style && style.length > 0 ) {
  5490. return this.setColorName( style, colorSpace );
  5491. }
  5492. return this;
  5493. }
  5494. setColorName( style, colorSpace = SRGBColorSpace ) {
  5495. // color keywords
  5496. const hex = _colorKeywords[ style.toLowerCase() ];
  5497. if ( hex !== undefined ) {
  5498. // red
  5499. this.setHex( hex, colorSpace );
  5500. } else {
  5501. // unknown color
  5502. console.warn( 'THREE.Color: Unknown color ' + style );
  5503. }
  5504. return this;
  5505. }
  5506. clone() {
  5507. return new this.constructor( this.r, this.g, this.b );
  5508. }
  5509. copy( color ) {
  5510. this.r = color.r;
  5511. this.g = color.g;
  5512. this.b = color.b;
  5513. return this;
  5514. }
  5515. copySRGBToLinear( color ) {
  5516. this.r = SRGBToLinear( color.r );
  5517. this.g = SRGBToLinear( color.g );
  5518. this.b = SRGBToLinear( color.b );
  5519. return this;
  5520. }
  5521. copyLinearToSRGB( color ) {
  5522. this.r = LinearToSRGB( color.r );
  5523. this.g = LinearToSRGB( color.g );
  5524. this.b = LinearToSRGB( color.b );
  5525. return this;
  5526. }
  5527. convertSRGBToLinear() {
  5528. this.copySRGBToLinear( this );
  5529. return this;
  5530. }
  5531. convertLinearToSRGB() {
  5532. this.copyLinearToSRGB( this );
  5533. return this;
  5534. }
  5535. getHex( colorSpace = SRGBColorSpace ) {
  5536. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5537. 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 ) );
  5538. }
  5539. getHexString( colorSpace = SRGBColorSpace ) {
  5540. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5541. }
  5542. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5543. // h,s,l ranges are in 0.0 - 1.0
  5544. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5545. const r = _color.r, g = _color.g, b = _color.b;
  5546. const max = Math.max( r, g, b );
  5547. const min = Math.min( r, g, b );
  5548. let hue, saturation;
  5549. const lightness = ( min + max ) / 2.0;
  5550. if ( min === max ) {
  5551. hue = 0;
  5552. saturation = 0;
  5553. } else {
  5554. const delta = max - min;
  5555. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5556. switch ( max ) {
  5557. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5558. case g: hue = ( b - r ) / delta + 2; break;
  5559. case b: hue = ( r - g ) / delta + 4; break;
  5560. }
  5561. hue /= 6;
  5562. }
  5563. target.h = hue;
  5564. target.s = saturation;
  5565. target.l = lightness;
  5566. return target;
  5567. }
  5568. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5569. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5570. target.r = _color.r;
  5571. target.g = _color.g;
  5572. target.b = _color.b;
  5573. return target;
  5574. }
  5575. getStyle( colorSpace = SRGBColorSpace ) {
  5576. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5577. const r = _color.r, g = _color.g, b = _color.b;
  5578. if ( colorSpace !== SRGBColorSpace ) {
  5579. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5580. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5581. }
  5582. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5583. }
  5584. offsetHSL( h, s, l ) {
  5585. this.getHSL( _hslA );
  5586. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5587. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5588. return this;
  5589. }
  5590. add( color ) {
  5591. this.r += color.r;
  5592. this.g += color.g;
  5593. this.b += color.b;
  5594. return this;
  5595. }
  5596. addColors( color1, color2 ) {
  5597. this.r = color1.r + color2.r;
  5598. this.g = color1.g + color2.g;
  5599. this.b = color1.b + color2.b;
  5600. return this;
  5601. }
  5602. addScalar( s ) {
  5603. this.r += s;
  5604. this.g += s;
  5605. this.b += s;
  5606. return this;
  5607. }
  5608. sub( color ) {
  5609. this.r = Math.max( 0, this.r - color.r );
  5610. this.g = Math.max( 0, this.g - color.g );
  5611. this.b = Math.max( 0, this.b - color.b );
  5612. return this;
  5613. }
  5614. multiply( color ) {
  5615. this.r *= color.r;
  5616. this.g *= color.g;
  5617. this.b *= color.b;
  5618. return this;
  5619. }
  5620. multiplyScalar( s ) {
  5621. this.r *= s;
  5622. this.g *= s;
  5623. this.b *= s;
  5624. return this;
  5625. }
  5626. lerp( color, alpha ) {
  5627. this.r += ( color.r - this.r ) * alpha;
  5628. this.g += ( color.g - this.g ) * alpha;
  5629. this.b += ( color.b - this.b ) * alpha;
  5630. return this;
  5631. }
  5632. lerpColors( color1, color2, alpha ) {
  5633. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5634. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5635. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5636. return this;
  5637. }
  5638. lerpHSL( color, alpha ) {
  5639. this.getHSL( _hslA );
  5640. color.getHSL( _hslB );
  5641. const h = lerp( _hslA.h, _hslB.h, alpha );
  5642. const s = lerp( _hslA.s, _hslB.s, alpha );
  5643. const l = lerp( _hslA.l, _hslB.l, alpha );
  5644. this.setHSL( h, s, l );
  5645. return this;
  5646. }
  5647. setFromVector3( v ) {
  5648. this.r = v.x;
  5649. this.g = v.y;
  5650. this.b = v.z;
  5651. return this;
  5652. }
  5653. applyMatrix3( m ) {
  5654. const r = this.r, g = this.g, b = this.b;
  5655. const e = m.elements;
  5656. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5657. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5658. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5659. return this;
  5660. }
  5661. equals( c ) {
  5662. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5663. }
  5664. fromArray( array, offset = 0 ) {
  5665. this.r = array[ offset ];
  5666. this.g = array[ offset + 1 ];
  5667. this.b = array[ offset + 2 ];
  5668. return this;
  5669. }
  5670. toArray( array = [], offset = 0 ) {
  5671. array[ offset ] = this.r;
  5672. array[ offset + 1 ] = this.g;
  5673. array[ offset + 2 ] = this.b;
  5674. return array;
  5675. }
  5676. fromBufferAttribute( attribute, index ) {
  5677. this.r = attribute.getX( index );
  5678. this.g = attribute.getY( index );
  5679. this.b = attribute.getZ( index );
  5680. return this;
  5681. }
  5682. toJSON() {
  5683. return this.getHex();
  5684. }
  5685. *[ Symbol.iterator ]() {
  5686. yield this.r;
  5687. yield this.g;
  5688. yield this.b;
  5689. }
  5690. }
  5691. const _color = /*@__PURE__*/ new Color();
  5692. Color.NAMES = _colorKeywords;
  5693. class MeshBasicMaterial extends Material {
  5694. constructor( parameters ) {
  5695. super();
  5696. this.isMeshBasicMaterial = true;
  5697. this.type = 'MeshBasicMaterial';
  5698. this.color = new Color( 0xffffff ); // emissive
  5699. this.map = null;
  5700. this.lightMap = null;
  5701. this.lightMapIntensity = 1.0;
  5702. this.aoMap = null;
  5703. this.aoMapIntensity = 1.0;
  5704. this.specularMap = null;
  5705. this.alphaMap = null;
  5706. this.envMap = null;
  5707. this.combine = MultiplyOperation;
  5708. this.reflectivity = 1;
  5709. this.refractionRatio = 0.98;
  5710. this.wireframe = false;
  5711. this.wireframeLinewidth = 1;
  5712. this.wireframeLinecap = 'round';
  5713. this.wireframeLinejoin = 'round';
  5714. this.fog = true;
  5715. this.setValues( parameters );
  5716. }
  5717. copy( source ) {
  5718. super.copy( source );
  5719. this.color.copy( source.color );
  5720. this.map = source.map;
  5721. this.lightMap = source.lightMap;
  5722. this.lightMapIntensity = source.lightMapIntensity;
  5723. this.aoMap = source.aoMap;
  5724. this.aoMapIntensity = source.aoMapIntensity;
  5725. this.specularMap = source.specularMap;
  5726. this.alphaMap = source.alphaMap;
  5727. this.envMap = source.envMap;
  5728. this.combine = source.combine;
  5729. this.reflectivity = source.reflectivity;
  5730. this.refractionRatio = source.refractionRatio;
  5731. this.wireframe = source.wireframe;
  5732. this.wireframeLinewidth = source.wireframeLinewidth;
  5733. this.wireframeLinecap = source.wireframeLinecap;
  5734. this.wireframeLinejoin = source.wireframeLinejoin;
  5735. this.fog = source.fog;
  5736. return this;
  5737. }
  5738. }
  5739. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5740. const _tables = /*@__PURE__*/ _generateTables();
  5741. function _generateTables() {
  5742. // float32 to float16 helpers
  5743. const buffer = new ArrayBuffer( 4 );
  5744. const floatView = new Float32Array( buffer );
  5745. const uint32View = new Uint32Array( buffer );
  5746. const baseTable = new Uint32Array( 512 );
  5747. const shiftTable = new Uint32Array( 512 );
  5748. for ( let i = 0; i < 256; ++ i ) {
  5749. const e = i - 127;
  5750. // very small number (0, -0)
  5751. if ( e < - 27 ) {
  5752. baseTable[ i ] = 0x0000;
  5753. baseTable[ i | 0x100 ] = 0x8000;
  5754. shiftTable[ i ] = 24;
  5755. shiftTable[ i | 0x100 ] = 24;
  5756. // small number (denorm)
  5757. } else if ( e < - 14 ) {
  5758. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5759. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5760. shiftTable[ i ] = - e - 1;
  5761. shiftTable[ i | 0x100 ] = - e - 1;
  5762. // normal number
  5763. } else if ( e <= 15 ) {
  5764. baseTable[ i ] = ( e + 15 ) << 10;
  5765. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5766. shiftTable[ i ] = 13;
  5767. shiftTable[ i | 0x100 ] = 13;
  5768. // large number (Infinity, -Infinity)
  5769. } else if ( e < 128 ) {
  5770. baseTable[ i ] = 0x7c00;
  5771. baseTable[ i | 0x100 ] = 0xfc00;
  5772. shiftTable[ i ] = 24;
  5773. shiftTable[ i | 0x100 ] = 24;
  5774. // stay (NaN, Infinity, -Infinity)
  5775. } else {
  5776. baseTable[ i ] = 0x7c00;
  5777. baseTable[ i | 0x100 ] = 0xfc00;
  5778. shiftTable[ i ] = 13;
  5779. shiftTable[ i | 0x100 ] = 13;
  5780. }
  5781. }
  5782. // float16 to float32 helpers
  5783. const mantissaTable = new Uint32Array( 2048 );
  5784. const exponentTable = new Uint32Array( 64 );
  5785. const offsetTable = new Uint32Array( 64 );
  5786. for ( let i = 1; i < 1024; ++ i ) {
  5787. let m = i << 13; // zero pad mantissa bits
  5788. let e = 0; // zero exponent
  5789. // normalized
  5790. while ( ( m & 0x00800000 ) === 0 ) {
  5791. m <<= 1;
  5792. e -= 0x00800000; // decrement exponent
  5793. }
  5794. m &= ~ 0x00800000; // clear leading 1 bit
  5795. e += 0x38800000; // adjust bias
  5796. mantissaTable[ i ] = m | e;
  5797. }
  5798. for ( let i = 1024; i < 2048; ++ i ) {
  5799. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5800. }
  5801. for ( let i = 1; i < 31; ++ i ) {
  5802. exponentTable[ i ] = i << 23;
  5803. }
  5804. exponentTable[ 31 ] = 0x47800000;
  5805. exponentTable[ 32 ] = 0x80000000;
  5806. for ( let i = 33; i < 63; ++ i ) {
  5807. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5808. }
  5809. exponentTable[ 63 ] = 0xc7800000;
  5810. for ( let i = 1; i < 64; ++ i ) {
  5811. if ( i !== 32 ) {
  5812. offsetTable[ i ] = 1024;
  5813. }
  5814. }
  5815. return {
  5816. floatView: floatView,
  5817. uint32View: uint32View,
  5818. baseTable: baseTable,
  5819. shiftTable: shiftTable,
  5820. mantissaTable: mantissaTable,
  5821. exponentTable: exponentTable,
  5822. offsetTable: offsetTable
  5823. };
  5824. }
  5825. // float32 to float16
  5826. function toHalfFloat( val ) {
  5827. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5828. val = clamp( val, - 65504, 65504 );
  5829. _tables.floatView[ 0 ] = val;
  5830. const f = _tables.uint32View[ 0 ];
  5831. const e = ( f >> 23 ) & 0x1ff;
  5832. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5833. }
  5834. // float16 to float32
  5835. function fromHalfFloat( val ) {
  5836. const m = val >> 10;
  5837. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5838. return _tables.floatView[ 0 ];
  5839. }
  5840. const DataUtils = {
  5841. toHalfFloat: toHalfFloat,
  5842. fromHalfFloat: fromHalfFloat,
  5843. };
  5844. const _vector$8 = /*@__PURE__*/ new Vector3();
  5845. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5846. class BufferAttribute {
  5847. constructor( array, itemSize, normalized = false ) {
  5848. if ( Array.isArray( array ) ) {
  5849. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5850. }
  5851. this.isBufferAttribute = true;
  5852. this.name = '';
  5853. this.array = array;
  5854. this.itemSize = itemSize;
  5855. this.count = array !== undefined ? array.length / itemSize : 0;
  5856. this.normalized = normalized;
  5857. this.usage = StaticDrawUsage;
  5858. this.updateRange = { offset: 0, count: - 1 };
  5859. this.gpuType = FloatType;
  5860. this.version = 0;
  5861. }
  5862. onUploadCallback() {}
  5863. set needsUpdate( value ) {
  5864. if ( value === true ) this.version ++;
  5865. }
  5866. setUsage( value ) {
  5867. this.usage = value;
  5868. return this;
  5869. }
  5870. copy( source ) {
  5871. this.name = source.name;
  5872. this.array = new source.array.constructor( source.array );
  5873. this.itemSize = source.itemSize;
  5874. this.count = source.count;
  5875. this.normalized = source.normalized;
  5876. this.usage = source.usage;
  5877. this.gpuType = source.gpuType;
  5878. return this;
  5879. }
  5880. copyAt( index1, attribute, index2 ) {
  5881. index1 *= this.itemSize;
  5882. index2 *= attribute.itemSize;
  5883. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5884. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5885. }
  5886. return this;
  5887. }
  5888. copyArray( array ) {
  5889. this.array.set( array );
  5890. return this;
  5891. }
  5892. applyMatrix3( m ) {
  5893. if ( this.itemSize === 2 ) {
  5894. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5895. _vector2$1.fromBufferAttribute( this, i );
  5896. _vector2$1.applyMatrix3( m );
  5897. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5898. }
  5899. } else if ( this.itemSize === 3 ) {
  5900. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5901. _vector$8.fromBufferAttribute( this, i );
  5902. _vector$8.applyMatrix3( m );
  5903. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5904. }
  5905. }
  5906. return this;
  5907. }
  5908. applyMatrix4( m ) {
  5909. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5910. _vector$8.fromBufferAttribute( this, i );
  5911. _vector$8.applyMatrix4( m );
  5912. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5913. }
  5914. return this;
  5915. }
  5916. applyNormalMatrix( m ) {
  5917. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5918. _vector$8.fromBufferAttribute( this, i );
  5919. _vector$8.applyNormalMatrix( m );
  5920. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5921. }
  5922. return this;
  5923. }
  5924. transformDirection( m ) {
  5925. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5926. _vector$8.fromBufferAttribute( this, i );
  5927. _vector$8.transformDirection( m );
  5928. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5929. }
  5930. return this;
  5931. }
  5932. set( value, offset = 0 ) {
  5933. // Matching BufferAttribute constructor, do not normalize the array.
  5934. this.array.set( value, offset );
  5935. return this;
  5936. }
  5937. getX( index ) {
  5938. let x = this.array[ index * this.itemSize ];
  5939. if ( this.normalized ) x = denormalize( x, this.array );
  5940. return x;
  5941. }
  5942. setX( index, x ) {
  5943. if ( this.normalized ) x = normalize( x, this.array );
  5944. this.array[ index * this.itemSize ] = x;
  5945. return this;
  5946. }
  5947. getY( index ) {
  5948. let y = this.array[ index * this.itemSize + 1 ];
  5949. if ( this.normalized ) y = denormalize( y, this.array );
  5950. return y;
  5951. }
  5952. setY( index, y ) {
  5953. if ( this.normalized ) y = normalize( y, this.array );
  5954. this.array[ index * this.itemSize + 1 ] = y;
  5955. return this;
  5956. }
  5957. getZ( index ) {
  5958. let z = this.array[ index * this.itemSize + 2 ];
  5959. if ( this.normalized ) z = denormalize( z, this.array );
  5960. return z;
  5961. }
  5962. setZ( index, z ) {
  5963. if ( this.normalized ) z = normalize( z, this.array );
  5964. this.array[ index * this.itemSize + 2 ] = z;
  5965. return this;
  5966. }
  5967. getW( index ) {
  5968. let w = this.array[ index * this.itemSize + 3 ];
  5969. if ( this.normalized ) w = denormalize( w, this.array );
  5970. return w;
  5971. }
  5972. setW( index, w ) {
  5973. if ( this.normalized ) w = normalize( w, this.array );
  5974. this.array[ index * this.itemSize + 3 ] = w;
  5975. return this;
  5976. }
  5977. setXY( index, x, y ) {
  5978. index *= this.itemSize;
  5979. if ( this.normalized ) {
  5980. x = normalize( x, this.array );
  5981. y = normalize( y, this.array );
  5982. }
  5983. this.array[ index + 0 ] = x;
  5984. this.array[ index + 1 ] = y;
  5985. return this;
  5986. }
  5987. setXYZ( index, x, y, z ) {
  5988. index *= this.itemSize;
  5989. if ( this.normalized ) {
  5990. x = normalize( x, this.array );
  5991. y = normalize( y, this.array );
  5992. z = normalize( z, this.array );
  5993. }
  5994. this.array[ index + 0 ] = x;
  5995. this.array[ index + 1 ] = y;
  5996. this.array[ index + 2 ] = z;
  5997. return this;
  5998. }
  5999. setXYZW( index, x, y, z, w ) {
  6000. index *= this.itemSize;
  6001. if ( this.normalized ) {
  6002. x = normalize( x, this.array );
  6003. y = normalize( y, this.array );
  6004. z = normalize( z, this.array );
  6005. w = normalize( w, this.array );
  6006. }
  6007. this.array[ index + 0 ] = x;
  6008. this.array[ index + 1 ] = y;
  6009. this.array[ index + 2 ] = z;
  6010. this.array[ index + 3 ] = w;
  6011. return this;
  6012. }
  6013. onUpload( callback ) {
  6014. this.onUploadCallback = callback;
  6015. return this;
  6016. }
  6017. clone() {
  6018. return new this.constructor( this.array, this.itemSize ).copy( this );
  6019. }
  6020. toJSON() {
  6021. const data = {
  6022. itemSize: this.itemSize,
  6023. type: this.array.constructor.name,
  6024. array: Array.from( this.array ),
  6025. normalized: this.normalized
  6026. };
  6027. if ( this.name !== '' ) data.name = this.name;
  6028. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6029. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  6030. return data;
  6031. }
  6032. copyColorsArray() { // @deprecated, r144
  6033. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  6034. }
  6035. copyVector2sArray() { // @deprecated, r144
  6036. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  6037. }
  6038. copyVector3sArray() { // @deprecated, r144
  6039. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  6040. }
  6041. copyVector4sArray() { // @deprecated, r144
  6042. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  6043. }
  6044. }
  6045. //
  6046. class Int8BufferAttribute extends BufferAttribute {
  6047. constructor( array, itemSize, normalized ) {
  6048. super( new Int8Array( array ), itemSize, normalized );
  6049. }
  6050. }
  6051. class Uint8BufferAttribute extends BufferAttribute {
  6052. constructor( array, itemSize, normalized ) {
  6053. super( new Uint8Array( array ), itemSize, normalized );
  6054. }
  6055. }
  6056. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6057. constructor( array, itemSize, normalized ) {
  6058. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6059. }
  6060. }
  6061. class Int16BufferAttribute extends BufferAttribute {
  6062. constructor( array, itemSize, normalized ) {
  6063. super( new Int16Array( array ), itemSize, normalized );
  6064. }
  6065. }
  6066. class Uint16BufferAttribute extends BufferAttribute {
  6067. constructor( array, itemSize, normalized ) {
  6068. super( new Uint16Array( array ), itemSize, normalized );
  6069. }
  6070. }
  6071. class Int32BufferAttribute extends BufferAttribute {
  6072. constructor( array, itemSize, normalized ) {
  6073. super( new Int32Array( array ), itemSize, normalized );
  6074. }
  6075. }
  6076. class Uint32BufferAttribute extends BufferAttribute {
  6077. constructor( array, itemSize, normalized ) {
  6078. super( new Uint32Array( array ), itemSize, normalized );
  6079. }
  6080. }
  6081. class Float16BufferAttribute extends BufferAttribute {
  6082. constructor( array, itemSize, normalized ) {
  6083. super( new Uint16Array( array ), itemSize, normalized );
  6084. this.isFloat16BufferAttribute = true;
  6085. }
  6086. getX( index ) {
  6087. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6088. if ( this.normalized ) x = denormalize( x, this.array );
  6089. return x;
  6090. }
  6091. setX( index, x ) {
  6092. if ( this.normalized ) x = normalize( x, this.array );
  6093. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6094. return this;
  6095. }
  6096. getY( index ) {
  6097. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6098. if ( this.normalized ) y = denormalize( y, this.array );
  6099. return y;
  6100. }
  6101. setY( index, y ) {
  6102. if ( this.normalized ) y = normalize( y, this.array );
  6103. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6104. return this;
  6105. }
  6106. getZ( index ) {
  6107. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6108. if ( this.normalized ) z = denormalize( z, this.array );
  6109. return z;
  6110. }
  6111. setZ( index, z ) {
  6112. if ( this.normalized ) z = normalize( z, this.array );
  6113. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6114. return this;
  6115. }
  6116. getW( index ) {
  6117. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6118. if ( this.normalized ) w = denormalize( w, this.array );
  6119. return w;
  6120. }
  6121. setW( index, w ) {
  6122. if ( this.normalized ) w = normalize( w, this.array );
  6123. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6124. return this;
  6125. }
  6126. setXY( index, x, y ) {
  6127. index *= this.itemSize;
  6128. if ( this.normalized ) {
  6129. x = normalize( x, this.array );
  6130. y = normalize( y, this.array );
  6131. }
  6132. this.array[ index + 0 ] = toHalfFloat( x );
  6133. this.array[ index + 1 ] = toHalfFloat( y );
  6134. return this;
  6135. }
  6136. setXYZ( index, x, y, z ) {
  6137. index *= this.itemSize;
  6138. if ( this.normalized ) {
  6139. x = normalize( x, this.array );
  6140. y = normalize( y, this.array );
  6141. z = normalize( z, this.array );
  6142. }
  6143. this.array[ index + 0 ] = toHalfFloat( x );
  6144. this.array[ index + 1 ] = toHalfFloat( y );
  6145. this.array[ index + 2 ] = toHalfFloat( z );
  6146. return this;
  6147. }
  6148. setXYZW( index, x, y, z, w ) {
  6149. index *= this.itemSize;
  6150. if ( this.normalized ) {
  6151. x = normalize( x, this.array );
  6152. y = normalize( y, this.array );
  6153. z = normalize( z, this.array );
  6154. w = normalize( w, this.array );
  6155. }
  6156. this.array[ index + 0 ] = toHalfFloat( x );
  6157. this.array[ index + 1 ] = toHalfFloat( y );
  6158. this.array[ index + 2 ] = toHalfFloat( z );
  6159. this.array[ index + 3 ] = toHalfFloat( w );
  6160. return this;
  6161. }
  6162. }
  6163. class Float32BufferAttribute extends BufferAttribute {
  6164. constructor( array, itemSize, normalized ) {
  6165. super( new Float32Array( array ), itemSize, normalized );
  6166. }
  6167. }
  6168. class Float64BufferAttribute extends BufferAttribute {
  6169. constructor( array, itemSize, normalized ) {
  6170. super( new Float64Array( array ), itemSize, normalized );
  6171. }
  6172. }
  6173. let _id$1 = 0;
  6174. const _m1 = /*@__PURE__*/ new Matrix4();
  6175. const _obj = /*@__PURE__*/ new Object3D();
  6176. const _offset = /*@__PURE__*/ new Vector3();
  6177. const _box$1 = /*@__PURE__*/ new Box3();
  6178. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6179. const _vector$7 = /*@__PURE__*/ new Vector3();
  6180. class BufferGeometry extends EventDispatcher {
  6181. constructor() {
  6182. super();
  6183. this.isBufferGeometry = true;
  6184. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  6185. this.uuid = generateUUID();
  6186. this.name = '';
  6187. this.type = 'BufferGeometry';
  6188. this.index = null;
  6189. this.attributes = {};
  6190. this.morphAttributes = {};
  6191. this.morphTargetsRelative = false;
  6192. this.groups = [];
  6193. this.boundingBox = null;
  6194. this.boundingSphere = null;
  6195. this.drawRange = { start: 0, count: Infinity };
  6196. this.userData = {};
  6197. }
  6198. getIndex() {
  6199. return this.index;
  6200. }
  6201. setIndex( index ) {
  6202. if ( Array.isArray( index ) ) {
  6203. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6204. } else {
  6205. this.index = index;
  6206. }
  6207. return this;
  6208. }
  6209. getAttribute( name ) {
  6210. return this.attributes[ name ];
  6211. }
  6212. setAttribute( name, attribute ) {
  6213. this.attributes[ name ] = attribute;
  6214. return this;
  6215. }
  6216. deleteAttribute( name ) {
  6217. delete this.attributes[ name ];
  6218. return this;
  6219. }
  6220. hasAttribute( name ) {
  6221. return this.attributes[ name ] !== undefined;
  6222. }
  6223. addGroup( start, count, materialIndex = 0 ) {
  6224. this.groups.push( {
  6225. start: start,
  6226. count: count,
  6227. materialIndex: materialIndex
  6228. } );
  6229. }
  6230. clearGroups() {
  6231. this.groups = [];
  6232. }
  6233. setDrawRange( start, count ) {
  6234. this.drawRange.start = start;
  6235. this.drawRange.count = count;
  6236. }
  6237. applyMatrix4( matrix ) {
  6238. const position = this.attributes.position;
  6239. if ( position !== undefined ) {
  6240. position.applyMatrix4( matrix );
  6241. position.needsUpdate = true;
  6242. }
  6243. const normal = this.attributes.normal;
  6244. if ( normal !== undefined ) {
  6245. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6246. normal.applyNormalMatrix( normalMatrix );
  6247. normal.needsUpdate = true;
  6248. }
  6249. const tangent = this.attributes.tangent;
  6250. if ( tangent !== undefined ) {
  6251. tangent.transformDirection( matrix );
  6252. tangent.needsUpdate = true;
  6253. }
  6254. if ( this.boundingBox !== null ) {
  6255. this.computeBoundingBox();
  6256. }
  6257. if ( this.boundingSphere !== null ) {
  6258. this.computeBoundingSphere();
  6259. }
  6260. return this;
  6261. }
  6262. applyQuaternion( q ) {
  6263. _m1.makeRotationFromQuaternion( q );
  6264. this.applyMatrix4( _m1 );
  6265. return this;
  6266. }
  6267. rotateX( angle ) {
  6268. // rotate geometry around world x-axis
  6269. _m1.makeRotationX( angle );
  6270. this.applyMatrix4( _m1 );
  6271. return this;
  6272. }
  6273. rotateY( angle ) {
  6274. // rotate geometry around world y-axis
  6275. _m1.makeRotationY( angle );
  6276. this.applyMatrix4( _m1 );
  6277. return this;
  6278. }
  6279. rotateZ( angle ) {
  6280. // rotate geometry around world z-axis
  6281. _m1.makeRotationZ( angle );
  6282. this.applyMatrix4( _m1 );
  6283. return this;
  6284. }
  6285. translate( x, y, z ) {
  6286. // translate geometry
  6287. _m1.makeTranslation( x, y, z );
  6288. this.applyMatrix4( _m1 );
  6289. return this;
  6290. }
  6291. scale( x, y, z ) {
  6292. // scale geometry
  6293. _m1.makeScale( x, y, z );
  6294. this.applyMatrix4( _m1 );
  6295. return this;
  6296. }
  6297. lookAt( vector ) {
  6298. _obj.lookAt( vector );
  6299. _obj.updateMatrix();
  6300. this.applyMatrix4( _obj.matrix );
  6301. return this;
  6302. }
  6303. center() {
  6304. this.computeBoundingBox();
  6305. this.boundingBox.getCenter( _offset ).negate();
  6306. this.translate( _offset.x, _offset.y, _offset.z );
  6307. return this;
  6308. }
  6309. setFromPoints( points ) {
  6310. const position = [];
  6311. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6312. const point = points[ i ];
  6313. position.push( point.x, point.y, point.z || 0 );
  6314. }
  6315. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6316. return this;
  6317. }
  6318. computeBoundingBox() {
  6319. if ( this.boundingBox === null ) {
  6320. this.boundingBox = new Box3();
  6321. }
  6322. const position = this.attributes.position;
  6323. const morphAttributesPosition = this.morphAttributes.position;
  6324. if ( position && position.isGLBufferAttribute ) {
  6325. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6326. this.boundingBox.set(
  6327. new Vector3( - Infinity, - Infinity, - Infinity ),
  6328. new Vector3( + Infinity, + Infinity, + Infinity )
  6329. );
  6330. return;
  6331. }
  6332. if ( position !== undefined ) {
  6333. this.boundingBox.setFromBufferAttribute( position );
  6334. // process morph attributes if present
  6335. if ( morphAttributesPosition ) {
  6336. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6337. const morphAttribute = morphAttributesPosition[ i ];
  6338. _box$1.setFromBufferAttribute( morphAttribute );
  6339. if ( this.morphTargetsRelative ) {
  6340. _vector$7.addVectors( this.boundingBox.min, _box$1.min );
  6341. this.boundingBox.expandByPoint( _vector$7 );
  6342. _vector$7.addVectors( this.boundingBox.max, _box$1.max );
  6343. this.boundingBox.expandByPoint( _vector$7 );
  6344. } else {
  6345. this.boundingBox.expandByPoint( _box$1.min );
  6346. this.boundingBox.expandByPoint( _box$1.max );
  6347. }
  6348. }
  6349. }
  6350. } else {
  6351. this.boundingBox.makeEmpty();
  6352. }
  6353. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6354. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6355. }
  6356. }
  6357. computeBoundingSphere() {
  6358. if ( this.boundingSphere === null ) {
  6359. this.boundingSphere = new Sphere();
  6360. }
  6361. const position = this.attributes.position;
  6362. const morphAttributesPosition = this.morphAttributes.position;
  6363. if ( position && position.isGLBufferAttribute ) {
  6364. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6365. this.boundingSphere.set( new Vector3(), Infinity );
  6366. return;
  6367. }
  6368. if ( position ) {
  6369. // first, find the center of the bounding sphere
  6370. const center = this.boundingSphere.center;
  6371. _box$1.setFromBufferAttribute( position );
  6372. // process morph attributes if present
  6373. if ( morphAttributesPosition ) {
  6374. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6375. const morphAttribute = morphAttributesPosition[ i ];
  6376. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6377. if ( this.morphTargetsRelative ) {
  6378. _vector$7.addVectors( _box$1.min, _boxMorphTargets.min );
  6379. _box$1.expandByPoint( _vector$7 );
  6380. _vector$7.addVectors( _box$1.max, _boxMorphTargets.max );
  6381. _box$1.expandByPoint( _vector$7 );
  6382. } else {
  6383. _box$1.expandByPoint( _boxMorphTargets.min );
  6384. _box$1.expandByPoint( _boxMorphTargets.max );
  6385. }
  6386. }
  6387. }
  6388. _box$1.getCenter( center );
  6389. // second, try to find a boundingSphere with a radius smaller than the
  6390. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6391. let maxRadiusSq = 0;
  6392. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6393. _vector$7.fromBufferAttribute( position, i );
  6394. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6395. }
  6396. // process morph attributes if present
  6397. if ( morphAttributesPosition ) {
  6398. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6399. const morphAttribute = morphAttributesPosition[ i ];
  6400. const morphTargetsRelative = this.morphTargetsRelative;
  6401. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6402. _vector$7.fromBufferAttribute( morphAttribute, j );
  6403. if ( morphTargetsRelative ) {
  6404. _offset.fromBufferAttribute( position, j );
  6405. _vector$7.add( _offset );
  6406. }
  6407. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6408. }
  6409. }
  6410. }
  6411. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6412. if ( isNaN( this.boundingSphere.radius ) ) {
  6413. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6414. }
  6415. }
  6416. }
  6417. computeTangents() {
  6418. const index = this.index;
  6419. const attributes = this.attributes;
  6420. // based on http://www.terathon.com/code/tangent.html
  6421. // (per vertex tangents)
  6422. if ( index === null ||
  6423. attributes.position === undefined ||
  6424. attributes.normal === undefined ||
  6425. attributes.uv === undefined ) {
  6426. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6427. return;
  6428. }
  6429. const indices = index.array;
  6430. const positions = attributes.position.array;
  6431. const normals = attributes.normal.array;
  6432. const uvs = attributes.uv.array;
  6433. const nVertices = positions.length / 3;
  6434. if ( this.hasAttribute( 'tangent' ) === false ) {
  6435. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6436. }
  6437. const tangents = this.getAttribute( 'tangent' ).array;
  6438. const tan1 = [], tan2 = [];
  6439. for ( let i = 0; i < nVertices; i ++ ) {
  6440. tan1[ i ] = new Vector3();
  6441. tan2[ i ] = new Vector3();
  6442. }
  6443. const vA = new Vector3(),
  6444. vB = new Vector3(),
  6445. vC = new Vector3(),
  6446. uvA = new Vector2(),
  6447. uvB = new Vector2(),
  6448. uvC = new Vector2(),
  6449. sdir = new Vector3(),
  6450. tdir = new Vector3();
  6451. function handleTriangle( a, b, c ) {
  6452. vA.fromArray( positions, a * 3 );
  6453. vB.fromArray( positions, b * 3 );
  6454. vC.fromArray( positions, c * 3 );
  6455. uvA.fromArray( uvs, a * 2 );
  6456. uvB.fromArray( uvs, b * 2 );
  6457. uvC.fromArray( uvs, c * 2 );
  6458. vB.sub( vA );
  6459. vC.sub( vA );
  6460. uvB.sub( uvA );
  6461. uvC.sub( uvA );
  6462. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6463. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6464. if ( ! isFinite( r ) ) return;
  6465. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6466. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6467. tan1[ a ].add( sdir );
  6468. tan1[ b ].add( sdir );
  6469. tan1[ c ].add( sdir );
  6470. tan2[ a ].add( tdir );
  6471. tan2[ b ].add( tdir );
  6472. tan2[ c ].add( tdir );
  6473. }
  6474. let groups = this.groups;
  6475. if ( groups.length === 0 ) {
  6476. groups = [ {
  6477. start: 0,
  6478. count: indices.length
  6479. } ];
  6480. }
  6481. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6482. const group = groups[ i ];
  6483. const start = group.start;
  6484. const count = group.count;
  6485. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6486. handleTriangle(
  6487. indices[ j + 0 ],
  6488. indices[ j + 1 ],
  6489. indices[ j + 2 ]
  6490. );
  6491. }
  6492. }
  6493. const tmp = new Vector3(), tmp2 = new Vector3();
  6494. const n = new Vector3(), n2 = new Vector3();
  6495. function handleVertex( v ) {
  6496. n.fromArray( normals, v * 3 );
  6497. n2.copy( n );
  6498. const t = tan1[ v ];
  6499. // Gram-Schmidt orthogonalize
  6500. tmp.copy( t );
  6501. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6502. // Calculate handedness
  6503. tmp2.crossVectors( n2, t );
  6504. const test = tmp2.dot( tan2[ v ] );
  6505. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6506. tangents[ v * 4 ] = tmp.x;
  6507. tangents[ v * 4 + 1 ] = tmp.y;
  6508. tangents[ v * 4 + 2 ] = tmp.z;
  6509. tangents[ v * 4 + 3 ] = w;
  6510. }
  6511. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6512. const group = groups[ i ];
  6513. const start = group.start;
  6514. const count = group.count;
  6515. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6516. handleVertex( indices[ j + 0 ] );
  6517. handleVertex( indices[ j + 1 ] );
  6518. handleVertex( indices[ j + 2 ] );
  6519. }
  6520. }
  6521. }
  6522. computeVertexNormals() {
  6523. const index = this.index;
  6524. const positionAttribute = this.getAttribute( 'position' );
  6525. if ( positionAttribute !== undefined ) {
  6526. let normalAttribute = this.getAttribute( 'normal' );
  6527. if ( normalAttribute === undefined ) {
  6528. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6529. this.setAttribute( 'normal', normalAttribute );
  6530. } else {
  6531. // reset existing normals to zero
  6532. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6533. normalAttribute.setXYZ( i, 0, 0, 0 );
  6534. }
  6535. }
  6536. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6537. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6538. const cb = new Vector3(), ab = new Vector3();
  6539. // indexed elements
  6540. if ( index ) {
  6541. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6542. const vA = index.getX( i + 0 );
  6543. const vB = index.getX( i + 1 );
  6544. const vC = index.getX( i + 2 );
  6545. pA.fromBufferAttribute( positionAttribute, vA );
  6546. pB.fromBufferAttribute( positionAttribute, vB );
  6547. pC.fromBufferAttribute( positionAttribute, vC );
  6548. cb.subVectors( pC, pB );
  6549. ab.subVectors( pA, pB );
  6550. cb.cross( ab );
  6551. nA.fromBufferAttribute( normalAttribute, vA );
  6552. nB.fromBufferAttribute( normalAttribute, vB );
  6553. nC.fromBufferAttribute( normalAttribute, vC );
  6554. nA.add( cb );
  6555. nB.add( cb );
  6556. nC.add( cb );
  6557. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6558. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6559. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6560. }
  6561. } else {
  6562. // non-indexed elements (unconnected triangle soup)
  6563. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6564. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6565. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6566. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6567. cb.subVectors( pC, pB );
  6568. ab.subVectors( pA, pB );
  6569. cb.cross( ab );
  6570. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6571. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6572. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6573. }
  6574. }
  6575. this.normalizeNormals();
  6576. normalAttribute.needsUpdate = true;
  6577. }
  6578. }
  6579. merge() { // @deprecated, r144
  6580. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeGeometries() instead.' );
  6581. return this;
  6582. }
  6583. normalizeNormals() {
  6584. const normals = this.attributes.normal;
  6585. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6586. _vector$7.fromBufferAttribute( normals, i );
  6587. _vector$7.normalize();
  6588. normals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  6589. }
  6590. }
  6591. toNonIndexed() {
  6592. function convertBufferAttribute( attribute, indices ) {
  6593. const array = attribute.array;
  6594. const itemSize = attribute.itemSize;
  6595. const normalized = attribute.normalized;
  6596. const array2 = new array.constructor( indices.length * itemSize );
  6597. let index = 0, index2 = 0;
  6598. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6599. if ( attribute.isInterleavedBufferAttribute ) {
  6600. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6601. } else {
  6602. index = indices[ i ] * itemSize;
  6603. }
  6604. for ( let j = 0; j < itemSize; j ++ ) {
  6605. array2[ index2 ++ ] = array[ index ++ ];
  6606. }
  6607. }
  6608. return new BufferAttribute( array2, itemSize, normalized );
  6609. }
  6610. //
  6611. if ( this.index === null ) {
  6612. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6613. return this;
  6614. }
  6615. const geometry2 = new BufferGeometry();
  6616. const indices = this.index.array;
  6617. const attributes = this.attributes;
  6618. // attributes
  6619. for ( const name in attributes ) {
  6620. const attribute = attributes[ name ];
  6621. const newAttribute = convertBufferAttribute( attribute, indices );
  6622. geometry2.setAttribute( name, newAttribute );
  6623. }
  6624. // morph attributes
  6625. const morphAttributes = this.morphAttributes;
  6626. for ( const name in morphAttributes ) {
  6627. const morphArray = [];
  6628. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6629. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6630. const attribute = morphAttribute[ i ];
  6631. const newAttribute = convertBufferAttribute( attribute, indices );
  6632. morphArray.push( newAttribute );
  6633. }
  6634. geometry2.morphAttributes[ name ] = morphArray;
  6635. }
  6636. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6637. // groups
  6638. const groups = this.groups;
  6639. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6640. const group = groups[ i ];
  6641. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6642. }
  6643. return geometry2;
  6644. }
  6645. toJSON() {
  6646. const data = {
  6647. metadata: {
  6648. version: 4.6,
  6649. type: 'BufferGeometry',
  6650. generator: 'BufferGeometry.toJSON'
  6651. }
  6652. };
  6653. // standard BufferGeometry serialization
  6654. data.uuid = this.uuid;
  6655. data.type = this.type;
  6656. if ( this.name !== '' ) data.name = this.name;
  6657. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6658. if ( this.parameters !== undefined ) {
  6659. const parameters = this.parameters;
  6660. for ( const key in parameters ) {
  6661. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6662. }
  6663. return data;
  6664. }
  6665. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6666. data.data = { attributes: {} };
  6667. const index = this.index;
  6668. if ( index !== null ) {
  6669. data.data.index = {
  6670. type: index.array.constructor.name,
  6671. array: Array.prototype.slice.call( index.array )
  6672. };
  6673. }
  6674. const attributes = this.attributes;
  6675. for ( const key in attributes ) {
  6676. const attribute = attributes[ key ];
  6677. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6678. }
  6679. const morphAttributes = {};
  6680. let hasMorphAttributes = false;
  6681. for ( const key in this.morphAttributes ) {
  6682. const attributeArray = this.morphAttributes[ key ];
  6683. const array = [];
  6684. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6685. const attribute = attributeArray[ i ];
  6686. array.push( attribute.toJSON( data.data ) );
  6687. }
  6688. if ( array.length > 0 ) {
  6689. morphAttributes[ key ] = array;
  6690. hasMorphAttributes = true;
  6691. }
  6692. }
  6693. if ( hasMorphAttributes ) {
  6694. data.data.morphAttributes = morphAttributes;
  6695. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6696. }
  6697. const groups = this.groups;
  6698. if ( groups.length > 0 ) {
  6699. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6700. }
  6701. const boundingSphere = this.boundingSphere;
  6702. if ( boundingSphere !== null ) {
  6703. data.data.boundingSphere = {
  6704. center: boundingSphere.center.toArray(),
  6705. radius: boundingSphere.radius
  6706. };
  6707. }
  6708. return data;
  6709. }
  6710. clone() {
  6711. return new this.constructor().copy( this );
  6712. }
  6713. copy( source ) {
  6714. // reset
  6715. this.index = null;
  6716. this.attributes = {};
  6717. this.morphAttributes = {};
  6718. this.groups = [];
  6719. this.boundingBox = null;
  6720. this.boundingSphere = null;
  6721. // used for storing cloned, shared data
  6722. const data = {};
  6723. // name
  6724. this.name = source.name;
  6725. // index
  6726. const index = source.index;
  6727. if ( index !== null ) {
  6728. this.setIndex( index.clone( data ) );
  6729. }
  6730. // attributes
  6731. const attributes = source.attributes;
  6732. for ( const name in attributes ) {
  6733. const attribute = attributes[ name ];
  6734. this.setAttribute( name, attribute.clone( data ) );
  6735. }
  6736. // morph attributes
  6737. const morphAttributes = source.morphAttributes;
  6738. for ( const name in morphAttributes ) {
  6739. const array = [];
  6740. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6741. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6742. array.push( morphAttribute[ i ].clone( data ) );
  6743. }
  6744. this.morphAttributes[ name ] = array;
  6745. }
  6746. this.morphTargetsRelative = source.morphTargetsRelative;
  6747. // groups
  6748. const groups = source.groups;
  6749. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6750. const group = groups[ i ];
  6751. this.addGroup( group.start, group.count, group.materialIndex );
  6752. }
  6753. // bounding box
  6754. const boundingBox = source.boundingBox;
  6755. if ( boundingBox !== null ) {
  6756. this.boundingBox = boundingBox.clone();
  6757. }
  6758. // bounding sphere
  6759. const boundingSphere = source.boundingSphere;
  6760. if ( boundingSphere !== null ) {
  6761. this.boundingSphere = boundingSphere.clone();
  6762. }
  6763. // draw range
  6764. this.drawRange.start = source.drawRange.start;
  6765. this.drawRange.count = source.drawRange.count;
  6766. // user data
  6767. this.userData = source.userData;
  6768. return this;
  6769. }
  6770. dispose() {
  6771. this.dispatchEvent( { type: 'dispose' } );
  6772. }
  6773. }
  6774. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6775. const _ray$3 = /*@__PURE__*/ new Ray();
  6776. const _sphere$5 = /*@__PURE__*/ new Sphere();
  6777. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6778. const _vA$1 = /*@__PURE__*/ new Vector3();
  6779. const _vB$1 = /*@__PURE__*/ new Vector3();
  6780. const _vC$1 = /*@__PURE__*/ new Vector3();
  6781. const _tempA = /*@__PURE__*/ new Vector3();
  6782. const _morphA = /*@__PURE__*/ new Vector3();
  6783. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6784. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6785. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6786. const _normalA = /*@__PURE__*/ new Vector3();
  6787. const _normalB = /*@__PURE__*/ new Vector3();
  6788. const _normalC = /*@__PURE__*/ new Vector3();
  6789. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6790. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6791. class Mesh extends Object3D {
  6792. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6793. super();
  6794. this.isMesh = true;
  6795. this.type = 'Mesh';
  6796. this.geometry = geometry;
  6797. this.material = material;
  6798. this.updateMorphTargets();
  6799. }
  6800. copy( source, recursive ) {
  6801. super.copy( source, recursive );
  6802. if ( source.morphTargetInfluences !== undefined ) {
  6803. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6804. }
  6805. if ( source.morphTargetDictionary !== undefined ) {
  6806. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6807. }
  6808. this.material = source.material;
  6809. this.geometry = source.geometry;
  6810. return this;
  6811. }
  6812. updateMorphTargets() {
  6813. const geometry = this.geometry;
  6814. const morphAttributes = geometry.morphAttributes;
  6815. const keys = Object.keys( morphAttributes );
  6816. if ( keys.length > 0 ) {
  6817. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6818. if ( morphAttribute !== undefined ) {
  6819. this.morphTargetInfluences = [];
  6820. this.morphTargetDictionary = {};
  6821. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6822. const name = morphAttribute[ m ].name || String( m );
  6823. this.morphTargetInfluences.push( 0 );
  6824. this.morphTargetDictionary[ name ] = m;
  6825. }
  6826. }
  6827. }
  6828. }
  6829. getVertexPosition( index, target ) {
  6830. const geometry = this.geometry;
  6831. const position = geometry.attributes.position;
  6832. const morphPosition = geometry.morphAttributes.position;
  6833. const morphTargetsRelative = geometry.morphTargetsRelative;
  6834. target.fromBufferAttribute( position, index );
  6835. const morphInfluences = this.morphTargetInfluences;
  6836. if ( morphPosition && morphInfluences ) {
  6837. _morphA.set( 0, 0, 0 );
  6838. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6839. const influence = morphInfluences[ i ];
  6840. const morphAttribute = morphPosition[ i ];
  6841. if ( influence === 0 ) continue;
  6842. _tempA.fromBufferAttribute( morphAttribute, index );
  6843. if ( morphTargetsRelative ) {
  6844. _morphA.addScaledVector( _tempA, influence );
  6845. } else {
  6846. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6847. }
  6848. }
  6849. target.add( _morphA );
  6850. }
  6851. return target;
  6852. }
  6853. raycast( raycaster, intersects ) {
  6854. const geometry = this.geometry;
  6855. const material = this.material;
  6856. const matrixWorld = this.matrixWorld;
  6857. if ( material === undefined ) return;
  6858. // test with bounding sphere in world space
  6859. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6860. _sphere$5.copy( geometry.boundingSphere );
  6861. _sphere$5.applyMatrix4( matrixWorld );
  6862. // check distance from ray origin to bounding sphere
  6863. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6864. if ( _sphere$5.containsPoint( _ray$3.origin ) === false ) {
  6865. if ( _ray$3.intersectSphere( _sphere$5, _sphereHitAt ) === null ) return;
  6866. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6867. }
  6868. // convert ray to local space of mesh
  6869. _inverseMatrix$3.copy( matrixWorld ).invert();
  6870. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6871. // test with bounding box in local space
  6872. if ( geometry.boundingBox !== null ) {
  6873. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6874. }
  6875. // test for intersections with geometry
  6876. this._computeIntersections( raycaster, intersects, _ray$3 );
  6877. }
  6878. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6879. let intersection;
  6880. const geometry = this.geometry;
  6881. const material = this.material;
  6882. const index = geometry.index;
  6883. const position = geometry.attributes.position;
  6884. const uv = geometry.attributes.uv;
  6885. const uv1 = geometry.attributes.uv1;
  6886. const normal = geometry.attributes.normal;
  6887. const groups = geometry.groups;
  6888. const drawRange = geometry.drawRange;
  6889. if ( index !== null ) {
  6890. // indexed buffer geometry
  6891. if ( Array.isArray( material ) ) {
  6892. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6893. const group = groups[ i ];
  6894. const groupMaterial = material[ group.materialIndex ];
  6895. const start = Math.max( group.start, drawRange.start );
  6896. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6897. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6898. const a = index.getX( j );
  6899. const b = index.getX( j + 1 );
  6900. const c = index.getX( j + 2 );
  6901. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6902. if ( intersection ) {
  6903. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6904. intersection.face.materialIndex = group.materialIndex;
  6905. intersects.push( intersection );
  6906. }
  6907. }
  6908. }
  6909. } else {
  6910. const start = Math.max( 0, drawRange.start );
  6911. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6912. for ( let i = start, il = end; i < il; i += 3 ) {
  6913. const a = index.getX( i );
  6914. const b = index.getX( i + 1 );
  6915. const c = index.getX( i + 2 );
  6916. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6917. if ( intersection ) {
  6918. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6919. intersects.push( intersection );
  6920. }
  6921. }
  6922. }
  6923. } else if ( position !== undefined ) {
  6924. // non-indexed buffer geometry
  6925. if ( Array.isArray( material ) ) {
  6926. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6927. const group = groups[ i ];
  6928. const groupMaterial = material[ group.materialIndex ];
  6929. const start = Math.max( group.start, drawRange.start );
  6930. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6931. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6932. const a = j;
  6933. const b = j + 1;
  6934. const c = j + 2;
  6935. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6936. if ( intersection ) {
  6937. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6938. intersection.face.materialIndex = group.materialIndex;
  6939. intersects.push( intersection );
  6940. }
  6941. }
  6942. }
  6943. } else {
  6944. const start = Math.max( 0, drawRange.start );
  6945. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6946. for ( let i = start, il = end; i < il; i += 3 ) {
  6947. const a = i;
  6948. const b = i + 1;
  6949. const c = i + 2;
  6950. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6951. if ( intersection ) {
  6952. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6953. intersects.push( intersection );
  6954. }
  6955. }
  6956. }
  6957. }
  6958. }
  6959. }
  6960. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6961. let intersect;
  6962. if ( material.side === BackSide ) {
  6963. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6964. } else {
  6965. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6966. }
  6967. if ( intersect === null ) return null;
  6968. _intersectionPointWorld.copy( point );
  6969. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6970. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6971. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6972. return {
  6973. distance: distance,
  6974. point: _intersectionPointWorld.clone(),
  6975. object: object
  6976. };
  6977. }
  6978. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  6979. object.getVertexPosition( a, _vA$1 );
  6980. object.getVertexPosition( b, _vB$1 );
  6981. object.getVertexPosition( c, _vC$1 );
  6982. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6983. if ( intersection ) {
  6984. if ( uv ) {
  6985. _uvA$1.fromBufferAttribute( uv, a );
  6986. _uvB$1.fromBufferAttribute( uv, b );
  6987. _uvC$1.fromBufferAttribute( uv, c );
  6988. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6989. }
  6990. if ( uv1 ) {
  6991. _uvA$1.fromBufferAttribute( uv1, a );
  6992. _uvB$1.fromBufferAttribute( uv1, b );
  6993. _uvC$1.fromBufferAttribute( uv1, c );
  6994. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6995. intersection.uv2 = intersection.uv1; // @deprecated, r152
  6996. }
  6997. if ( normal ) {
  6998. _normalA.fromBufferAttribute( normal, a );
  6999. _normalB.fromBufferAttribute( normal, b );
  7000. _normalC.fromBufferAttribute( normal, c );
  7001. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7002. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7003. intersection.normal.multiplyScalar( - 1 );
  7004. }
  7005. }
  7006. const face = {
  7007. a: a,
  7008. b: b,
  7009. c: c,
  7010. normal: new Vector3(),
  7011. materialIndex: 0
  7012. };
  7013. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7014. intersection.face = face;
  7015. }
  7016. return intersection;
  7017. }
  7018. class BoxGeometry extends BufferGeometry {
  7019. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7020. super();
  7021. this.type = 'BoxGeometry';
  7022. this.parameters = {
  7023. width: width,
  7024. height: height,
  7025. depth: depth,
  7026. widthSegments: widthSegments,
  7027. heightSegments: heightSegments,
  7028. depthSegments: depthSegments
  7029. };
  7030. const scope = this;
  7031. // segments
  7032. widthSegments = Math.floor( widthSegments );
  7033. heightSegments = Math.floor( heightSegments );
  7034. depthSegments = Math.floor( depthSegments );
  7035. // buffers
  7036. const indices = [];
  7037. const vertices = [];
  7038. const normals = [];
  7039. const uvs = [];
  7040. // helper variables
  7041. let numberOfVertices = 0;
  7042. let groupStart = 0;
  7043. // build each side of the box geometry
  7044. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7045. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7046. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7047. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7048. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7049. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7050. // build geometry
  7051. this.setIndex( indices );
  7052. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7053. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7054. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7055. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7056. const segmentWidth = width / gridX;
  7057. const segmentHeight = height / gridY;
  7058. const widthHalf = width / 2;
  7059. const heightHalf = height / 2;
  7060. const depthHalf = depth / 2;
  7061. const gridX1 = gridX + 1;
  7062. const gridY1 = gridY + 1;
  7063. let vertexCounter = 0;
  7064. let groupCount = 0;
  7065. const vector = new Vector3();
  7066. // generate vertices, normals and uvs
  7067. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7068. const y = iy * segmentHeight - heightHalf;
  7069. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7070. const x = ix * segmentWidth - widthHalf;
  7071. // set values to correct vector component
  7072. vector[ u ] = x * udir;
  7073. vector[ v ] = y * vdir;
  7074. vector[ w ] = depthHalf;
  7075. // now apply vector to vertex buffer
  7076. vertices.push( vector.x, vector.y, vector.z );
  7077. // set values to correct vector component
  7078. vector[ u ] = 0;
  7079. vector[ v ] = 0;
  7080. vector[ w ] = depth > 0 ? 1 : - 1;
  7081. // now apply vector to normal buffer
  7082. normals.push( vector.x, vector.y, vector.z );
  7083. // uvs
  7084. uvs.push( ix / gridX );
  7085. uvs.push( 1 - ( iy / gridY ) );
  7086. // counters
  7087. vertexCounter += 1;
  7088. }
  7089. }
  7090. // indices
  7091. // 1. you need three indices to draw a single face
  7092. // 2. a single segment consists of two faces
  7093. // 3. so we need to generate six (2*3) indices per segment
  7094. for ( let iy = 0; iy < gridY; iy ++ ) {
  7095. for ( let ix = 0; ix < gridX; ix ++ ) {
  7096. const a = numberOfVertices + ix + gridX1 * iy;
  7097. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7098. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7099. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7100. // faces
  7101. indices.push( a, b, d );
  7102. indices.push( b, c, d );
  7103. // increase counter
  7104. groupCount += 6;
  7105. }
  7106. }
  7107. // add a group to the geometry. this will ensure multi material support
  7108. scope.addGroup( groupStart, groupCount, materialIndex );
  7109. // calculate new start value for groups
  7110. groupStart += groupCount;
  7111. // update total number of vertices
  7112. numberOfVertices += vertexCounter;
  7113. }
  7114. }
  7115. copy( source ) {
  7116. super.copy( source );
  7117. this.parameters = Object.assign( {}, source.parameters );
  7118. return this;
  7119. }
  7120. static fromJSON( data ) {
  7121. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7122. }
  7123. }
  7124. /**
  7125. * Uniform Utilities
  7126. */
  7127. function cloneUniforms( src ) {
  7128. const dst = {};
  7129. for ( const u in src ) {
  7130. dst[ u ] = {};
  7131. for ( const p in src[ u ] ) {
  7132. const property = src[ u ][ p ];
  7133. if ( property && ( property.isColor ||
  7134. property.isMatrix3 || property.isMatrix4 ||
  7135. property.isVector2 || property.isVector3 || property.isVector4 ||
  7136. property.isTexture || property.isQuaternion ) ) {
  7137. if ( property.isRenderTargetTexture ) {
  7138. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7139. dst[ u ][ p ] = null;
  7140. } else {
  7141. dst[ u ][ p ] = property.clone();
  7142. }
  7143. } else if ( Array.isArray( property ) ) {
  7144. dst[ u ][ p ] = property.slice();
  7145. } else {
  7146. dst[ u ][ p ] = property;
  7147. }
  7148. }
  7149. }
  7150. return dst;
  7151. }
  7152. function mergeUniforms( uniforms ) {
  7153. const merged = {};
  7154. for ( let u = 0; u < uniforms.length; u ++ ) {
  7155. const tmp = cloneUniforms( uniforms[ u ] );
  7156. for ( const p in tmp ) {
  7157. merged[ p ] = tmp[ p ];
  7158. }
  7159. }
  7160. return merged;
  7161. }
  7162. function cloneUniformsGroups( src ) {
  7163. const dst = [];
  7164. for ( let u = 0; u < src.length; u ++ ) {
  7165. dst.push( src[ u ].clone() );
  7166. }
  7167. return dst;
  7168. }
  7169. function getUnlitUniformColorSpace( renderer ) {
  7170. if ( renderer.getRenderTarget() === null ) {
  7171. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7172. return renderer.outputColorSpace;
  7173. }
  7174. return LinearSRGBColorSpace;
  7175. }
  7176. // Legacy
  7177. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7178. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7179. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7180. class ShaderMaterial extends Material {
  7181. constructor( parameters ) {
  7182. super();
  7183. this.isShaderMaterial = true;
  7184. this.type = 'ShaderMaterial';
  7185. this.defines = {};
  7186. this.uniforms = {};
  7187. this.uniformsGroups = [];
  7188. this.vertexShader = default_vertex;
  7189. this.fragmentShader = default_fragment;
  7190. this.linewidth = 1;
  7191. this.wireframe = false;
  7192. this.wireframeLinewidth = 1;
  7193. this.fog = false; // set to use scene fog
  7194. this.lights = false; // set to use scene lights
  7195. this.clipping = false; // set to use user-defined clipping planes
  7196. this.forceSinglePass = true;
  7197. this.extensions = {
  7198. derivatives: false, // set to use derivatives
  7199. fragDepth: false, // set to use fragment depth values
  7200. drawBuffers: false, // set to use draw buffers
  7201. shaderTextureLOD: false // set to use shader texture LOD
  7202. };
  7203. // When rendered geometry doesn't include these attributes but the material does,
  7204. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7205. this.defaultAttributeValues = {
  7206. 'color': [ 1, 1, 1 ],
  7207. 'uv': [ 0, 0 ],
  7208. 'uv1': [ 0, 0 ]
  7209. };
  7210. this.index0AttributeName = undefined;
  7211. this.uniformsNeedUpdate = false;
  7212. this.glslVersion = null;
  7213. if ( parameters !== undefined ) {
  7214. this.setValues( parameters );
  7215. }
  7216. }
  7217. copy( source ) {
  7218. super.copy( source );
  7219. this.fragmentShader = source.fragmentShader;
  7220. this.vertexShader = source.vertexShader;
  7221. this.uniforms = cloneUniforms( source.uniforms );
  7222. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7223. this.defines = Object.assign( {}, source.defines );
  7224. this.wireframe = source.wireframe;
  7225. this.wireframeLinewidth = source.wireframeLinewidth;
  7226. this.fog = source.fog;
  7227. this.lights = source.lights;
  7228. this.clipping = source.clipping;
  7229. this.extensions = Object.assign( {}, source.extensions );
  7230. this.glslVersion = source.glslVersion;
  7231. return this;
  7232. }
  7233. toJSON( meta ) {
  7234. const data = super.toJSON( meta );
  7235. data.glslVersion = this.glslVersion;
  7236. data.uniforms = {};
  7237. for ( const name in this.uniforms ) {
  7238. const uniform = this.uniforms[ name ];
  7239. const value = uniform.value;
  7240. if ( value && value.isTexture ) {
  7241. data.uniforms[ name ] = {
  7242. type: 't',
  7243. value: value.toJSON( meta ).uuid
  7244. };
  7245. } else if ( value && value.isColor ) {
  7246. data.uniforms[ name ] = {
  7247. type: 'c',
  7248. value: value.getHex()
  7249. };
  7250. } else if ( value && value.isVector2 ) {
  7251. data.uniforms[ name ] = {
  7252. type: 'v2',
  7253. value: value.toArray()
  7254. };
  7255. } else if ( value && value.isVector3 ) {
  7256. data.uniforms[ name ] = {
  7257. type: 'v3',
  7258. value: value.toArray()
  7259. };
  7260. } else if ( value && value.isVector4 ) {
  7261. data.uniforms[ name ] = {
  7262. type: 'v4',
  7263. value: value.toArray()
  7264. };
  7265. } else if ( value && value.isMatrix3 ) {
  7266. data.uniforms[ name ] = {
  7267. type: 'm3',
  7268. value: value.toArray()
  7269. };
  7270. } else if ( value && value.isMatrix4 ) {
  7271. data.uniforms[ name ] = {
  7272. type: 'm4',
  7273. value: value.toArray()
  7274. };
  7275. } else {
  7276. data.uniforms[ name ] = {
  7277. value: value
  7278. };
  7279. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7280. }
  7281. }
  7282. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7283. data.vertexShader = this.vertexShader;
  7284. data.fragmentShader = this.fragmentShader;
  7285. data.lights = this.lights;
  7286. data.clipping = this.clipping;
  7287. const extensions = {};
  7288. for ( const key in this.extensions ) {
  7289. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7290. }
  7291. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7292. return data;
  7293. }
  7294. }
  7295. class Camera extends Object3D {
  7296. constructor() {
  7297. super();
  7298. this.isCamera = true;
  7299. this.type = 'Camera';
  7300. this.matrixWorldInverse = new Matrix4();
  7301. this.projectionMatrix = new Matrix4();
  7302. this.projectionMatrixInverse = new Matrix4();
  7303. this.coordinateSystem = WebGLCoordinateSystem;
  7304. }
  7305. copy( source, recursive ) {
  7306. super.copy( source, recursive );
  7307. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7308. this.projectionMatrix.copy( source.projectionMatrix );
  7309. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7310. this.coordinateSystem = source.coordinateSystem;
  7311. return this;
  7312. }
  7313. getWorldDirection( target ) {
  7314. this.updateWorldMatrix( true, false );
  7315. const e = this.matrixWorld.elements;
  7316. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7317. }
  7318. updateMatrixWorld( force ) {
  7319. super.updateMatrixWorld( force );
  7320. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7321. }
  7322. updateWorldMatrix( updateParents, updateChildren ) {
  7323. super.updateWorldMatrix( updateParents, updateChildren );
  7324. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7325. }
  7326. clone() {
  7327. return new this.constructor().copy( this );
  7328. }
  7329. }
  7330. class PerspectiveCamera extends Camera {
  7331. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7332. super();
  7333. this.isPerspectiveCamera = true;
  7334. this.type = 'PerspectiveCamera';
  7335. this.fov = fov;
  7336. this.zoom = 1;
  7337. this.near = near;
  7338. this.far = far;
  7339. this.focus = 10;
  7340. this.aspect = aspect;
  7341. this.view = null;
  7342. this.filmGauge = 35; // width of the film (default in millimeters)
  7343. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7344. this.updateProjectionMatrix();
  7345. }
  7346. copy( source, recursive ) {
  7347. super.copy( source, recursive );
  7348. this.fov = source.fov;
  7349. this.zoom = source.zoom;
  7350. this.near = source.near;
  7351. this.far = source.far;
  7352. this.focus = source.focus;
  7353. this.aspect = source.aspect;
  7354. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7355. this.filmGauge = source.filmGauge;
  7356. this.filmOffset = source.filmOffset;
  7357. return this;
  7358. }
  7359. /**
  7360. * Sets the FOV by focal length in respect to the current .filmGauge.
  7361. *
  7362. * The default film gauge is 35, so that the focal length can be specified for
  7363. * a 35mm (full frame) camera.
  7364. *
  7365. * Values for focal length and film gauge must have the same unit.
  7366. */
  7367. setFocalLength( focalLength ) {
  7368. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7369. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7370. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7371. this.updateProjectionMatrix();
  7372. }
  7373. /**
  7374. * Calculates the focal length from the current .fov and .filmGauge.
  7375. */
  7376. getFocalLength() {
  7377. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7378. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7379. }
  7380. getEffectiveFOV() {
  7381. return RAD2DEG * 2 * Math.atan(
  7382. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7383. }
  7384. getFilmWidth() {
  7385. // film not completely covered in portrait format (aspect < 1)
  7386. return this.filmGauge * Math.min( this.aspect, 1 );
  7387. }
  7388. getFilmHeight() {
  7389. // film not completely covered in landscape format (aspect > 1)
  7390. return this.filmGauge / Math.max( this.aspect, 1 );
  7391. }
  7392. /**
  7393. * Sets an offset in a larger frustum. This is useful for multi-window or
  7394. * multi-monitor/multi-machine setups.
  7395. *
  7396. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7397. * the monitors are in grid like this
  7398. *
  7399. * +---+---+---+
  7400. * | A | B | C |
  7401. * +---+---+---+
  7402. * | D | E | F |
  7403. * +---+---+---+
  7404. *
  7405. * then for each monitor you would call it like this
  7406. *
  7407. * const w = 1920;
  7408. * const h = 1080;
  7409. * const fullWidth = w * 3;
  7410. * const fullHeight = h * 2;
  7411. *
  7412. * --A--
  7413. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7414. * --B--
  7415. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7416. * --C--
  7417. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7418. * --D--
  7419. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7420. * --E--
  7421. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7422. * --F--
  7423. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7424. *
  7425. * Note there is no reason monitors have to be the same size or in a grid.
  7426. */
  7427. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7428. this.aspect = fullWidth / fullHeight;
  7429. if ( this.view === null ) {
  7430. this.view = {
  7431. enabled: true,
  7432. fullWidth: 1,
  7433. fullHeight: 1,
  7434. offsetX: 0,
  7435. offsetY: 0,
  7436. width: 1,
  7437. height: 1
  7438. };
  7439. }
  7440. this.view.enabled = true;
  7441. this.view.fullWidth = fullWidth;
  7442. this.view.fullHeight = fullHeight;
  7443. this.view.offsetX = x;
  7444. this.view.offsetY = y;
  7445. this.view.width = width;
  7446. this.view.height = height;
  7447. this.updateProjectionMatrix();
  7448. }
  7449. clearViewOffset() {
  7450. if ( this.view !== null ) {
  7451. this.view.enabled = false;
  7452. }
  7453. this.updateProjectionMatrix();
  7454. }
  7455. updateProjectionMatrix() {
  7456. const near = this.near;
  7457. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7458. let height = 2 * top;
  7459. let width = this.aspect * height;
  7460. let left = - 0.5 * width;
  7461. const view = this.view;
  7462. if ( this.view !== null && this.view.enabled ) {
  7463. const fullWidth = view.fullWidth,
  7464. fullHeight = view.fullHeight;
  7465. left += view.offsetX * width / fullWidth;
  7466. top -= view.offsetY * height / fullHeight;
  7467. width *= view.width / fullWidth;
  7468. height *= view.height / fullHeight;
  7469. }
  7470. const skew = this.filmOffset;
  7471. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7472. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7473. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7474. }
  7475. toJSON( meta ) {
  7476. const data = super.toJSON( meta );
  7477. data.object.fov = this.fov;
  7478. data.object.zoom = this.zoom;
  7479. data.object.near = this.near;
  7480. data.object.far = this.far;
  7481. data.object.focus = this.focus;
  7482. data.object.aspect = this.aspect;
  7483. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7484. data.object.filmGauge = this.filmGauge;
  7485. data.object.filmOffset = this.filmOffset;
  7486. return data;
  7487. }
  7488. }
  7489. const fov = - 90; // negative fov is not an error
  7490. const aspect = 1;
  7491. class CubeCamera extends Object3D {
  7492. constructor( near, far, renderTarget ) {
  7493. super();
  7494. this.type = 'CubeCamera';
  7495. this.renderTarget = renderTarget;
  7496. this.coordinateSystem = null;
  7497. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7498. cameraPX.layers = this.layers;
  7499. this.add( cameraPX );
  7500. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7501. cameraNX.layers = this.layers;
  7502. this.add( cameraNX );
  7503. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7504. cameraPY.layers = this.layers;
  7505. this.add( cameraPY );
  7506. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7507. cameraNY.layers = this.layers;
  7508. this.add( cameraNY );
  7509. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7510. cameraPZ.layers = this.layers;
  7511. this.add( cameraPZ );
  7512. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7513. cameraNZ.layers = this.layers;
  7514. this.add( cameraNZ );
  7515. }
  7516. updateCoordinateSystem() {
  7517. const coordinateSystem = this.coordinateSystem;
  7518. const cameras = this.children.concat();
  7519. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7520. for ( const camera of cameras ) this.remove( camera );
  7521. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7522. cameraPX.up.set( 0, 1, 0 );
  7523. cameraPX.lookAt( 1, 0, 0 );
  7524. cameraNX.up.set( 0, 1, 0 );
  7525. cameraNX.lookAt( - 1, 0, 0 );
  7526. cameraPY.up.set( 0, 0, - 1 );
  7527. cameraPY.lookAt( 0, 1, 0 );
  7528. cameraNY.up.set( 0, 0, 1 );
  7529. cameraNY.lookAt( 0, - 1, 0 );
  7530. cameraPZ.up.set( 0, 1, 0 );
  7531. cameraPZ.lookAt( 0, 0, 1 );
  7532. cameraNZ.up.set( 0, 1, 0 );
  7533. cameraNZ.lookAt( 0, 0, - 1 );
  7534. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7535. cameraPX.up.set( 0, - 1, 0 );
  7536. cameraPX.lookAt( - 1, 0, 0 );
  7537. cameraNX.up.set( 0, - 1, 0 );
  7538. cameraNX.lookAt( 1, 0, 0 );
  7539. cameraPY.up.set( 0, 0, 1 );
  7540. cameraPY.lookAt( 0, 1, 0 );
  7541. cameraNY.up.set( 0, 0, - 1 );
  7542. cameraNY.lookAt( 0, - 1, 0 );
  7543. cameraPZ.up.set( 0, - 1, 0 );
  7544. cameraPZ.lookAt( 0, 0, 1 );
  7545. cameraNZ.up.set( 0, - 1, 0 );
  7546. cameraNZ.lookAt( 0, 0, - 1 );
  7547. } else {
  7548. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7549. }
  7550. for ( const camera of cameras ) {
  7551. this.add( camera );
  7552. camera.updateMatrixWorld();
  7553. }
  7554. }
  7555. update( renderer, scene ) {
  7556. if ( this.parent === null ) this.updateMatrixWorld();
  7557. const renderTarget = this.renderTarget;
  7558. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7559. this.coordinateSystem = renderer.coordinateSystem;
  7560. this.updateCoordinateSystem();
  7561. }
  7562. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7563. const currentRenderTarget = renderer.getRenderTarget();
  7564. const currentToneMapping = renderer.toneMapping;
  7565. const currentXrEnabled = renderer.xr.enabled;
  7566. renderer.toneMapping = NoToneMapping;
  7567. renderer.xr.enabled = false;
  7568. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7569. renderTarget.texture.generateMipmaps = false;
  7570. renderer.setRenderTarget( renderTarget, 0 );
  7571. renderer.render( scene, cameraPX );
  7572. renderer.setRenderTarget( renderTarget, 1 );
  7573. renderer.render( scene, cameraNX );
  7574. renderer.setRenderTarget( renderTarget, 2 );
  7575. renderer.render( scene, cameraPY );
  7576. renderer.setRenderTarget( renderTarget, 3 );
  7577. renderer.render( scene, cameraNY );
  7578. renderer.setRenderTarget( renderTarget, 4 );
  7579. renderer.render( scene, cameraPZ );
  7580. renderTarget.texture.generateMipmaps = generateMipmaps;
  7581. renderer.setRenderTarget( renderTarget, 5 );
  7582. renderer.render( scene, cameraNZ );
  7583. renderer.setRenderTarget( currentRenderTarget );
  7584. renderer.toneMapping = currentToneMapping;
  7585. renderer.xr.enabled = currentXrEnabled;
  7586. renderTarget.texture.needsPMREMUpdate = true;
  7587. }
  7588. }
  7589. class CubeTexture extends Texture {
  7590. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7591. images = images !== undefined ? images : [];
  7592. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7593. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7594. this.isCubeTexture = true;
  7595. this.flipY = false;
  7596. }
  7597. get images() {
  7598. return this.image;
  7599. }
  7600. set images( value ) {
  7601. this.image = value;
  7602. }
  7603. }
  7604. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7605. constructor( size = 1, options = {} ) {
  7606. super( size, size, options );
  7607. this.isWebGLCubeRenderTarget = true;
  7608. const image = { width: size, height: size, depth: 1 };
  7609. const images = [ image, image, image, image, image, image ];
  7610. if ( options.encoding !== undefined ) {
  7611. // @deprecated, r152
  7612. warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  7613. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  7614. }
  7615. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7616. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7617. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7618. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7619. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7620. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7621. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7622. this.texture.isRenderTargetTexture = true;
  7623. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7624. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7625. }
  7626. fromEquirectangularTexture( renderer, texture ) {
  7627. this.texture.type = texture.type;
  7628. this.texture.colorSpace = texture.colorSpace;
  7629. this.texture.generateMipmaps = texture.generateMipmaps;
  7630. this.texture.minFilter = texture.minFilter;
  7631. this.texture.magFilter = texture.magFilter;
  7632. const shader = {
  7633. uniforms: {
  7634. tEquirect: { value: null },
  7635. },
  7636. vertexShader: /* glsl */`
  7637. varying vec3 vWorldDirection;
  7638. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7639. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7640. }
  7641. void main() {
  7642. vWorldDirection = transformDirection( position, modelMatrix );
  7643. #include <begin_vertex>
  7644. #include <project_vertex>
  7645. }
  7646. `,
  7647. fragmentShader: /* glsl */`
  7648. uniform sampler2D tEquirect;
  7649. varying vec3 vWorldDirection;
  7650. #include <common>
  7651. void main() {
  7652. vec3 direction = normalize( vWorldDirection );
  7653. vec2 sampleUV = equirectUv( direction );
  7654. gl_FragColor = texture2D( tEquirect, sampleUV );
  7655. }
  7656. `
  7657. };
  7658. const geometry = new BoxGeometry( 5, 5, 5 );
  7659. const material = new ShaderMaterial( {
  7660. name: 'CubemapFromEquirect',
  7661. uniforms: cloneUniforms( shader.uniforms ),
  7662. vertexShader: shader.vertexShader,
  7663. fragmentShader: shader.fragmentShader,
  7664. side: BackSide,
  7665. blending: NoBlending
  7666. } );
  7667. material.uniforms.tEquirect.value = texture;
  7668. const mesh = new Mesh( geometry, material );
  7669. const currentMinFilter = texture.minFilter;
  7670. // Avoid blurred poles
  7671. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7672. const camera = new CubeCamera( 1, 10, this );
  7673. camera.update( renderer, mesh );
  7674. texture.minFilter = currentMinFilter;
  7675. mesh.geometry.dispose();
  7676. mesh.material.dispose();
  7677. return this;
  7678. }
  7679. clear( renderer, color, depth, stencil ) {
  7680. const currentRenderTarget = renderer.getRenderTarget();
  7681. for ( let i = 0; i < 6; i ++ ) {
  7682. renderer.setRenderTarget( this, i );
  7683. renderer.clear( color, depth, stencil );
  7684. }
  7685. renderer.setRenderTarget( currentRenderTarget );
  7686. }
  7687. }
  7688. const _vector1 = /*@__PURE__*/ new Vector3();
  7689. const _vector2 = /*@__PURE__*/ new Vector3();
  7690. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7691. class Plane {
  7692. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7693. this.isPlane = true;
  7694. // normal is assumed to be normalized
  7695. this.normal = normal;
  7696. this.constant = constant;
  7697. }
  7698. set( normal, constant ) {
  7699. this.normal.copy( normal );
  7700. this.constant = constant;
  7701. return this;
  7702. }
  7703. setComponents( x, y, z, w ) {
  7704. this.normal.set( x, y, z );
  7705. this.constant = w;
  7706. return this;
  7707. }
  7708. setFromNormalAndCoplanarPoint( normal, point ) {
  7709. this.normal.copy( normal );
  7710. this.constant = - point.dot( this.normal );
  7711. return this;
  7712. }
  7713. setFromCoplanarPoints( a, b, c ) {
  7714. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7715. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7716. this.setFromNormalAndCoplanarPoint( normal, a );
  7717. return this;
  7718. }
  7719. copy( plane ) {
  7720. this.normal.copy( plane.normal );
  7721. this.constant = plane.constant;
  7722. return this;
  7723. }
  7724. normalize() {
  7725. // Note: will lead to a divide by zero if the plane is invalid.
  7726. const inverseNormalLength = 1.0 / this.normal.length();
  7727. this.normal.multiplyScalar( inverseNormalLength );
  7728. this.constant *= inverseNormalLength;
  7729. return this;
  7730. }
  7731. negate() {
  7732. this.constant *= - 1;
  7733. this.normal.negate();
  7734. return this;
  7735. }
  7736. distanceToPoint( point ) {
  7737. return this.normal.dot( point ) + this.constant;
  7738. }
  7739. distanceToSphere( sphere ) {
  7740. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7741. }
  7742. projectPoint( point, target ) {
  7743. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7744. }
  7745. intersectLine( line, target ) {
  7746. const direction = line.delta( _vector1 );
  7747. const denominator = this.normal.dot( direction );
  7748. if ( denominator === 0 ) {
  7749. // line is coplanar, return origin
  7750. if ( this.distanceToPoint( line.start ) === 0 ) {
  7751. return target.copy( line.start );
  7752. }
  7753. // Unsure if this is the correct method to handle this case.
  7754. return null;
  7755. }
  7756. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7757. if ( t < 0 || t > 1 ) {
  7758. return null;
  7759. }
  7760. return target.copy( line.start ).addScaledVector( direction, t );
  7761. }
  7762. intersectsLine( line ) {
  7763. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7764. const startSign = this.distanceToPoint( line.start );
  7765. const endSign = this.distanceToPoint( line.end );
  7766. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7767. }
  7768. intersectsBox( box ) {
  7769. return box.intersectsPlane( this );
  7770. }
  7771. intersectsSphere( sphere ) {
  7772. return sphere.intersectsPlane( this );
  7773. }
  7774. coplanarPoint( target ) {
  7775. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7776. }
  7777. applyMatrix4( matrix, optionalNormalMatrix ) {
  7778. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7779. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7780. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7781. this.constant = - referencePoint.dot( normal );
  7782. return this;
  7783. }
  7784. translate( offset ) {
  7785. this.constant -= offset.dot( this.normal );
  7786. return this;
  7787. }
  7788. equals( plane ) {
  7789. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7790. }
  7791. clone() {
  7792. return new this.constructor().copy( this );
  7793. }
  7794. }
  7795. const _sphere$4 = /*@__PURE__*/ new Sphere();
  7796. const _vector$6 = /*@__PURE__*/ new Vector3();
  7797. class Frustum {
  7798. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7799. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7800. }
  7801. set( p0, p1, p2, p3, p4, p5 ) {
  7802. const planes = this.planes;
  7803. planes[ 0 ].copy( p0 );
  7804. planes[ 1 ].copy( p1 );
  7805. planes[ 2 ].copy( p2 );
  7806. planes[ 3 ].copy( p3 );
  7807. planes[ 4 ].copy( p4 );
  7808. planes[ 5 ].copy( p5 );
  7809. return this;
  7810. }
  7811. copy( frustum ) {
  7812. const planes = this.planes;
  7813. for ( let i = 0; i < 6; i ++ ) {
  7814. planes[ i ].copy( frustum.planes[ i ] );
  7815. }
  7816. return this;
  7817. }
  7818. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7819. const planes = this.planes;
  7820. const me = m.elements;
  7821. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7822. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7823. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7824. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7825. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7826. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7827. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7828. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7829. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7830. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7831. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7832. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7833. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7834. } else {
  7835. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7836. }
  7837. return this;
  7838. }
  7839. intersectsObject( object ) {
  7840. if ( object.boundingSphere !== undefined ) {
  7841. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7842. _sphere$4.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7843. } else {
  7844. const geometry = object.geometry;
  7845. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7846. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7847. }
  7848. return this.intersectsSphere( _sphere$4 );
  7849. }
  7850. intersectsSprite( sprite ) {
  7851. _sphere$4.center.set( 0, 0, 0 );
  7852. _sphere$4.radius = 0.7071067811865476;
  7853. _sphere$4.applyMatrix4( sprite.matrixWorld );
  7854. return this.intersectsSphere( _sphere$4 );
  7855. }
  7856. intersectsSphere( sphere ) {
  7857. const planes = this.planes;
  7858. const center = sphere.center;
  7859. const negRadius = - sphere.radius;
  7860. for ( let i = 0; i < 6; i ++ ) {
  7861. const distance = planes[ i ].distanceToPoint( center );
  7862. if ( distance < negRadius ) {
  7863. return false;
  7864. }
  7865. }
  7866. return true;
  7867. }
  7868. intersectsBox( box ) {
  7869. const planes = this.planes;
  7870. for ( let i = 0; i < 6; i ++ ) {
  7871. const plane = planes[ i ];
  7872. // corner at max distance
  7873. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7874. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7875. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7876. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  7877. return false;
  7878. }
  7879. }
  7880. return true;
  7881. }
  7882. containsPoint( point ) {
  7883. const planes = this.planes;
  7884. for ( let i = 0; i < 6; i ++ ) {
  7885. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7886. return false;
  7887. }
  7888. }
  7889. return true;
  7890. }
  7891. clone() {
  7892. return new this.constructor().copy( this );
  7893. }
  7894. }
  7895. function WebGLAnimation() {
  7896. let context = null;
  7897. let isAnimating = false;
  7898. let animationLoop = null;
  7899. let requestId = null;
  7900. function onAnimationFrame( time, frame ) {
  7901. animationLoop( time, frame );
  7902. requestId = context.requestAnimationFrame( onAnimationFrame );
  7903. }
  7904. return {
  7905. start: function () {
  7906. if ( isAnimating === true ) return;
  7907. if ( animationLoop === null ) return;
  7908. requestId = context.requestAnimationFrame( onAnimationFrame );
  7909. isAnimating = true;
  7910. },
  7911. stop: function () {
  7912. context.cancelAnimationFrame( requestId );
  7913. isAnimating = false;
  7914. },
  7915. setAnimationLoop: function ( callback ) {
  7916. animationLoop = callback;
  7917. },
  7918. setContext: function ( value ) {
  7919. context = value;
  7920. }
  7921. };
  7922. }
  7923. function WebGLAttributes( gl, capabilities ) {
  7924. const isWebGL2 = capabilities.isWebGL2;
  7925. const buffers = new WeakMap();
  7926. function createBuffer( attribute, bufferType ) {
  7927. const array = attribute.array;
  7928. const usage = attribute.usage;
  7929. const buffer = gl.createBuffer();
  7930. gl.bindBuffer( bufferType, buffer );
  7931. gl.bufferData( bufferType, array, usage );
  7932. attribute.onUploadCallback();
  7933. let type;
  7934. if ( array instanceof Float32Array ) {
  7935. type = gl.FLOAT;
  7936. } else if ( array instanceof Uint16Array ) {
  7937. if ( attribute.isFloat16BufferAttribute ) {
  7938. if ( isWebGL2 ) {
  7939. type = gl.HALF_FLOAT;
  7940. } else {
  7941. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7942. }
  7943. } else {
  7944. type = gl.UNSIGNED_SHORT;
  7945. }
  7946. } else if ( array instanceof Int16Array ) {
  7947. type = gl.SHORT;
  7948. } else if ( array instanceof Uint32Array ) {
  7949. type = gl.UNSIGNED_INT;
  7950. } else if ( array instanceof Int32Array ) {
  7951. type = gl.INT;
  7952. } else if ( array instanceof Int8Array ) {
  7953. type = gl.BYTE;
  7954. } else if ( array instanceof Uint8Array ) {
  7955. type = gl.UNSIGNED_BYTE;
  7956. } else if ( array instanceof Uint8ClampedArray ) {
  7957. type = gl.UNSIGNED_BYTE;
  7958. } else {
  7959. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7960. }
  7961. return {
  7962. buffer: buffer,
  7963. type: type,
  7964. bytesPerElement: array.BYTES_PER_ELEMENT,
  7965. version: attribute.version
  7966. };
  7967. }
  7968. function updateBuffer( buffer, attribute, bufferType ) {
  7969. const array = attribute.array;
  7970. const updateRange = attribute.updateRange;
  7971. gl.bindBuffer( bufferType, buffer );
  7972. if ( updateRange.count === - 1 ) {
  7973. // Not using update ranges
  7974. gl.bufferSubData( bufferType, 0, array );
  7975. } else {
  7976. if ( isWebGL2 ) {
  7977. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7978. array, updateRange.offset, updateRange.count );
  7979. } else {
  7980. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7981. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7982. }
  7983. updateRange.count = - 1; // reset range
  7984. }
  7985. attribute.onUploadCallback();
  7986. }
  7987. //
  7988. function get( attribute ) {
  7989. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7990. return buffers.get( attribute );
  7991. }
  7992. function remove( attribute ) {
  7993. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7994. const data = buffers.get( attribute );
  7995. if ( data ) {
  7996. gl.deleteBuffer( data.buffer );
  7997. buffers.delete( attribute );
  7998. }
  7999. }
  8000. function update( attribute, bufferType ) {
  8001. if ( attribute.isGLBufferAttribute ) {
  8002. const cached = buffers.get( attribute );
  8003. if ( ! cached || cached.version < attribute.version ) {
  8004. buffers.set( attribute, {
  8005. buffer: attribute.buffer,
  8006. type: attribute.type,
  8007. bytesPerElement: attribute.elementSize,
  8008. version: attribute.version
  8009. } );
  8010. }
  8011. return;
  8012. }
  8013. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8014. const data = buffers.get( attribute );
  8015. if ( data === undefined ) {
  8016. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8017. } else if ( data.version < attribute.version ) {
  8018. updateBuffer( data.buffer, attribute, bufferType );
  8019. data.version = attribute.version;
  8020. }
  8021. }
  8022. return {
  8023. get: get,
  8024. remove: remove,
  8025. update: update
  8026. };
  8027. }
  8028. class PlaneGeometry extends BufferGeometry {
  8029. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8030. super();
  8031. this.type = 'PlaneGeometry';
  8032. this.parameters = {
  8033. width: width,
  8034. height: height,
  8035. widthSegments: widthSegments,
  8036. heightSegments: heightSegments
  8037. };
  8038. const width_half = width / 2;
  8039. const height_half = height / 2;
  8040. const gridX = Math.floor( widthSegments );
  8041. const gridY = Math.floor( heightSegments );
  8042. const gridX1 = gridX + 1;
  8043. const gridY1 = gridY + 1;
  8044. const segment_width = width / gridX;
  8045. const segment_height = height / gridY;
  8046. //
  8047. const indices = [];
  8048. const vertices = [];
  8049. const normals = [];
  8050. const uvs = [];
  8051. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8052. const y = iy * segment_height - height_half;
  8053. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8054. const x = ix * segment_width - width_half;
  8055. vertices.push( x, - y, 0 );
  8056. normals.push( 0, 0, 1 );
  8057. uvs.push( ix / gridX );
  8058. uvs.push( 1 - ( iy / gridY ) );
  8059. }
  8060. }
  8061. for ( let iy = 0; iy < gridY; iy ++ ) {
  8062. for ( let ix = 0; ix < gridX; ix ++ ) {
  8063. const a = ix + gridX1 * iy;
  8064. const b = ix + gridX1 * ( iy + 1 );
  8065. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8066. const d = ( ix + 1 ) + gridX1 * iy;
  8067. indices.push( a, b, d );
  8068. indices.push( b, c, d );
  8069. }
  8070. }
  8071. this.setIndex( indices );
  8072. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8073. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8074. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8075. }
  8076. copy( source ) {
  8077. super.copy( source );
  8078. this.parameters = Object.assign( {}, source.parameters );
  8079. return this;
  8080. }
  8081. static fromJSON( data ) {
  8082. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8083. }
  8084. }
  8085. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8086. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8087. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8088. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8089. 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( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  8090. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8091. var begin_vertex = "vec3 transformed = vec3( position );";
  8092. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8093. 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";
  8094. 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\t return 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 R21 = R12;\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";
  8095. 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";
  8096. 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";
  8097. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8098. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8099. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8100. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8101. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8102. 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";
  8103. 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";
  8104. 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};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\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";
  8105. 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";
  8106. 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";
  8107. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8108. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8109. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8110. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8111. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8112. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( 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}";
  8113. 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";
  8114. 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";
  8115. 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";
  8116. 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";
  8117. 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";
  8118. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8119. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8120. 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";
  8121. 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";
  8122. 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}";
  8123. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8124. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8125. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8126. 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 GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, 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 GeometricContext geometry, 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";
  8127. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\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, const in GeometricContext geometry, 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 GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\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 GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\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";
  8128. 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";
  8129. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8130. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, 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";
  8131. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8132. 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 GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, 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";
  8133. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\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";
  8134. 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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, 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 GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, 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( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, 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}";
  8135. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometry.viewDir ) );\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, geometry, 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, geometry, 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, geometry, 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, geometry, 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, geometry, 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, geometry, 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, geometry, 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\tirradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\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 ], geometry.normal );\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";
  8136. 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( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometry.viewDir, geometry.normal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8137. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  8138. 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";
  8139. 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";
  8140. 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";
  8141. 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";
  8142. var map_fragment = "#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, vMapUv );\n#endif";
  8143. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8144. 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";
  8145. 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";
  8146. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8147. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8148. 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";
  8149. 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";
  8150. 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";
  8151. 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";
  8152. 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, vNormalMapUv );\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 geometryNormal = normal;";
  8153. 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";
  8154. 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";
  8155. 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";
  8156. 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";
  8157. 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";
  8158. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8159. 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";
  8160. 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";
  8161. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8162. var output_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 );";
  8163. 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}";
  8164. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8165. 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;";
  8166. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8167. 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";
  8168. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8169. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8170. 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";
  8171. 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";
  8172. 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";
  8173. 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}";
  8174. 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";
  8175. 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";
  8176. 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";
  8177. 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";
  8178. 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";
  8179. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8180. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8181. 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; }";
  8182. 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";
  8183. 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";
  8184. var uv_pars_fragment = "#ifdef USE_UV\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";
  8185. var uv_pars_vertex = "#ifdef USE_UV\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";
  8186. var uv_vertex = "#ifdef USE_UV\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";
  8187. 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";
  8188. 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}";
  8189. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8190. 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}";
  8191. 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 <encodings_fragment>\n}";
  8192. 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}";
  8193. 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 <encodings_fragment>\n}";
  8194. 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}";
  8195. 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 <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 <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}";
  8196. 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}";
  8197. 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 <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\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8198. 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}";
  8199. 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 <encodings_fragment>\n}";
  8200. 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}";
  8201. 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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8202. 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}";
  8203. 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 <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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8204. 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}";
  8205. 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 <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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8206. 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}";
  8207. 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 <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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8208. 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}";
  8209. 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}";
  8210. 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}";
  8211. 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 <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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8212. 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}";
  8213. 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 <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 <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( geometry.clearcoatNormal, geometry.viewDir ) );\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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8214. 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}";
  8215. 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 <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 <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 <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8216. 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}";
  8217. 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 <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\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8218. 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}";
  8219. 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 <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8220. 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}";
  8221. 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 <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\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8222. const ShaderChunk = {
  8223. alphamap_fragment: alphamap_fragment,
  8224. alphamap_pars_fragment: alphamap_pars_fragment,
  8225. alphatest_fragment: alphatest_fragment,
  8226. alphatest_pars_fragment: alphatest_pars_fragment,
  8227. aomap_fragment: aomap_fragment,
  8228. aomap_pars_fragment: aomap_pars_fragment,
  8229. begin_vertex: begin_vertex,
  8230. beginnormal_vertex: beginnormal_vertex,
  8231. bsdfs: bsdfs,
  8232. iridescence_fragment: iridescence_fragment,
  8233. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8234. clipping_planes_fragment: clipping_planes_fragment,
  8235. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8236. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8237. clipping_planes_vertex: clipping_planes_vertex,
  8238. color_fragment: color_fragment,
  8239. color_pars_fragment: color_pars_fragment,
  8240. color_pars_vertex: color_pars_vertex,
  8241. color_vertex: color_vertex,
  8242. common: common,
  8243. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8244. defaultnormal_vertex: defaultnormal_vertex,
  8245. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8246. displacementmap_vertex: displacementmap_vertex,
  8247. emissivemap_fragment: emissivemap_fragment,
  8248. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8249. encodings_fragment: encodings_fragment,
  8250. encodings_pars_fragment: encodings_pars_fragment,
  8251. envmap_fragment: envmap_fragment,
  8252. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8253. envmap_pars_fragment: envmap_pars_fragment,
  8254. envmap_pars_vertex: envmap_pars_vertex,
  8255. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8256. envmap_vertex: envmap_vertex,
  8257. fog_vertex: fog_vertex,
  8258. fog_pars_vertex: fog_pars_vertex,
  8259. fog_fragment: fog_fragment,
  8260. fog_pars_fragment: fog_pars_fragment,
  8261. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8262. lightmap_fragment: lightmap_fragment,
  8263. lightmap_pars_fragment: lightmap_pars_fragment,
  8264. lights_lambert_fragment: lights_lambert_fragment,
  8265. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8266. lights_pars_begin: lights_pars_begin,
  8267. lights_toon_fragment: lights_toon_fragment,
  8268. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8269. lights_phong_fragment: lights_phong_fragment,
  8270. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8271. lights_physical_fragment: lights_physical_fragment,
  8272. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8273. lights_fragment_begin: lights_fragment_begin,
  8274. lights_fragment_maps: lights_fragment_maps,
  8275. lights_fragment_end: lights_fragment_end,
  8276. logdepthbuf_fragment: logdepthbuf_fragment,
  8277. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8278. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8279. logdepthbuf_vertex: logdepthbuf_vertex,
  8280. map_fragment: map_fragment,
  8281. map_pars_fragment: map_pars_fragment,
  8282. map_particle_fragment: map_particle_fragment,
  8283. map_particle_pars_fragment: map_particle_pars_fragment,
  8284. metalnessmap_fragment: metalnessmap_fragment,
  8285. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8286. morphcolor_vertex: morphcolor_vertex,
  8287. morphnormal_vertex: morphnormal_vertex,
  8288. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8289. morphtarget_vertex: morphtarget_vertex,
  8290. normal_fragment_begin: normal_fragment_begin,
  8291. normal_fragment_maps: normal_fragment_maps,
  8292. normal_pars_fragment: normal_pars_fragment,
  8293. normal_pars_vertex: normal_pars_vertex,
  8294. normal_vertex: normal_vertex,
  8295. normalmap_pars_fragment: normalmap_pars_fragment,
  8296. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8297. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8298. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8299. iridescence_pars_fragment: iridescence_pars_fragment,
  8300. output_fragment: output_fragment,
  8301. packing: packing,
  8302. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8303. project_vertex: project_vertex,
  8304. dithering_fragment: dithering_fragment,
  8305. dithering_pars_fragment: dithering_pars_fragment,
  8306. roughnessmap_fragment: roughnessmap_fragment,
  8307. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8308. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8309. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8310. shadowmap_vertex: shadowmap_vertex,
  8311. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8312. skinbase_vertex: skinbase_vertex,
  8313. skinning_pars_vertex: skinning_pars_vertex,
  8314. skinning_vertex: skinning_vertex,
  8315. skinnormal_vertex: skinnormal_vertex,
  8316. specularmap_fragment: specularmap_fragment,
  8317. specularmap_pars_fragment: specularmap_pars_fragment,
  8318. tonemapping_fragment: tonemapping_fragment,
  8319. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8320. transmission_fragment: transmission_fragment,
  8321. transmission_pars_fragment: transmission_pars_fragment,
  8322. uv_pars_fragment: uv_pars_fragment,
  8323. uv_pars_vertex: uv_pars_vertex,
  8324. uv_vertex: uv_vertex,
  8325. worldpos_vertex: worldpos_vertex,
  8326. background_vert: vertex$h,
  8327. background_frag: fragment$h,
  8328. backgroundCube_vert: vertex$g,
  8329. backgroundCube_frag: fragment$g,
  8330. cube_vert: vertex$f,
  8331. cube_frag: fragment$f,
  8332. depth_vert: vertex$e,
  8333. depth_frag: fragment$e,
  8334. distanceRGBA_vert: vertex$d,
  8335. distanceRGBA_frag: fragment$d,
  8336. equirect_vert: vertex$c,
  8337. equirect_frag: fragment$c,
  8338. linedashed_vert: vertex$b,
  8339. linedashed_frag: fragment$b,
  8340. meshbasic_vert: vertex$a,
  8341. meshbasic_frag: fragment$a,
  8342. meshlambert_vert: vertex$9,
  8343. meshlambert_frag: fragment$9,
  8344. meshmatcap_vert: vertex$8,
  8345. meshmatcap_frag: fragment$8,
  8346. meshnormal_vert: vertex$7,
  8347. meshnormal_frag: fragment$7,
  8348. meshphong_vert: vertex$6,
  8349. meshphong_frag: fragment$6,
  8350. meshphysical_vert: vertex$5,
  8351. meshphysical_frag: fragment$5,
  8352. meshtoon_vert: vertex$4,
  8353. meshtoon_frag: fragment$4,
  8354. points_vert: vertex$3,
  8355. points_frag: fragment$3,
  8356. shadow_vert: vertex$2,
  8357. shadow_frag: fragment$2,
  8358. sprite_vert: vertex$1,
  8359. sprite_frag: fragment$1
  8360. };
  8361. /**
  8362. * Uniforms library for shared webgl shaders
  8363. */
  8364. const UniformsLib = {
  8365. common: {
  8366. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8367. opacity: { value: 1.0 },
  8368. map: { value: null },
  8369. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8370. alphaMap: { value: null },
  8371. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8372. alphaTest: { value: 0 }
  8373. },
  8374. specularmap: {
  8375. specularMap: { value: null },
  8376. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8377. },
  8378. envmap: {
  8379. envMap: { value: null },
  8380. flipEnvMap: { value: - 1 },
  8381. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8382. ior: { value: 1.5 }, // physical
  8383. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8384. },
  8385. aomap: {
  8386. aoMap: { value: null },
  8387. aoMapIntensity: { value: 1 },
  8388. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8389. },
  8390. lightmap: {
  8391. lightMap: { value: null },
  8392. lightMapIntensity: { value: 1 },
  8393. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8394. },
  8395. bumpmap: {
  8396. bumpMap: { value: null },
  8397. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8398. bumpScale: { value: 1 }
  8399. },
  8400. normalmap: {
  8401. normalMap: { value: null },
  8402. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8403. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8404. },
  8405. displacementmap: {
  8406. displacementMap: { value: null },
  8407. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8408. displacementScale: { value: 1 },
  8409. displacementBias: { value: 0 }
  8410. },
  8411. emissivemap: {
  8412. emissiveMap: { value: null },
  8413. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8414. },
  8415. metalnessmap: {
  8416. metalnessMap: { value: null },
  8417. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8418. },
  8419. roughnessmap: {
  8420. roughnessMap: { value: null },
  8421. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8422. },
  8423. gradientmap: {
  8424. gradientMap: { value: null }
  8425. },
  8426. fog: {
  8427. fogDensity: { value: 0.00025 },
  8428. fogNear: { value: 1 },
  8429. fogFar: { value: 2000 },
  8430. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8431. },
  8432. lights: {
  8433. ambientLightColor: { value: [] },
  8434. lightProbe: { value: [] },
  8435. directionalLights: { value: [], properties: {
  8436. direction: {},
  8437. color: {}
  8438. } },
  8439. directionalLightShadows: { value: [], properties: {
  8440. shadowBias: {},
  8441. shadowNormalBias: {},
  8442. shadowRadius: {},
  8443. shadowMapSize: {}
  8444. } },
  8445. directionalShadowMap: { value: [] },
  8446. directionalShadowMatrix: { value: [] },
  8447. spotLights: { value: [], properties: {
  8448. color: {},
  8449. position: {},
  8450. direction: {},
  8451. distance: {},
  8452. coneCos: {},
  8453. penumbraCos: {},
  8454. decay: {}
  8455. } },
  8456. spotLightShadows: { value: [], properties: {
  8457. shadowBias: {},
  8458. shadowNormalBias: {},
  8459. shadowRadius: {},
  8460. shadowMapSize: {}
  8461. } },
  8462. spotLightMap: { value: [] },
  8463. spotShadowMap: { value: [] },
  8464. spotLightMatrix: { value: [] },
  8465. pointLights: { value: [], properties: {
  8466. color: {},
  8467. position: {},
  8468. decay: {},
  8469. distance: {}
  8470. } },
  8471. pointLightShadows: { value: [], properties: {
  8472. shadowBias: {},
  8473. shadowNormalBias: {},
  8474. shadowRadius: {},
  8475. shadowMapSize: {},
  8476. shadowCameraNear: {},
  8477. shadowCameraFar: {}
  8478. } },
  8479. pointShadowMap: { value: [] },
  8480. pointShadowMatrix: { value: [] },
  8481. hemisphereLights: { value: [], properties: {
  8482. direction: {},
  8483. skyColor: {},
  8484. groundColor: {}
  8485. } },
  8486. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8487. rectAreaLights: { value: [], properties: {
  8488. color: {},
  8489. position: {},
  8490. width: {},
  8491. height: {}
  8492. } },
  8493. ltc_1: { value: null },
  8494. ltc_2: { value: null }
  8495. },
  8496. points: {
  8497. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8498. opacity: { value: 1.0 },
  8499. size: { value: 1.0 },
  8500. scale: { value: 1.0 },
  8501. map: { value: null },
  8502. alphaMap: { value: null },
  8503. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8504. alphaTest: { value: 0 },
  8505. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8506. },
  8507. sprite: {
  8508. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8509. opacity: { value: 1.0 },
  8510. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8511. rotation: { value: 0.0 },
  8512. map: { value: null },
  8513. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8514. alphaMap: { value: null },
  8515. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8516. alphaTest: { value: 0 }
  8517. }
  8518. };
  8519. const ShaderLib = {
  8520. basic: {
  8521. uniforms: /*@__PURE__*/ mergeUniforms( [
  8522. UniformsLib.common,
  8523. UniformsLib.specularmap,
  8524. UniformsLib.envmap,
  8525. UniformsLib.aomap,
  8526. UniformsLib.lightmap,
  8527. UniformsLib.fog
  8528. ] ),
  8529. vertexShader: ShaderChunk.meshbasic_vert,
  8530. fragmentShader: ShaderChunk.meshbasic_frag
  8531. },
  8532. lambert: {
  8533. uniforms: /*@__PURE__*/ mergeUniforms( [
  8534. UniformsLib.common,
  8535. UniformsLib.specularmap,
  8536. UniformsLib.envmap,
  8537. UniformsLib.aomap,
  8538. UniformsLib.lightmap,
  8539. UniformsLib.emissivemap,
  8540. UniformsLib.bumpmap,
  8541. UniformsLib.normalmap,
  8542. UniformsLib.displacementmap,
  8543. UniformsLib.fog,
  8544. UniformsLib.lights,
  8545. {
  8546. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8547. }
  8548. ] ),
  8549. vertexShader: ShaderChunk.meshlambert_vert,
  8550. fragmentShader: ShaderChunk.meshlambert_frag
  8551. },
  8552. phong: {
  8553. uniforms: /*@__PURE__*/ mergeUniforms( [
  8554. UniformsLib.common,
  8555. UniformsLib.specularmap,
  8556. UniformsLib.envmap,
  8557. UniformsLib.aomap,
  8558. UniformsLib.lightmap,
  8559. UniformsLib.emissivemap,
  8560. UniformsLib.bumpmap,
  8561. UniformsLib.normalmap,
  8562. UniformsLib.displacementmap,
  8563. UniformsLib.fog,
  8564. UniformsLib.lights,
  8565. {
  8566. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8567. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8568. shininess: { value: 30 }
  8569. }
  8570. ] ),
  8571. vertexShader: ShaderChunk.meshphong_vert,
  8572. fragmentShader: ShaderChunk.meshphong_frag
  8573. },
  8574. standard: {
  8575. uniforms: /*@__PURE__*/ mergeUniforms( [
  8576. UniformsLib.common,
  8577. UniformsLib.envmap,
  8578. UniformsLib.aomap,
  8579. UniformsLib.lightmap,
  8580. UniformsLib.emissivemap,
  8581. UniformsLib.bumpmap,
  8582. UniformsLib.normalmap,
  8583. UniformsLib.displacementmap,
  8584. UniformsLib.roughnessmap,
  8585. UniformsLib.metalnessmap,
  8586. UniformsLib.fog,
  8587. UniformsLib.lights,
  8588. {
  8589. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8590. roughness: { value: 1.0 },
  8591. metalness: { value: 0.0 },
  8592. envMapIntensity: { value: 1 } // temporary
  8593. }
  8594. ] ),
  8595. vertexShader: ShaderChunk.meshphysical_vert,
  8596. fragmentShader: ShaderChunk.meshphysical_frag
  8597. },
  8598. toon: {
  8599. uniforms: /*@__PURE__*/ mergeUniforms( [
  8600. UniformsLib.common,
  8601. UniformsLib.aomap,
  8602. UniformsLib.lightmap,
  8603. UniformsLib.emissivemap,
  8604. UniformsLib.bumpmap,
  8605. UniformsLib.normalmap,
  8606. UniformsLib.displacementmap,
  8607. UniformsLib.gradientmap,
  8608. UniformsLib.fog,
  8609. UniformsLib.lights,
  8610. {
  8611. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8612. }
  8613. ] ),
  8614. vertexShader: ShaderChunk.meshtoon_vert,
  8615. fragmentShader: ShaderChunk.meshtoon_frag
  8616. },
  8617. matcap: {
  8618. uniforms: /*@__PURE__*/ mergeUniforms( [
  8619. UniformsLib.common,
  8620. UniformsLib.bumpmap,
  8621. UniformsLib.normalmap,
  8622. UniformsLib.displacementmap,
  8623. UniformsLib.fog,
  8624. {
  8625. matcap: { value: null }
  8626. }
  8627. ] ),
  8628. vertexShader: ShaderChunk.meshmatcap_vert,
  8629. fragmentShader: ShaderChunk.meshmatcap_frag
  8630. },
  8631. points: {
  8632. uniforms: /*@__PURE__*/ mergeUniforms( [
  8633. UniformsLib.points,
  8634. UniformsLib.fog
  8635. ] ),
  8636. vertexShader: ShaderChunk.points_vert,
  8637. fragmentShader: ShaderChunk.points_frag
  8638. },
  8639. dashed: {
  8640. uniforms: /*@__PURE__*/ mergeUniforms( [
  8641. UniformsLib.common,
  8642. UniformsLib.fog,
  8643. {
  8644. scale: { value: 1 },
  8645. dashSize: { value: 1 },
  8646. totalSize: { value: 2 }
  8647. }
  8648. ] ),
  8649. vertexShader: ShaderChunk.linedashed_vert,
  8650. fragmentShader: ShaderChunk.linedashed_frag
  8651. },
  8652. depth: {
  8653. uniforms: /*@__PURE__*/ mergeUniforms( [
  8654. UniformsLib.common,
  8655. UniformsLib.displacementmap
  8656. ] ),
  8657. vertexShader: ShaderChunk.depth_vert,
  8658. fragmentShader: ShaderChunk.depth_frag
  8659. },
  8660. normal: {
  8661. uniforms: /*@__PURE__*/ mergeUniforms( [
  8662. UniformsLib.common,
  8663. UniformsLib.bumpmap,
  8664. UniformsLib.normalmap,
  8665. UniformsLib.displacementmap,
  8666. {
  8667. opacity: { value: 1.0 }
  8668. }
  8669. ] ),
  8670. vertexShader: ShaderChunk.meshnormal_vert,
  8671. fragmentShader: ShaderChunk.meshnormal_frag
  8672. },
  8673. sprite: {
  8674. uniforms: /*@__PURE__*/ mergeUniforms( [
  8675. UniformsLib.sprite,
  8676. UniformsLib.fog
  8677. ] ),
  8678. vertexShader: ShaderChunk.sprite_vert,
  8679. fragmentShader: ShaderChunk.sprite_frag
  8680. },
  8681. background: {
  8682. uniforms: {
  8683. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8684. t2D: { value: null },
  8685. backgroundIntensity: { value: 1 }
  8686. },
  8687. vertexShader: ShaderChunk.background_vert,
  8688. fragmentShader: ShaderChunk.background_frag
  8689. },
  8690. backgroundCube: {
  8691. uniforms: {
  8692. envMap: { value: null },
  8693. flipEnvMap: { value: - 1 },
  8694. backgroundBlurriness: { value: 0 },
  8695. backgroundIntensity: { value: 1 }
  8696. },
  8697. vertexShader: ShaderChunk.backgroundCube_vert,
  8698. fragmentShader: ShaderChunk.backgroundCube_frag
  8699. },
  8700. cube: {
  8701. uniforms: {
  8702. tCube: { value: null },
  8703. tFlip: { value: - 1 },
  8704. opacity: { value: 1.0 }
  8705. },
  8706. vertexShader: ShaderChunk.cube_vert,
  8707. fragmentShader: ShaderChunk.cube_frag
  8708. },
  8709. equirect: {
  8710. uniforms: {
  8711. tEquirect: { value: null },
  8712. },
  8713. vertexShader: ShaderChunk.equirect_vert,
  8714. fragmentShader: ShaderChunk.equirect_frag
  8715. },
  8716. distanceRGBA: {
  8717. uniforms: /*@__PURE__*/ mergeUniforms( [
  8718. UniformsLib.common,
  8719. UniformsLib.displacementmap,
  8720. {
  8721. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8722. nearDistance: { value: 1 },
  8723. farDistance: { value: 1000 }
  8724. }
  8725. ] ),
  8726. vertexShader: ShaderChunk.distanceRGBA_vert,
  8727. fragmentShader: ShaderChunk.distanceRGBA_frag
  8728. },
  8729. shadow: {
  8730. uniforms: /*@__PURE__*/ mergeUniforms( [
  8731. UniformsLib.lights,
  8732. UniformsLib.fog,
  8733. {
  8734. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8735. opacity: { value: 1.0 }
  8736. },
  8737. ] ),
  8738. vertexShader: ShaderChunk.shadow_vert,
  8739. fragmentShader: ShaderChunk.shadow_frag
  8740. }
  8741. };
  8742. ShaderLib.physical = {
  8743. uniforms: /*@__PURE__*/ mergeUniforms( [
  8744. ShaderLib.standard.uniforms,
  8745. {
  8746. clearcoat: { value: 0 },
  8747. clearcoatMap: { value: null },
  8748. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8749. clearcoatNormalMap: { value: null },
  8750. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8751. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8752. clearcoatRoughness: { value: 0 },
  8753. clearcoatRoughnessMap: { value: null },
  8754. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8755. iridescence: { value: 0 },
  8756. iridescenceMap: { value: null },
  8757. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8758. iridescenceIOR: { value: 1.3 },
  8759. iridescenceThicknessMinimum: { value: 100 },
  8760. iridescenceThicknessMaximum: { value: 400 },
  8761. iridescenceThicknessMap: { value: null },
  8762. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8763. sheen: { value: 0 },
  8764. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8765. sheenColorMap: { value: null },
  8766. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8767. sheenRoughness: { value: 1 },
  8768. sheenRoughnessMap: { value: null },
  8769. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8770. transmission: { value: 0 },
  8771. transmissionMap: { value: null },
  8772. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8773. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8774. transmissionSamplerMap: { value: null },
  8775. thickness: { value: 0 },
  8776. thicknessMap: { value: null },
  8777. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8778. attenuationDistance: { value: 0 },
  8779. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8780. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8781. specularColorMap: { value: null },
  8782. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8783. specularIntensity: { value: 1 },
  8784. specularIntensityMap: { value: null },
  8785. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8786. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8787. anisotropyMap: { value: null },
  8788. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8789. }
  8790. ] ),
  8791. vertexShader: ShaderChunk.meshphysical_vert,
  8792. fragmentShader: ShaderChunk.meshphysical_frag
  8793. };
  8794. const _rgb = { r: 0, b: 0, g: 0 };
  8795. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8796. const clearColor = new Color( 0x000000 );
  8797. let clearAlpha = alpha === true ? 0 : 1;
  8798. let planeMesh;
  8799. let boxMesh;
  8800. let currentBackground = null;
  8801. let currentBackgroundVersion = 0;
  8802. let currentTonemapping = null;
  8803. function render( renderList, scene ) {
  8804. let forceClear = false;
  8805. let background = scene.isScene === true ? scene.background : null;
  8806. if ( background && background.isTexture ) {
  8807. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8808. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8809. }
  8810. if ( background === null ) {
  8811. setClear( clearColor, clearAlpha );
  8812. } else if ( background && background.isColor ) {
  8813. setClear( background, 1 );
  8814. forceClear = true;
  8815. }
  8816. const xr = renderer.xr;
  8817. const environmentBlendMode = xr.getEnvironmentBlendMode();
  8818. switch ( environmentBlendMode ) {
  8819. case 'opaque':
  8820. forceClear = true;
  8821. break;
  8822. case 'additive':
  8823. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8824. forceClear = true;
  8825. break;
  8826. case 'alpha-blend':
  8827. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8828. forceClear = true;
  8829. break;
  8830. }
  8831. if ( renderer.autoClear || forceClear ) {
  8832. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8833. }
  8834. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8835. if ( boxMesh === undefined ) {
  8836. boxMesh = new Mesh(
  8837. new BoxGeometry( 1, 1, 1 ),
  8838. new ShaderMaterial( {
  8839. name: 'BackgroundCubeMaterial',
  8840. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8841. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8842. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8843. side: BackSide,
  8844. depthTest: false,
  8845. depthWrite: false,
  8846. fog: false
  8847. } )
  8848. );
  8849. boxMesh.geometry.deleteAttribute( 'normal' );
  8850. boxMesh.geometry.deleteAttribute( 'uv' );
  8851. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8852. this.matrixWorld.copyPosition( camera.matrixWorld );
  8853. };
  8854. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8855. Object.defineProperty( boxMesh.material, 'envMap', {
  8856. get: function () {
  8857. return this.uniforms.envMap.value;
  8858. }
  8859. } );
  8860. objects.update( boxMesh );
  8861. }
  8862. boxMesh.material.uniforms.envMap.value = background;
  8863. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8864. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8865. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8866. boxMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;
  8867. if ( currentBackground !== background ||
  8868. currentBackgroundVersion !== background.version ||
  8869. currentTonemapping !== renderer.toneMapping ) {
  8870. boxMesh.material.needsUpdate = true;
  8871. currentBackground = background;
  8872. currentBackgroundVersion = background.version;
  8873. currentTonemapping = renderer.toneMapping;
  8874. }
  8875. boxMesh.layers.enableAll();
  8876. // push to the pre-sorted opaque render list
  8877. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8878. } else if ( background && background.isTexture ) {
  8879. if ( planeMesh === undefined ) {
  8880. planeMesh = new Mesh(
  8881. new PlaneGeometry( 2, 2 ),
  8882. new ShaderMaterial( {
  8883. name: 'BackgroundMaterial',
  8884. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8885. vertexShader: ShaderLib.background.vertexShader,
  8886. fragmentShader: ShaderLib.background.fragmentShader,
  8887. side: FrontSide,
  8888. depthTest: false,
  8889. depthWrite: false,
  8890. fog: false
  8891. } )
  8892. );
  8893. planeMesh.geometry.deleteAttribute( 'normal' );
  8894. // add "map" material property so the renderer can evaluate it like for built-in materials
  8895. Object.defineProperty( planeMesh.material, 'map', {
  8896. get: function () {
  8897. return this.uniforms.t2D.value;
  8898. }
  8899. } );
  8900. objects.update( planeMesh );
  8901. }
  8902. planeMesh.material.uniforms.t2D.value = background;
  8903. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8904. planeMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;
  8905. if ( background.matrixAutoUpdate === true ) {
  8906. background.updateMatrix();
  8907. }
  8908. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8909. if ( currentBackground !== background ||
  8910. currentBackgroundVersion !== background.version ||
  8911. currentTonemapping !== renderer.toneMapping ) {
  8912. planeMesh.material.needsUpdate = true;
  8913. currentBackground = background;
  8914. currentBackgroundVersion = background.version;
  8915. currentTonemapping = renderer.toneMapping;
  8916. }
  8917. planeMesh.layers.enableAll();
  8918. // push to the pre-sorted opaque render list
  8919. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8920. }
  8921. }
  8922. function setClear( color, alpha ) {
  8923. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8924. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8925. }
  8926. return {
  8927. getClearColor: function () {
  8928. return clearColor;
  8929. },
  8930. setClearColor: function ( color, alpha = 1 ) {
  8931. clearColor.set( color );
  8932. clearAlpha = alpha;
  8933. setClear( clearColor, clearAlpha );
  8934. },
  8935. getClearAlpha: function () {
  8936. return clearAlpha;
  8937. },
  8938. setClearAlpha: function ( alpha ) {
  8939. clearAlpha = alpha;
  8940. setClear( clearColor, clearAlpha );
  8941. },
  8942. render: render
  8943. };
  8944. }
  8945. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8946. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8947. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8948. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8949. const bindingStates = {};
  8950. const defaultState = createBindingState( null );
  8951. let currentState = defaultState;
  8952. let forceUpdate = false;
  8953. function setup( object, material, program, geometry, index ) {
  8954. let updateBuffers = false;
  8955. if ( vaoAvailable ) {
  8956. const state = getBindingState( geometry, program, material );
  8957. if ( currentState !== state ) {
  8958. currentState = state;
  8959. bindVertexArrayObject( currentState.object );
  8960. }
  8961. updateBuffers = needsUpdate( object, geometry, program, index );
  8962. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8963. } else {
  8964. const wireframe = ( material.wireframe === true );
  8965. if ( currentState.geometry !== geometry.id ||
  8966. currentState.program !== program.id ||
  8967. currentState.wireframe !== wireframe ) {
  8968. currentState.geometry = geometry.id;
  8969. currentState.program = program.id;
  8970. currentState.wireframe = wireframe;
  8971. updateBuffers = true;
  8972. }
  8973. }
  8974. if ( index !== null ) {
  8975. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  8976. }
  8977. if ( updateBuffers || forceUpdate ) {
  8978. forceUpdate = false;
  8979. setupVertexAttributes( object, material, program, geometry );
  8980. if ( index !== null ) {
  8981. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  8982. }
  8983. }
  8984. }
  8985. function createVertexArrayObject() {
  8986. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8987. return extension.createVertexArrayOES();
  8988. }
  8989. function bindVertexArrayObject( vao ) {
  8990. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8991. return extension.bindVertexArrayOES( vao );
  8992. }
  8993. function deleteVertexArrayObject( vao ) {
  8994. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8995. return extension.deleteVertexArrayOES( vao );
  8996. }
  8997. function getBindingState( geometry, program, material ) {
  8998. const wireframe = ( material.wireframe === true );
  8999. let programMap = bindingStates[ geometry.id ];
  9000. if ( programMap === undefined ) {
  9001. programMap = {};
  9002. bindingStates[ geometry.id ] = programMap;
  9003. }
  9004. let stateMap = programMap[ program.id ];
  9005. if ( stateMap === undefined ) {
  9006. stateMap = {};
  9007. programMap[ program.id ] = stateMap;
  9008. }
  9009. let state = stateMap[ wireframe ];
  9010. if ( state === undefined ) {
  9011. state = createBindingState( createVertexArrayObject() );
  9012. stateMap[ wireframe ] = state;
  9013. }
  9014. return state;
  9015. }
  9016. function createBindingState( vao ) {
  9017. const newAttributes = [];
  9018. const enabledAttributes = [];
  9019. const attributeDivisors = [];
  9020. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9021. newAttributes[ i ] = 0;
  9022. enabledAttributes[ i ] = 0;
  9023. attributeDivisors[ i ] = 0;
  9024. }
  9025. return {
  9026. // for backward compatibility on non-VAO support browser
  9027. geometry: null,
  9028. program: null,
  9029. wireframe: false,
  9030. newAttributes: newAttributes,
  9031. enabledAttributes: enabledAttributes,
  9032. attributeDivisors: attributeDivisors,
  9033. object: vao,
  9034. attributes: {},
  9035. index: null
  9036. };
  9037. }
  9038. function needsUpdate( object, geometry, program, index ) {
  9039. const cachedAttributes = currentState.attributes;
  9040. const geometryAttributes = geometry.attributes;
  9041. let attributesNum = 0;
  9042. const programAttributes = program.getAttributes();
  9043. for ( const name in programAttributes ) {
  9044. const programAttribute = programAttributes[ name ];
  9045. if ( programAttribute.location >= 0 ) {
  9046. const cachedAttribute = cachedAttributes[ name ];
  9047. let geometryAttribute = geometryAttributes[ name ];
  9048. if ( geometryAttribute === undefined ) {
  9049. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9050. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9051. }
  9052. if ( cachedAttribute === undefined ) return true;
  9053. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9054. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9055. attributesNum ++;
  9056. }
  9057. }
  9058. if ( currentState.attributesNum !== attributesNum ) return true;
  9059. if ( currentState.index !== index ) return true;
  9060. return false;
  9061. }
  9062. function saveCache( object, geometry, program, index ) {
  9063. const cache = {};
  9064. const attributes = geometry.attributes;
  9065. let attributesNum = 0;
  9066. const programAttributes = program.getAttributes();
  9067. for ( const name in programAttributes ) {
  9068. const programAttribute = programAttributes[ name ];
  9069. if ( programAttribute.location >= 0 ) {
  9070. let attribute = attributes[ name ];
  9071. if ( attribute === undefined ) {
  9072. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9073. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9074. }
  9075. const data = {};
  9076. data.attribute = attribute;
  9077. if ( attribute && attribute.data ) {
  9078. data.data = attribute.data;
  9079. }
  9080. cache[ name ] = data;
  9081. attributesNum ++;
  9082. }
  9083. }
  9084. currentState.attributes = cache;
  9085. currentState.attributesNum = attributesNum;
  9086. currentState.index = index;
  9087. }
  9088. function initAttributes() {
  9089. const newAttributes = currentState.newAttributes;
  9090. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9091. newAttributes[ i ] = 0;
  9092. }
  9093. }
  9094. function enableAttribute( attribute ) {
  9095. enableAttributeAndDivisor( attribute, 0 );
  9096. }
  9097. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9098. const newAttributes = currentState.newAttributes;
  9099. const enabledAttributes = currentState.enabledAttributes;
  9100. const attributeDivisors = currentState.attributeDivisors;
  9101. newAttributes[ attribute ] = 1;
  9102. if ( enabledAttributes[ attribute ] === 0 ) {
  9103. gl.enableVertexAttribArray( attribute );
  9104. enabledAttributes[ attribute ] = 1;
  9105. }
  9106. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9107. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9108. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9109. attributeDivisors[ attribute ] = meshPerAttribute;
  9110. }
  9111. }
  9112. function disableUnusedAttributes() {
  9113. const newAttributes = currentState.newAttributes;
  9114. const enabledAttributes = currentState.enabledAttributes;
  9115. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9116. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9117. gl.disableVertexAttribArray( i );
  9118. enabledAttributes[ i ] = 0;
  9119. }
  9120. }
  9121. }
  9122. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9123. if ( integer === true ) {
  9124. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9125. } else {
  9126. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9127. }
  9128. }
  9129. function setupVertexAttributes( object, material, program, geometry ) {
  9130. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9131. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9132. }
  9133. initAttributes();
  9134. const geometryAttributes = geometry.attributes;
  9135. const programAttributes = program.getAttributes();
  9136. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9137. for ( const name in programAttributes ) {
  9138. const programAttribute = programAttributes[ name ];
  9139. if ( programAttribute.location >= 0 ) {
  9140. let geometryAttribute = geometryAttributes[ name ];
  9141. if ( geometryAttribute === undefined ) {
  9142. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9143. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9144. }
  9145. if ( geometryAttribute !== undefined ) {
  9146. const normalized = geometryAttribute.normalized;
  9147. const size = geometryAttribute.itemSize;
  9148. const attribute = attributes.get( geometryAttribute );
  9149. // TODO Attribute may not be available on context restore
  9150. if ( attribute === undefined ) continue;
  9151. const buffer = attribute.buffer;
  9152. const type = attribute.type;
  9153. const bytesPerElement = attribute.bytesPerElement;
  9154. // check for integer attributes (WebGL 2 only)
  9155. const integer = ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ) );
  9156. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9157. const data = geometryAttribute.data;
  9158. const stride = data.stride;
  9159. const offset = geometryAttribute.offset;
  9160. if ( data.isInstancedInterleavedBuffer ) {
  9161. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9162. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9163. }
  9164. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9165. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9166. }
  9167. } else {
  9168. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9169. enableAttribute( programAttribute.location + i );
  9170. }
  9171. }
  9172. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9173. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9174. vertexAttribPointer(
  9175. programAttribute.location + i,
  9176. size / programAttribute.locationSize,
  9177. type,
  9178. normalized,
  9179. stride * bytesPerElement,
  9180. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9181. integer
  9182. );
  9183. }
  9184. } else {
  9185. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9186. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9187. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9188. }
  9189. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9190. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9191. }
  9192. } else {
  9193. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9194. enableAttribute( programAttribute.location + i );
  9195. }
  9196. }
  9197. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9198. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9199. vertexAttribPointer(
  9200. programAttribute.location + i,
  9201. size / programAttribute.locationSize,
  9202. type,
  9203. normalized,
  9204. size * bytesPerElement,
  9205. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9206. integer
  9207. );
  9208. }
  9209. }
  9210. } else if ( materialDefaultAttributeValues !== undefined ) {
  9211. const value = materialDefaultAttributeValues[ name ];
  9212. if ( value !== undefined ) {
  9213. switch ( value.length ) {
  9214. case 2:
  9215. gl.vertexAttrib2fv( programAttribute.location, value );
  9216. break;
  9217. case 3:
  9218. gl.vertexAttrib3fv( programAttribute.location, value );
  9219. break;
  9220. case 4:
  9221. gl.vertexAttrib4fv( programAttribute.location, value );
  9222. break;
  9223. default:
  9224. gl.vertexAttrib1fv( programAttribute.location, value );
  9225. }
  9226. }
  9227. }
  9228. }
  9229. }
  9230. disableUnusedAttributes();
  9231. }
  9232. function dispose() {
  9233. reset();
  9234. for ( const geometryId in bindingStates ) {
  9235. const programMap = bindingStates[ geometryId ];
  9236. for ( const programId in programMap ) {
  9237. const stateMap = programMap[ programId ];
  9238. for ( const wireframe in stateMap ) {
  9239. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9240. delete stateMap[ wireframe ];
  9241. }
  9242. delete programMap[ programId ];
  9243. }
  9244. delete bindingStates[ geometryId ];
  9245. }
  9246. }
  9247. function releaseStatesOfGeometry( geometry ) {
  9248. if ( bindingStates[ geometry.id ] === undefined ) return;
  9249. const programMap = bindingStates[ geometry.id ];
  9250. for ( const programId in programMap ) {
  9251. const stateMap = programMap[ programId ];
  9252. for ( const wireframe in stateMap ) {
  9253. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9254. delete stateMap[ wireframe ];
  9255. }
  9256. delete programMap[ programId ];
  9257. }
  9258. delete bindingStates[ geometry.id ];
  9259. }
  9260. function releaseStatesOfProgram( program ) {
  9261. for ( const geometryId in bindingStates ) {
  9262. const programMap = bindingStates[ geometryId ];
  9263. if ( programMap[ program.id ] === undefined ) continue;
  9264. const stateMap = programMap[ program.id ];
  9265. for ( const wireframe in stateMap ) {
  9266. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9267. delete stateMap[ wireframe ];
  9268. }
  9269. delete programMap[ program.id ];
  9270. }
  9271. }
  9272. function reset() {
  9273. resetDefaultState();
  9274. forceUpdate = true;
  9275. if ( currentState === defaultState ) return;
  9276. currentState = defaultState;
  9277. bindVertexArrayObject( currentState.object );
  9278. }
  9279. // for backward-compatibility
  9280. function resetDefaultState() {
  9281. defaultState.geometry = null;
  9282. defaultState.program = null;
  9283. defaultState.wireframe = false;
  9284. }
  9285. return {
  9286. setup: setup,
  9287. reset: reset,
  9288. resetDefaultState: resetDefaultState,
  9289. dispose: dispose,
  9290. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9291. releaseStatesOfProgram: releaseStatesOfProgram,
  9292. initAttributes: initAttributes,
  9293. enableAttribute: enableAttribute,
  9294. disableUnusedAttributes: disableUnusedAttributes
  9295. };
  9296. }
  9297. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9298. const isWebGL2 = capabilities.isWebGL2;
  9299. let mode;
  9300. function setMode( value ) {
  9301. mode = value;
  9302. }
  9303. function render( start, count ) {
  9304. gl.drawArrays( mode, start, count );
  9305. info.update( count, mode, 1 );
  9306. }
  9307. function renderInstances( start, count, primcount ) {
  9308. if ( primcount === 0 ) return;
  9309. let extension, methodName;
  9310. if ( isWebGL2 ) {
  9311. extension = gl;
  9312. methodName = 'drawArraysInstanced';
  9313. } else {
  9314. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9315. methodName = 'drawArraysInstancedANGLE';
  9316. if ( extension === null ) {
  9317. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9318. return;
  9319. }
  9320. }
  9321. extension[ methodName ]( mode, start, count, primcount );
  9322. info.update( count, mode, primcount );
  9323. }
  9324. //
  9325. this.setMode = setMode;
  9326. this.render = render;
  9327. this.renderInstances = renderInstances;
  9328. }
  9329. function WebGLCapabilities( gl, extensions, parameters ) {
  9330. let maxAnisotropy;
  9331. function getMaxAnisotropy() {
  9332. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9333. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9334. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9335. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9336. } else {
  9337. maxAnisotropy = 0;
  9338. }
  9339. return maxAnisotropy;
  9340. }
  9341. function getMaxPrecision( precision ) {
  9342. if ( precision === 'highp' ) {
  9343. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9344. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9345. return 'highp';
  9346. }
  9347. precision = 'mediump';
  9348. }
  9349. if ( precision === 'mediump' ) {
  9350. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9351. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9352. return 'mediump';
  9353. }
  9354. }
  9355. return 'lowp';
  9356. }
  9357. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9358. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9359. const maxPrecision = getMaxPrecision( precision );
  9360. if ( maxPrecision !== precision ) {
  9361. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9362. precision = maxPrecision;
  9363. }
  9364. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9365. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9366. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9367. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9368. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9369. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9370. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9371. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9372. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9373. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9374. const vertexTextures = maxVertexTextures > 0;
  9375. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9376. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9377. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  9378. return {
  9379. isWebGL2: isWebGL2,
  9380. drawBuffers: drawBuffers,
  9381. getMaxAnisotropy: getMaxAnisotropy,
  9382. getMaxPrecision: getMaxPrecision,
  9383. precision: precision,
  9384. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9385. maxTextures: maxTextures,
  9386. maxVertexTextures: maxVertexTextures,
  9387. maxTextureSize: maxTextureSize,
  9388. maxCubemapSize: maxCubemapSize,
  9389. maxAttributes: maxAttributes,
  9390. maxVertexUniforms: maxVertexUniforms,
  9391. maxVaryings: maxVaryings,
  9392. maxFragmentUniforms: maxFragmentUniforms,
  9393. vertexTextures: vertexTextures,
  9394. floatFragmentTextures: floatFragmentTextures,
  9395. floatVertexTextures: floatVertexTextures,
  9396. maxSamples: maxSamples
  9397. };
  9398. }
  9399. function WebGLClipping( properties ) {
  9400. const scope = this;
  9401. let globalState = null,
  9402. numGlobalPlanes = 0,
  9403. localClippingEnabled = false,
  9404. renderingShadows = false;
  9405. const plane = new Plane(),
  9406. viewNormalMatrix = new Matrix3(),
  9407. uniform = { value: null, needsUpdate: false };
  9408. this.uniform = uniform;
  9409. this.numPlanes = 0;
  9410. this.numIntersection = 0;
  9411. this.init = function ( planes, enableLocalClipping ) {
  9412. const enabled =
  9413. planes.length !== 0 ||
  9414. enableLocalClipping ||
  9415. // enable state of previous frame - the clipping code has to
  9416. // run another frame in order to reset the state:
  9417. numGlobalPlanes !== 0 ||
  9418. localClippingEnabled;
  9419. localClippingEnabled = enableLocalClipping;
  9420. numGlobalPlanes = planes.length;
  9421. return enabled;
  9422. };
  9423. this.beginShadows = function () {
  9424. renderingShadows = true;
  9425. projectPlanes( null );
  9426. };
  9427. this.endShadows = function () {
  9428. renderingShadows = false;
  9429. };
  9430. this.setGlobalState = function ( planes, camera ) {
  9431. globalState = projectPlanes( planes, camera, 0 );
  9432. };
  9433. this.setState = function ( material, camera, useCache ) {
  9434. const planes = material.clippingPlanes,
  9435. clipIntersection = material.clipIntersection,
  9436. clipShadows = material.clipShadows;
  9437. const materialProperties = properties.get( material );
  9438. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9439. // there's no local clipping
  9440. if ( renderingShadows ) {
  9441. // there's no global clipping
  9442. projectPlanes( null );
  9443. } else {
  9444. resetGlobalState();
  9445. }
  9446. } else {
  9447. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9448. lGlobal = nGlobal * 4;
  9449. let dstArray = materialProperties.clippingState || null;
  9450. uniform.value = dstArray; // ensure unique state
  9451. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9452. for ( let i = 0; i !== lGlobal; ++ i ) {
  9453. dstArray[ i ] = globalState[ i ];
  9454. }
  9455. materialProperties.clippingState = dstArray;
  9456. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9457. this.numPlanes += nGlobal;
  9458. }
  9459. };
  9460. function resetGlobalState() {
  9461. if ( uniform.value !== globalState ) {
  9462. uniform.value = globalState;
  9463. uniform.needsUpdate = numGlobalPlanes > 0;
  9464. }
  9465. scope.numPlanes = numGlobalPlanes;
  9466. scope.numIntersection = 0;
  9467. }
  9468. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9469. const nPlanes = planes !== null ? planes.length : 0;
  9470. let dstArray = null;
  9471. if ( nPlanes !== 0 ) {
  9472. dstArray = uniform.value;
  9473. if ( skipTransform !== true || dstArray === null ) {
  9474. const flatSize = dstOffset + nPlanes * 4,
  9475. viewMatrix = camera.matrixWorldInverse;
  9476. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9477. if ( dstArray === null || dstArray.length < flatSize ) {
  9478. dstArray = new Float32Array( flatSize );
  9479. }
  9480. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9481. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9482. plane.normal.toArray( dstArray, i4 );
  9483. dstArray[ i4 + 3 ] = plane.constant;
  9484. }
  9485. }
  9486. uniform.value = dstArray;
  9487. uniform.needsUpdate = true;
  9488. }
  9489. scope.numPlanes = nPlanes;
  9490. scope.numIntersection = 0;
  9491. return dstArray;
  9492. }
  9493. }
  9494. function WebGLCubeMaps( renderer ) {
  9495. let cubemaps = new WeakMap();
  9496. function mapTextureMapping( texture, mapping ) {
  9497. if ( mapping === EquirectangularReflectionMapping ) {
  9498. texture.mapping = CubeReflectionMapping;
  9499. } else if ( mapping === EquirectangularRefractionMapping ) {
  9500. texture.mapping = CubeRefractionMapping;
  9501. }
  9502. return texture;
  9503. }
  9504. function get( texture ) {
  9505. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9506. const mapping = texture.mapping;
  9507. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9508. if ( cubemaps.has( texture ) ) {
  9509. const cubemap = cubemaps.get( texture ).texture;
  9510. return mapTextureMapping( cubemap, texture.mapping );
  9511. } else {
  9512. const image = texture.image;
  9513. if ( image && image.height > 0 ) {
  9514. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9515. renderTarget.fromEquirectangularTexture( renderer, texture );
  9516. cubemaps.set( texture, renderTarget );
  9517. texture.addEventListener( 'dispose', onTextureDispose );
  9518. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9519. } else {
  9520. // image not yet ready. try the conversion next frame
  9521. return null;
  9522. }
  9523. }
  9524. }
  9525. }
  9526. return texture;
  9527. }
  9528. function onTextureDispose( event ) {
  9529. const texture = event.target;
  9530. texture.removeEventListener( 'dispose', onTextureDispose );
  9531. const cubemap = cubemaps.get( texture );
  9532. if ( cubemap !== undefined ) {
  9533. cubemaps.delete( texture );
  9534. cubemap.dispose();
  9535. }
  9536. }
  9537. function dispose() {
  9538. cubemaps = new WeakMap();
  9539. }
  9540. return {
  9541. get: get,
  9542. dispose: dispose
  9543. };
  9544. }
  9545. class OrthographicCamera extends Camera {
  9546. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9547. super();
  9548. this.isOrthographicCamera = true;
  9549. this.type = 'OrthographicCamera';
  9550. this.zoom = 1;
  9551. this.view = null;
  9552. this.left = left;
  9553. this.right = right;
  9554. this.top = top;
  9555. this.bottom = bottom;
  9556. this.near = near;
  9557. this.far = far;
  9558. this.updateProjectionMatrix();
  9559. }
  9560. copy( source, recursive ) {
  9561. super.copy( source, recursive );
  9562. this.left = source.left;
  9563. this.right = source.right;
  9564. this.top = source.top;
  9565. this.bottom = source.bottom;
  9566. this.near = source.near;
  9567. this.far = source.far;
  9568. this.zoom = source.zoom;
  9569. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9570. return this;
  9571. }
  9572. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9573. if ( this.view === null ) {
  9574. this.view = {
  9575. enabled: true,
  9576. fullWidth: 1,
  9577. fullHeight: 1,
  9578. offsetX: 0,
  9579. offsetY: 0,
  9580. width: 1,
  9581. height: 1
  9582. };
  9583. }
  9584. this.view.enabled = true;
  9585. this.view.fullWidth = fullWidth;
  9586. this.view.fullHeight = fullHeight;
  9587. this.view.offsetX = x;
  9588. this.view.offsetY = y;
  9589. this.view.width = width;
  9590. this.view.height = height;
  9591. this.updateProjectionMatrix();
  9592. }
  9593. clearViewOffset() {
  9594. if ( this.view !== null ) {
  9595. this.view.enabled = false;
  9596. }
  9597. this.updateProjectionMatrix();
  9598. }
  9599. updateProjectionMatrix() {
  9600. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9601. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9602. const cx = ( this.right + this.left ) / 2;
  9603. const cy = ( this.top + this.bottom ) / 2;
  9604. let left = cx - dx;
  9605. let right = cx + dx;
  9606. let top = cy + dy;
  9607. let bottom = cy - dy;
  9608. if ( this.view !== null && this.view.enabled ) {
  9609. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9610. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9611. left += scaleW * this.view.offsetX;
  9612. right = left + scaleW * this.view.width;
  9613. top -= scaleH * this.view.offsetY;
  9614. bottom = top - scaleH * this.view.height;
  9615. }
  9616. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9617. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9618. }
  9619. toJSON( meta ) {
  9620. const data = super.toJSON( meta );
  9621. data.object.zoom = this.zoom;
  9622. data.object.left = this.left;
  9623. data.object.right = this.right;
  9624. data.object.top = this.top;
  9625. data.object.bottom = this.bottom;
  9626. data.object.near = this.near;
  9627. data.object.far = this.far;
  9628. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9629. return data;
  9630. }
  9631. }
  9632. const LOD_MIN = 4;
  9633. // The standard deviations (radians) associated with the extra mips. These are
  9634. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9635. // geometric shadowing function. These sigma values squared must match the
  9636. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9637. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9638. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9639. // samples and exit early, but not recompile the shader.
  9640. const MAX_SAMPLES = 20;
  9641. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9642. const _clearColor = /*@__PURE__*/ new Color();
  9643. let _oldTarget = null;
  9644. // Golden Ratio
  9645. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9646. const INV_PHI = 1 / PHI;
  9647. // Vertices of a dodecahedron (except the opposites, which represent the
  9648. // same axis), used as axis directions evenly spread on a sphere.
  9649. const _axisDirections = [
  9650. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9651. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9652. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9653. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9654. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9655. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9656. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9657. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9658. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9659. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9660. /**
  9661. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9662. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9663. * blur to be quickly accessed based on material roughness. It is packed into a
  9664. * special CubeUV format that allows us to perform custom interpolation so that
  9665. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9666. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9667. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9668. * higher roughness levels. In this way we maintain resolution to smoothly
  9669. * interpolate diffuse lighting while limiting sampling computation.
  9670. *
  9671. * Paper: Fast, Accurate Image-Based Lighting
  9672. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9673. */
  9674. class PMREMGenerator {
  9675. constructor( renderer ) {
  9676. this._renderer = renderer;
  9677. this._pingPongRenderTarget = null;
  9678. this._lodMax = 0;
  9679. this._cubeSize = 0;
  9680. this._lodPlanes = [];
  9681. this._sizeLods = [];
  9682. this._sigmas = [];
  9683. this._blurMaterial = null;
  9684. this._cubemapMaterial = null;
  9685. this._equirectMaterial = null;
  9686. this._compileMaterial( this._blurMaterial );
  9687. }
  9688. /**
  9689. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9690. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9691. * in radians to be applied to the scene before PMREM generation. Optional near
  9692. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9693. * is placed at the origin).
  9694. */
  9695. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9696. _oldTarget = this._renderer.getRenderTarget();
  9697. this._setSize( 256 );
  9698. const cubeUVRenderTarget = this._allocateTargets();
  9699. cubeUVRenderTarget.depthBuffer = true;
  9700. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9701. if ( sigma > 0 ) {
  9702. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9703. }
  9704. this._applyPMREM( cubeUVRenderTarget );
  9705. this._cleanup( cubeUVRenderTarget );
  9706. return cubeUVRenderTarget;
  9707. }
  9708. /**
  9709. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9710. * or HDR. The ideal input image size is 1k (1024 x 512),
  9711. * as this matches best with the 256 x 256 cubemap output.
  9712. */
  9713. fromEquirectangular( equirectangular, renderTarget = null ) {
  9714. return this._fromTexture( equirectangular, renderTarget );
  9715. }
  9716. /**
  9717. * Generates a PMREM from an cubemap texture, which can be either LDR
  9718. * or HDR. The ideal input cube size is 256 x 256,
  9719. * as this matches best with the 256 x 256 cubemap output.
  9720. */
  9721. fromCubemap( cubemap, renderTarget = null ) {
  9722. return this._fromTexture( cubemap, renderTarget );
  9723. }
  9724. /**
  9725. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9726. * your texture's network fetch for increased concurrency.
  9727. */
  9728. compileCubemapShader() {
  9729. if ( this._cubemapMaterial === null ) {
  9730. this._cubemapMaterial = _getCubemapMaterial();
  9731. this._compileMaterial( this._cubemapMaterial );
  9732. }
  9733. }
  9734. /**
  9735. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9736. * your texture's network fetch for increased concurrency.
  9737. */
  9738. compileEquirectangularShader() {
  9739. if ( this._equirectMaterial === null ) {
  9740. this._equirectMaterial = _getEquirectMaterial();
  9741. this._compileMaterial( this._equirectMaterial );
  9742. }
  9743. }
  9744. /**
  9745. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9746. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9747. * one of them will cause any others to also become unusable.
  9748. */
  9749. dispose() {
  9750. this._dispose();
  9751. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9752. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9753. }
  9754. // private interface
  9755. _setSize( cubeSize ) {
  9756. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9757. this._cubeSize = Math.pow( 2, this._lodMax );
  9758. }
  9759. _dispose() {
  9760. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9761. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9762. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9763. this._lodPlanes[ i ].dispose();
  9764. }
  9765. }
  9766. _cleanup( outputTarget ) {
  9767. this._renderer.setRenderTarget( _oldTarget );
  9768. outputTarget.scissorTest = false;
  9769. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9770. }
  9771. _fromTexture( texture, renderTarget ) {
  9772. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9773. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9774. } else { // Equirectangular
  9775. this._setSize( texture.image.width / 4 );
  9776. }
  9777. _oldTarget = this._renderer.getRenderTarget();
  9778. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9779. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9780. this._applyPMREM( cubeUVRenderTarget );
  9781. this._cleanup( cubeUVRenderTarget );
  9782. return cubeUVRenderTarget;
  9783. }
  9784. _allocateTargets() {
  9785. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9786. const height = 4 * this._cubeSize;
  9787. const params = {
  9788. magFilter: LinearFilter,
  9789. minFilter: LinearFilter,
  9790. generateMipmaps: false,
  9791. type: HalfFloatType,
  9792. format: RGBAFormat,
  9793. colorSpace: LinearSRGBColorSpace,
  9794. depthBuffer: false
  9795. };
  9796. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9797. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9798. if ( this._pingPongRenderTarget !== null ) {
  9799. this._dispose();
  9800. }
  9801. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9802. const { _lodMax } = this;
  9803. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9804. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9805. }
  9806. return cubeUVRenderTarget;
  9807. }
  9808. _compileMaterial( material ) {
  9809. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9810. this._renderer.compile( tmpMesh, _flatCamera );
  9811. }
  9812. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9813. const fov = 90;
  9814. const aspect = 1;
  9815. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9816. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9817. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9818. const renderer = this._renderer;
  9819. const originalAutoClear = renderer.autoClear;
  9820. const toneMapping = renderer.toneMapping;
  9821. renderer.getClearColor( _clearColor );
  9822. renderer.toneMapping = NoToneMapping;
  9823. renderer.autoClear = false;
  9824. const backgroundMaterial = new MeshBasicMaterial( {
  9825. name: 'PMREM.Background',
  9826. side: BackSide,
  9827. depthWrite: false,
  9828. depthTest: false,
  9829. } );
  9830. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9831. let useSolidColor = false;
  9832. const background = scene.background;
  9833. if ( background ) {
  9834. if ( background.isColor ) {
  9835. backgroundMaterial.color.copy( background );
  9836. scene.background = null;
  9837. useSolidColor = true;
  9838. }
  9839. } else {
  9840. backgroundMaterial.color.copy( _clearColor );
  9841. useSolidColor = true;
  9842. }
  9843. for ( let i = 0; i < 6; i ++ ) {
  9844. const col = i % 3;
  9845. if ( col === 0 ) {
  9846. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9847. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9848. } else if ( col === 1 ) {
  9849. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9850. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9851. } else {
  9852. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9853. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9854. }
  9855. const size = this._cubeSize;
  9856. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9857. renderer.setRenderTarget( cubeUVRenderTarget );
  9858. if ( useSolidColor ) {
  9859. renderer.render( backgroundBox, cubeCamera );
  9860. }
  9861. renderer.render( scene, cubeCamera );
  9862. }
  9863. backgroundBox.geometry.dispose();
  9864. backgroundBox.material.dispose();
  9865. renderer.toneMapping = toneMapping;
  9866. renderer.autoClear = originalAutoClear;
  9867. scene.background = background;
  9868. }
  9869. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9870. const renderer = this._renderer;
  9871. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9872. if ( isCubeTexture ) {
  9873. if ( this._cubemapMaterial === null ) {
  9874. this._cubemapMaterial = _getCubemapMaterial();
  9875. }
  9876. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9877. } else {
  9878. if ( this._equirectMaterial === null ) {
  9879. this._equirectMaterial = _getEquirectMaterial();
  9880. }
  9881. }
  9882. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9883. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9884. const uniforms = material.uniforms;
  9885. uniforms[ 'envMap' ].value = texture;
  9886. const size = this._cubeSize;
  9887. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9888. renderer.setRenderTarget( cubeUVRenderTarget );
  9889. renderer.render( mesh, _flatCamera );
  9890. }
  9891. _applyPMREM( cubeUVRenderTarget ) {
  9892. const renderer = this._renderer;
  9893. const autoClear = renderer.autoClear;
  9894. renderer.autoClear = false;
  9895. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9896. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9897. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9898. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9899. }
  9900. renderer.autoClear = autoClear;
  9901. }
  9902. /**
  9903. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9904. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9905. * the blur latitudinally (around the poles), and then longitudinally (towards
  9906. * the poles) to approximate the orthogonally-separable blur. It is least
  9907. * accurate at the poles, but still does a decent job.
  9908. */
  9909. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9910. const pingPongRenderTarget = this._pingPongRenderTarget;
  9911. this._halfBlur(
  9912. cubeUVRenderTarget,
  9913. pingPongRenderTarget,
  9914. lodIn,
  9915. lodOut,
  9916. sigma,
  9917. 'latitudinal',
  9918. poleAxis );
  9919. this._halfBlur(
  9920. pingPongRenderTarget,
  9921. cubeUVRenderTarget,
  9922. lodOut,
  9923. lodOut,
  9924. sigma,
  9925. 'longitudinal',
  9926. poleAxis );
  9927. }
  9928. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9929. const renderer = this._renderer;
  9930. const blurMaterial = this._blurMaterial;
  9931. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9932. console.error(
  9933. 'blur direction must be either latitudinal or longitudinal!' );
  9934. }
  9935. // Number of standard deviations at which to cut off the discrete approximation.
  9936. const STANDARD_DEVIATIONS = 3;
  9937. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9938. const blurUniforms = blurMaterial.uniforms;
  9939. const pixels = this._sizeLods[ lodIn ] - 1;
  9940. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9941. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9942. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9943. if ( samples > MAX_SAMPLES ) {
  9944. console.warn( `sigmaRadians, ${
  9945. sigmaRadians}, is too large and will clip, as it requested ${
  9946. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9947. }
  9948. const weights = [];
  9949. let sum = 0;
  9950. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9951. const x = i / sigmaPixels;
  9952. const weight = Math.exp( - x * x / 2 );
  9953. weights.push( weight );
  9954. if ( i === 0 ) {
  9955. sum += weight;
  9956. } else if ( i < samples ) {
  9957. sum += 2 * weight;
  9958. }
  9959. }
  9960. for ( let i = 0; i < weights.length; i ++ ) {
  9961. weights[ i ] = weights[ i ] / sum;
  9962. }
  9963. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9964. blurUniforms[ 'samples' ].value = samples;
  9965. blurUniforms[ 'weights' ].value = weights;
  9966. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9967. if ( poleAxis ) {
  9968. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9969. }
  9970. const { _lodMax } = this;
  9971. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9972. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9973. const outputSize = this._sizeLods[ lodOut ];
  9974. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9975. const y = 4 * ( this._cubeSize - outputSize );
  9976. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9977. renderer.setRenderTarget( targetOut );
  9978. renderer.render( blurMesh, _flatCamera );
  9979. }
  9980. }
  9981. function _createPlanes( lodMax ) {
  9982. const lodPlanes = [];
  9983. const sizeLods = [];
  9984. const sigmas = [];
  9985. let lod = lodMax;
  9986. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9987. for ( let i = 0; i < totalLods; i ++ ) {
  9988. const sizeLod = Math.pow( 2, lod );
  9989. sizeLods.push( sizeLod );
  9990. let sigma = 1.0 / sizeLod;
  9991. if ( i > lodMax - LOD_MIN ) {
  9992. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9993. } else if ( i === 0 ) {
  9994. sigma = 0;
  9995. }
  9996. sigmas.push( sigma );
  9997. const texelSize = 1.0 / ( sizeLod - 2 );
  9998. const min = - texelSize;
  9999. const max = 1 + texelSize;
  10000. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10001. const cubeFaces = 6;
  10002. const vertices = 6;
  10003. const positionSize = 3;
  10004. const uvSize = 2;
  10005. const faceIndexSize = 1;
  10006. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10007. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10008. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10009. for ( let face = 0; face < cubeFaces; face ++ ) {
  10010. const x = ( face % 3 ) * 2 / 3 - 1;
  10011. const y = face > 2 ? 0 : - 1;
  10012. const coordinates = [
  10013. x, y, 0,
  10014. x + 2 / 3, y, 0,
  10015. x + 2 / 3, y + 1, 0,
  10016. x, y, 0,
  10017. x + 2 / 3, y + 1, 0,
  10018. x, y + 1, 0
  10019. ];
  10020. position.set( coordinates, positionSize * vertices * face );
  10021. uv.set( uv1, uvSize * vertices * face );
  10022. const fill = [ face, face, face, face, face, face ];
  10023. faceIndex.set( fill, faceIndexSize * vertices * face );
  10024. }
  10025. const planes = new BufferGeometry();
  10026. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10027. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10028. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10029. lodPlanes.push( planes );
  10030. if ( lod > LOD_MIN ) {
  10031. lod --;
  10032. }
  10033. }
  10034. return { lodPlanes, sizeLods, sigmas };
  10035. }
  10036. function _createRenderTarget( width, height, params ) {
  10037. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10038. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10039. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10040. cubeUVRenderTarget.scissorTest = true;
  10041. return cubeUVRenderTarget;
  10042. }
  10043. function _setViewport( target, x, y, width, height ) {
  10044. target.viewport.set( x, y, width, height );
  10045. target.scissor.set( x, y, width, height );
  10046. }
  10047. function _getBlurShader( lodMax, width, height ) {
  10048. const weights = new Float32Array( MAX_SAMPLES );
  10049. const poleAxis = new Vector3( 0, 1, 0 );
  10050. const shaderMaterial = new ShaderMaterial( {
  10051. name: 'SphericalGaussianBlur',
  10052. defines: {
  10053. 'n': MAX_SAMPLES,
  10054. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10055. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10056. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10057. },
  10058. uniforms: {
  10059. 'envMap': { value: null },
  10060. 'samples': { value: 1 },
  10061. 'weights': { value: weights },
  10062. 'latitudinal': { value: false },
  10063. 'dTheta': { value: 0 },
  10064. 'mipInt': { value: 0 },
  10065. 'poleAxis': { value: poleAxis }
  10066. },
  10067. vertexShader: _getCommonVertexShader(),
  10068. fragmentShader: /* glsl */`
  10069. precision mediump float;
  10070. precision mediump int;
  10071. varying vec3 vOutputDirection;
  10072. uniform sampler2D envMap;
  10073. uniform int samples;
  10074. uniform float weights[ n ];
  10075. uniform bool latitudinal;
  10076. uniform float dTheta;
  10077. uniform float mipInt;
  10078. uniform vec3 poleAxis;
  10079. #define ENVMAP_TYPE_CUBE_UV
  10080. #include <cube_uv_reflection_fragment>
  10081. vec3 getSample( float theta, vec3 axis ) {
  10082. float cosTheta = cos( theta );
  10083. // Rodrigues' axis-angle rotation
  10084. vec3 sampleDirection = vOutputDirection * cosTheta
  10085. + cross( axis, vOutputDirection ) * sin( theta )
  10086. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10087. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10088. }
  10089. void main() {
  10090. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10091. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10092. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10093. }
  10094. axis = normalize( axis );
  10095. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10096. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10097. for ( int i = 1; i < n; i++ ) {
  10098. if ( i >= samples ) {
  10099. break;
  10100. }
  10101. float theta = dTheta * float( i );
  10102. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10103. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10104. }
  10105. }
  10106. `,
  10107. blending: NoBlending,
  10108. depthTest: false,
  10109. depthWrite: false
  10110. } );
  10111. return shaderMaterial;
  10112. }
  10113. function _getEquirectMaterial() {
  10114. return new ShaderMaterial( {
  10115. name: 'EquirectangularToCubeUV',
  10116. uniforms: {
  10117. 'envMap': { value: null }
  10118. },
  10119. vertexShader: _getCommonVertexShader(),
  10120. fragmentShader: /* glsl */`
  10121. precision mediump float;
  10122. precision mediump int;
  10123. varying vec3 vOutputDirection;
  10124. uniform sampler2D envMap;
  10125. #include <common>
  10126. void main() {
  10127. vec3 outputDirection = normalize( vOutputDirection );
  10128. vec2 uv = equirectUv( outputDirection );
  10129. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10130. }
  10131. `,
  10132. blending: NoBlending,
  10133. depthTest: false,
  10134. depthWrite: false
  10135. } );
  10136. }
  10137. function _getCubemapMaterial() {
  10138. return new ShaderMaterial( {
  10139. name: 'CubemapToCubeUV',
  10140. uniforms: {
  10141. 'envMap': { value: null },
  10142. 'flipEnvMap': { value: - 1 }
  10143. },
  10144. vertexShader: _getCommonVertexShader(),
  10145. fragmentShader: /* glsl */`
  10146. precision mediump float;
  10147. precision mediump int;
  10148. uniform float flipEnvMap;
  10149. varying vec3 vOutputDirection;
  10150. uniform samplerCube envMap;
  10151. void main() {
  10152. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10153. }
  10154. `,
  10155. blending: NoBlending,
  10156. depthTest: false,
  10157. depthWrite: false
  10158. } );
  10159. }
  10160. function _getCommonVertexShader() {
  10161. return /* glsl */`
  10162. precision mediump float;
  10163. precision mediump int;
  10164. attribute float faceIndex;
  10165. varying vec3 vOutputDirection;
  10166. // RH coordinate system; PMREM face-indexing convention
  10167. vec3 getDirection( vec2 uv, float face ) {
  10168. uv = 2.0 * uv - 1.0;
  10169. vec3 direction = vec3( uv, 1.0 );
  10170. if ( face == 0.0 ) {
  10171. direction = direction.zyx; // ( 1, v, u ) pos x
  10172. } else if ( face == 1.0 ) {
  10173. direction = direction.xzy;
  10174. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10175. } else if ( face == 2.0 ) {
  10176. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10177. } else if ( face == 3.0 ) {
  10178. direction = direction.zyx;
  10179. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10180. } else if ( face == 4.0 ) {
  10181. direction = direction.xzy;
  10182. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10183. } else if ( face == 5.0 ) {
  10184. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10185. }
  10186. return direction;
  10187. }
  10188. void main() {
  10189. vOutputDirection = getDirection( uv, faceIndex );
  10190. gl_Position = vec4( position, 1.0 );
  10191. }
  10192. `;
  10193. }
  10194. function WebGLCubeUVMaps( renderer ) {
  10195. let cubeUVmaps = new WeakMap();
  10196. let pmremGenerator = null;
  10197. function get( texture ) {
  10198. if ( texture && texture.isTexture ) {
  10199. const mapping = texture.mapping;
  10200. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10201. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10202. // equirect/cube map to cubeUV conversion
  10203. if ( isEquirectMap || isCubeMap ) {
  10204. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10205. texture.needsPMREMUpdate = false;
  10206. let renderTarget = cubeUVmaps.get( texture );
  10207. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10208. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10209. cubeUVmaps.set( texture, renderTarget );
  10210. return renderTarget.texture;
  10211. } else {
  10212. if ( cubeUVmaps.has( texture ) ) {
  10213. return cubeUVmaps.get( texture ).texture;
  10214. } else {
  10215. const image = texture.image;
  10216. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10217. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10218. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10219. cubeUVmaps.set( texture, renderTarget );
  10220. texture.addEventListener( 'dispose', onTextureDispose );
  10221. return renderTarget.texture;
  10222. } else {
  10223. // image not yet ready. try the conversion next frame
  10224. return null;
  10225. }
  10226. }
  10227. }
  10228. }
  10229. }
  10230. return texture;
  10231. }
  10232. function isCubeTextureComplete( image ) {
  10233. let count = 0;
  10234. const length = 6;
  10235. for ( let i = 0; i < length; i ++ ) {
  10236. if ( image[ i ] !== undefined ) count ++;
  10237. }
  10238. return count === length;
  10239. }
  10240. function onTextureDispose( event ) {
  10241. const texture = event.target;
  10242. texture.removeEventListener( 'dispose', onTextureDispose );
  10243. const cubemapUV = cubeUVmaps.get( texture );
  10244. if ( cubemapUV !== undefined ) {
  10245. cubeUVmaps.delete( texture );
  10246. cubemapUV.dispose();
  10247. }
  10248. }
  10249. function dispose() {
  10250. cubeUVmaps = new WeakMap();
  10251. if ( pmremGenerator !== null ) {
  10252. pmremGenerator.dispose();
  10253. pmremGenerator = null;
  10254. }
  10255. }
  10256. return {
  10257. get: get,
  10258. dispose: dispose
  10259. };
  10260. }
  10261. function WebGLExtensions( gl ) {
  10262. const extensions = {};
  10263. function getExtension( name ) {
  10264. if ( extensions[ name ] !== undefined ) {
  10265. return extensions[ name ];
  10266. }
  10267. let extension;
  10268. switch ( name ) {
  10269. case 'WEBGL_depth_texture':
  10270. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10271. break;
  10272. case 'EXT_texture_filter_anisotropic':
  10273. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10274. break;
  10275. case 'WEBGL_compressed_texture_s3tc':
  10276. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10277. break;
  10278. case 'WEBGL_compressed_texture_pvrtc':
  10279. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10280. break;
  10281. default:
  10282. extension = gl.getExtension( name );
  10283. }
  10284. extensions[ name ] = extension;
  10285. return extension;
  10286. }
  10287. return {
  10288. has: function ( name ) {
  10289. return getExtension( name ) !== null;
  10290. },
  10291. init: function ( capabilities ) {
  10292. if ( capabilities.isWebGL2 ) {
  10293. getExtension( 'EXT_color_buffer_float' );
  10294. } else {
  10295. getExtension( 'WEBGL_depth_texture' );
  10296. getExtension( 'OES_texture_float' );
  10297. getExtension( 'OES_texture_half_float' );
  10298. getExtension( 'OES_texture_half_float_linear' );
  10299. getExtension( 'OES_standard_derivatives' );
  10300. getExtension( 'OES_element_index_uint' );
  10301. getExtension( 'OES_vertex_array_object' );
  10302. getExtension( 'ANGLE_instanced_arrays' );
  10303. }
  10304. getExtension( 'OES_texture_float_linear' );
  10305. getExtension( 'EXT_color_buffer_half_float' );
  10306. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10307. },
  10308. get: function ( name ) {
  10309. const extension = getExtension( name );
  10310. if ( extension === null ) {
  10311. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10312. }
  10313. return extension;
  10314. }
  10315. };
  10316. }
  10317. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10318. const geometries = {};
  10319. const wireframeAttributes = new WeakMap();
  10320. function onGeometryDispose( event ) {
  10321. const geometry = event.target;
  10322. if ( geometry.index !== null ) {
  10323. attributes.remove( geometry.index );
  10324. }
  10325. for ( const name in geometry.attributes ) {
  10326. attributes.remove( geometry.attributes[ name ] );
  10327. }
  10328. for ( const name in geometry.morphAttributes ) {
  10329. const array = geometry.morphAttributes[ name ];
  10330. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10331. attributes.remove( array[ i ] );
  10332. }
  10333. }
  10334. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10335. delete geometries[ geometry.id ];
  10336. const attribute = wireframeAttributes.get( geometry );
  10337. if ( attribute ) {
  10338. attributes.remove( attribute );
  10339. wireframeAttributes.delete( geometry );
  10340. }
  10341. bindingStates.releaseStatesOfGeometry( geometry );
  10342. if ( geometry.isInstancedBufferGeometry === true ) {
  10343. delete geometry._maxInstanceCount;
  10344. }
  10345. //
  10346. info.memory.geometries --;
  10347. }
  10348. function get( object, geometry ) {
  10349. if ( geometries[ geometry.id ] === true ) return geometry;
  10350. geometry.addEventListener( 'dispose', onGeometryDispose );
  10351. geometries[ geometry.id ] = true;
  10352. info.memory.geometries ++;
  10353. return geometry;
  10354. }
  10355. function update( geometry ) {
  10356. const geometryAttributes = geometry.attributes;
  10357. // Updating index buffer in VAO now. See WebGLBindingStates.
  10358. for ( const name in geometryAttributes ) {
  10359. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10360. }
  10361. // morph targets
  10362. const morphAttributes = geometry.morphAttributes;
  10363. for ( const name in morphAttributes ) {
  10364. const array = morphAttributes[ name ];
  10365. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10366. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10367. }
  10368. }
  10369. }
  10370. function updateWireframeAttribute( geometry ) {
  10371. const indices = [];
  10372. const geometryIndex = geometry.index;
  10373. const geometryPosition = geometry.attributes.position;
  10374. let version = 0;
  10375. if ( geometryIndex !== null ) {
  10376. const array = geometryIndex.array;
  10377. version = geometryIndex.version;
  10378. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10379. const a = array[ i + 0 ];
  10380. const b = array[ i + 1 ];
  10381. const c = array[ i + 2 ];
  10382. indices.push( a, b, b, c, c, a );
  10383. }
  10384. } else {
  10385. const array = geometryPosition.array;
  10386. version = geometryPosition.version;
  10387. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10388. const a = i + 0;
  10389. const b = i + 1;
  10390. const c = i + 2;
  10391. indices.push( a, b, b, c, c, a );
  10392. }
  10393. }
  10394. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10395. attribute.version = version;
  10396. // Updating index buffer in VAO now. See WebGLBindingStates
  10397. //
  10398. const previousAttribute = wireframeAttributes.get( geometry );
  10399. if ( previousAttribute ) attributes.remove( previousAttribute );
  10400. //
  10401. wireframeAttributes.set( geometry, attribute );
  10402. }
  10403. function getWireframeAttribute( geometry ) {
  10404. const currentAttribute = wireframeAttributes.get( geometry );
  10405. if ( currentAttribute ) {
  10406. const geometryIndex = geometry.index;
  10407. if ( geometryIndex !== null ) {
  10408. // if the attribute is obsolete, create a new one
  10409. if ( currentAttribute.version < geometryIndex.version ) {
  10410. updateWireframeAttribute( geometry );
  10411. }
  10412. }
  10413. } else {
  10414. updateWireframeAttribute( geometry );
  10415. }
  10416. return wireframeAttributes.get( geometry );
  10417. }
  10418. return {
  10419. get: get,
  10420. update: update,
  10421. getWireframeAttribute: getWireframeAttribute
  10422. };
  10423. }
  10424. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10425. const isWebGL2 = capabilities.isWebGL2;
  10426. let mode;
  10427. function setMode( value ) {
  10428. mode = value;
  10429. }
  10430. let type, bytesPerElement;
  10431. function setIndex( value ) {
  10432. type = value.type;
  10433. bytesPerElement = value.bytesPerElement;
  10434. }
  10435. function render( start, count ) {
  10436. gl.drawElements( mode, count, type, start * bytesPerElement );
  10437. info.update( count, mode, 1 );
  10438. }
  10439. function renderInstances( start, count, primcount ) {
  10440. if ( primcount === 0 ) return;
  10441. let extension, methodName;
  10442. if ( isWebGL2 ) {
  10443. extension = gl;
  10444. methodName = 'drawElementsInstanced';
  10445. } else {
  10446. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10447. methodName = 'drawElementsInstancedANGLE';
  10448. if ( extension === null ) {
  10449. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10450. return;
  10451. }
  10452. }
  10453. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10454. info.update( count, mode, primcount );
  10455. }
  10456. //
  10457. this.setMode = setMode;
  10458. this.setIndex = setIndex;
  10459. this.render = render;
  10460. this.renderInstances = renderInstances;
  10461. }
  10462. function WebGLInfo( gl ) {
  10463. const memory = {
  10464. geometries: 0,
  10465. textures: 0
  10466. };
  10467. const render = {
  10468. frame: 0,
  10469. calls: 0,
  10470. triangles: 0,
  10471. points: 0,
  10472. lines: 0
  10473. };
  10474. function update( count, mode, instanceCount ) {
  10475. render.calls ++;
  10476. switch ( mode ) {
  10477. case gl.TRIANGLES:
  10478. render.triangles += instanceCount * ( count / 3 );
  10479. break;
  10480. case gl.LINES:
  10481. render.lines += instanceCount * ( count / 2 );
  10482. break;
  10483. case gl.LINE_STRIP:
  10484. render.lines += instanceCount * ( count - 1 );
  10485. break;
  10486. case gl.LINE_LOOP:
  10487. render.lines += instanceCount * count;
  10488. break;
  10489. case gl.POINTS:
  10490. render.points += instanceCount * count;
  10491. break;
  10492. default:
  10493. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10494. break;
  10495. }
  10496. }
  10497. function reset() {
  10498. render.calls = 0;
  10499. render.triangles = 0;
  10500. render.points = 0;
  10501. render.lines = 0;
  10502. }
  10503. return {
  10504. memory: memory,
  10505. render: render,
  10506. programs: null,
  10507. autoReset: true,
  10508. reset: reset,
  10509. update: update
  10510. };
  10511. }
  10512. function numericalSort( a, b ) {
  10513. return a[ 0 ] - b[ 0 ];
  10514. }
  10515. function absNumericalSort( a, b ) {
  10516. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10517. }
  10518. function WebGLMorphtargets( gl, capabilities, textures ) {
  10519. const influencesList = {};
  10520. const morphInfluences = new Float32Array( 8 );
  10521. const morphTextures = new WeakMap();
  10522. const morph = new Vector4();
  10523. const workInfluences = [];
  10524. for ( let i = 0; i < 8; i ++ ) {
  10525. workInfluences[ i ] = [ i, 0 ];
  10526. }
  10527. function update( object, geometry, program ) {
  10528. const objectInfluences = object.morphTargetInfluences;
  10529. if ( capabilities.isWebGL2 === true ) {
  10530. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10531. // into an array of data textures. Each layer represents a single morph target.
  10532. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10533. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10534. let entry = morphTextures.get( geometry );
  10535. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10536. if ( entry !== undefined ) entry.texture.dispose();
  10537. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10538. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10539. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10540. const morphTargets = geometry.morphAttributes.position || [];
  10541. const morphNormals = geometry.morphAttributes.normal || [];
  10542. const morphColors = geometry.morphAttributes.color || [];
  10543. let vertexDataCount = 0;
  10544. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10545. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10546. if ( hasMorphColors === true ) vertexDataCount = 3;
  10547. let width = geometry.attributes.position.count * vertexDataCount;
  10548. let height = 1;
  10549. if ( width > capabilities.maxTextureSize ) {
  10550. height = Math.ceil( width / capabilities.maxTextureSize );
  10551. width = capabilities.maxTextureSize;
  10552. }
  10553. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10554. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10555. texture.type = FloatType;
  10556. texture.needsUpdate = true;
  10557. // fill buffer
  10558. const vertexDataStride = vertexDataCount * 4;
  10559. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10560. const morphTarget = morphTargets[ i ];
  10561. const morphNormal = morphNormals[ i ];
  10562. const morphColor = morphColors[ i ];
  10563. const offset = width * height * 4 * i;
  10564. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10565. const stride = j * vertexDataStride;
  10566. if ( hasMorphPosition === true ) {
  10567. morph.fromBufferAttribute( morphTarget, j );
  10568. buffer[ offset + stride + 0 ] = morph.x;
  10569. buffer[ offset + stride + 1 ] = morph.y;
  10570. buffer[ offset + stride + 2 ] = morph.z;
  10571. buffer[ offset + stride + 3 ] = 0;
  10572. }
  10573. if ( hasMorphNormals === true ) {
  10574. morph.fromBufferAttribute( morphNormal, j );
  10575. buffer[ offset + stride + 4 ] = morph.x;
  10576. buffer[ offset + stride + 5 ] = morph.y;
  10577. buffer[ offset + stride + 6 ] = morph.z;
  10578. buffer[ offset + stride + 7 ] = 0;
  10579. }
  10580. if ( hasMorphColors === true ) {
  10581. morph.fromBufferAttribute( morphColor, j );
  10582. buffer[ offset + stride + 8 ] = morph.x;
  10583. buffer[ offset + stride + 9 ] = morph.y;
  10584. buffer[ offset + stride + 10 ] = morph.z;
  10585. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10586. }
  10587. }
  10588. }
  10589. entry = {
  10590. count: morphTargetsCount,
  10591. texture: texture,
  10592. size: new Vector2( width, height )
  10593. };
  10594. morphTextures.set( geometry, entry );
  10595. function disposeTexture() {
  10596. texture.dispose();
  10597. morphTextures.delete( geometry );
  10598. geometry.removeEventListener( 'dispose', disposeTexture );
  10599. }
  10600. geometry.addEventListener( 'dispose', disposeTexture );
  10601. }
  10602. //
  10603. let morphInfluencesSum = 0;
  10604. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10605. morphInfluencesSum += objectInfluences[ i ];
  10606. }
  10607. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10608. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10609. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10610. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10611. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10612. } else {
  10613. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10614. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10615. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10616. let influences = influencesList[ geometry.id ];
  10617. if ( influences === undefined || influences.length !== length ) {
  10618. // initialise list
  10619. influences = [];
  10620. for ( let i = 0; i < length; i ++ ) {
  10621. influences[ i ] = [ i, 0 ];
  10622. }
  10623. influencesList[ geometry.id ] = influences;
  10624. }
  10625. // Collect influences
  10626. for ( let i = 0; i < length; i ++ ) {
  10627. const influence = influences[ i ];
  10628. influence[ 0 ] = i;
  10629. influence[ 1 ] = objectInfluences[ i ];
  10630. }
  10631. influences.sort( absNumericalSort );
  10632. for ( let i = 0; i < 8; i ++ ) {
  10633. if ( i < length && influences[ i ][ 1 ] ) {
  10634. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10635. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10636. } else {
  10637. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10638. workInfluences[ i ][ 1 ] = 0;
  10639. }
  10640. }
  10641. workInfluences.sort( numericalSort );
  10642. const morphTargets = geometry.morphAttributes.position;
  10643. const morphNormals = geometry.morphAttributes.normal;
  10644. let morphInfluencesSum = 0;
  10645. for ( let i = 0; i < 8; i ++ ) {
  10646. const influence = workInfluences[ i ];
  10647. const index = influence[ 0 ];
  10648. const value = influence[ 1 ];
  10649. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10650. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10651. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10652. }
  10653. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10654. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10655. }
  10656. morphInfluences[ i ] = value;
  10657. morphInfluencesSum += value;
  10658. } else {
  10659. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10660. geometry.deleteAttribute( 'morphTarget' + i );
  10661. }
  10662. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10663. geometry.deleteAttribute( 'morphNormal' + i );
  10664. }
  10665. morphInfluences[ i ] = 0;
  10666. }
  10667. }
  10668. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10669. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10670. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10671. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10672. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10673. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10674. }
  10675. }
  10676. return {
  10677. update: update
  10678. };
  10679. }
  10680. function WebGLObjects( gl, geometries, attributes, info ) {
  10681. let updateMap = new WeakMap();
  10682. function update( object ) {
  10683. const frame = info.render.frame;
  10684. const geometry = object.geometry;
  10685. const buffergeometry = geometries.get( object, geometry );
  10686. // Update once per frame
  10687. if ( updateMap.get( buffergeometry ) !== frame ) {
  10688. geometries.update( buffergeometry );
  10689. updateMap.set( buffergeometry, frame );
  10690. }
  10691. if ( object.isInstancedMesh ) {
  10692. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10693. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10694. }
  10695. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10696. if ( object.instanceColor !== null ) {
  10697. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10698. }
  10699. }
  10700. return buffergeometry;
  10701. }
  10702. function dispose() {
  10703. updateMap = new WeakMap();
  10704. }
  10705. function onInstancedMeshDispose( event ) {
  10706. const instancedMesh = event.target;
  10707. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10708. attributes.remove( instancedMesh.instanceMatrix );
  10709. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10710. }
  10711. return {
  10712. update: update,
  10713. dispose: dispose
  10714. };
  10715. }
  10716. /**
  10717. * Uniforms of a program.
  10718. * Those form a tree structure with a special top-level container for the root,
  10719. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10720. *
  10721. *
  10722. * Properties of inner nodes including the top-level container:
  10723. *
  10724. * .seq - array of nested uniforms
  10725. * .map - nested uniforms by name
  10726. *
  10727. *
  10728. * Methods of all nodes except the top-level container:
  10729. *
  10730. * .setValue( gl, value, [textures] )
  10731. *
  10732. * uploads a uniform value(s)
  10733. * the 'textures' parameter is needed for sampler uniforms
  10734. *
  10735. *
  10736. * Static methods of the top-level container (textures factorizations):
  10737. *
  10738. * .upload( gl, seq, values, textures )
  10739. *
  10740. * sets uniforms in 'seq' to 'values[id].value'
  10741. *
  10742. * .seqWithValue( seq, values ) : filteredSeq
  10743. *
  10744. * filters 'seq' entries with corresponding entry in values
  10745. *
  10746. *
  10747. * Methods of the top-level container (textures factorizations):
  10748. *
  10749. * .setValue( gl, name, value, textures )
  10750. *
  10751. * sets uniform with name 'name' to 'value'
  10752. *
  10753. * .setOptional( gl, obj, prop )
  10754. *
  10755. * like .set for an optional property of the object
  10756. *
  10757. */
  10758. const emptyTexture = /*@__PURE__*/ new Texture();
  10759. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10760. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10761. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10762. // --- Utilities ---
  10763. // Array Caches (provide typed arrays for temporary by size)
  10764. const arrayCacheF32 = [];
  10765. const arrayCacheI32 = [];
  10766. // Float32Array caches used for uploading Matrix uniforms
  10767. const mat4array = new Float32Array( 16 );
  10768. const mat3array = new Float32Array( 9 );
  10769. const mat2array = new Float32Array( 4 );
  10770. // Flattening for arrays of vectors and matrices
  10771. function flatten( array, nBlocks, blockSize ) {
  10772. const firstElem = array[ 0 ];
  10773. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10774. // unoptimized: ! isNaN( firstElem )
  10775. // see http://jacksondunstan.com/articles/983
  10776. const n = nBlocks * blockSize;
  10777. let r = arrayCacheF32[ n ];
  10778. if ( r === undefined ) {
  10779. r = new Float32Array( n );
  10780. arrayCacheF32[ n ] = r;
  10781. }
  10782. if ( nBlocks !== 0 ) {
  10783. firstElem.toArray( r, 0 );
  10784. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10785. offset += blockSize;
  10786. array[ i ].toArray( r, offset );
  10787. }
  10788. }
  10789. return r;
  10790. }
  10791. function arraysEqual( a, b ) {
  10792. if ( a.length !== b.length ) return false;
  10793. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10794. if ( a[ i ] !== b[ i ] ) return false;
  10795. }
  10796. return true;
  10797. }
  10798. function copyArray( a, b ) {
  10799. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10800. a[ i ] = b[ i ];
  10801. }
  10802. }
  10803. // Texture unit allocation
  10804. function allocTexUnits( textures, n ) {
  10805. let r = arrayCacheI32[ n ];
  10806. if ( r === undefined ) {
  10807. r = new Int32Array( n );
  10808. arrayCacheI32[ n ] = r;
  10809. }
  10810. for ( let i = 0; i !== n; ++ i ) {
  10811. r[ i ] = textures.allocateTextureUnit();
  10812. }
  10813. return r;
  10814. }
  10815. // --- Setters ---
  10816. // Note: Defining these methods externally, because they come in a bunch
  10817. // and this way their names minify.
  10818. // Single scalar
  10819. function setValueV1f( gl, v ) {
  10820. const cache = this.cache;
  10821. if ( cache[ 0 ] === v ) return;
  10822. gl.uniform1f( this.addr, v );
  10823. cache[ 0 ] = v;
  10824. }
  10825. // Single float vector (from flat array or THREE.VectorN)
  10826. function setValueV2f( gl, v ) {
  10827. const cache = this.cache;
  10828. if ( v.x !== undefined ) {
  10829. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10830. gl.uniform2f( this.addr, v.x, v.y );
  10831. cache[ 0 ] = v.x;
  10832. cache[ 1 ] = v.y;
  10833. }
  10834. } else {
  10835. if ( arraysEqual( cache, v ) ) return;
  10836. gl.uniform2fv( this.addr, v );
  10837. copyArray( cache, v );
  10838. }
  10839. }
  10840. function setValueV3f( gl, v ) {
  10841. const cache = this.cache;
  10842. if ( v.x !== undefined ) {
  10843. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10844. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10845. cache[ 0 ] = v.x;
  10846. cache[ 1 ] = v.y;
  10847. cache[ 2 ] = v.z;
  10848. }
  10849. } else if ( v.r !== undefined ) {
  10850. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10851. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10852. cache[ 0 ] = v.r;
  10853. cache[ 1 ] = v.g;
  10854. cache[ 2 ] = v.b;
  10855. }
  10856. } else {
  10857. if ( arraysEqual( cache, v ) ) return;
  10858. gl.uniform3fv( this.addr, v );
  10859. copyArray( cache, v );
  10860. }
  10861. }
  10862. function setValueV4f( gl, v ) {
  10863. const cache = this.cache;
  10864. if ( v.x !== undefined ) {
  10865. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10866. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10867. cache[ 0 ] = v.x;
  10868. cache[ 1 ] = v.y;
  10869. cache[ 2 ] = v.z;
  10870. cache[ 3 ] = v.w;
  10871. }
  10872. } else {
  10873. if ( arraysEqual( cache, v ) ) return;
  10874. gl.uniform4fv( this.addr, v );
  10875. copyArray( cache, v );
  10876. }
  10877. }
  10878. // Single matrix (from flat array or THREE.MatrixN)
  10879. function setValueM2( gl, v ) {
  10880. const cache = this.cache;
  10881. const elements = v.elements;
  10882. if ( elements === undefined ) {
  10883. if ( arraysEqual( cache, v ) ) return;
  10884. gl.uniformMatrix2fv( this.addr, false, v );
  10885. copyArray( cache, v );
  10886. } else {
  10887. if ( arraysEqual( cache, elements ) ) return;
  10888. mat2array.set( elements );
  10889. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10890. copyArray( cache, elements );
  10891. }
  10892. }
  10893. function setValueM3( gl, v ) {
  10894. const cache = this.cache;
  10895. const elements = v.elements;
  10896. if ( elements === undefined ) {
  10897. if ( arraysEqual( cache, v ) ) return;
  10898. gl.uniformMatrix3fv( this.addr, false, v );
  10899. copyArray( cache, v );
  10900. } else {
  10901. if ( arraysEqual( cache, elements ) ) return;
  10902. mat3array.set( elements );
  10903. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10904. copyArray( cache, elements );
  10905. }
  10906. }
  10907. function setValueM4( gl, v ) {
  10908. const cache = this.cache;
  10909. const elements = v.elements;
  10910. if ( elements === undefined ) {
  10911. if ( arraysEqual( cache, v ) ) return;
  10912. gl.uniformMatrix4fv( this.addr, false, v );
  10913. copyArray( cache, v );
  10914. } else {
  10915. if ( arraysEqual( cache, elements ) ) return;
  10916. mat4array.set( elements );
  10917. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10918. copyArray( cache, elements );
  10919. }
  10920. }
  10921. // Single integer / boolean
  10922. function setValueV1i( gl, v ) {
  10923. const cache = this.cache;
  10924. if ( cache[ 0 ] === v ) return;
  10925. gl.uniform1i( this.addr, v );
  10926. cache[ 0 ] = v;
  10927. }
  10928. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10929. function setValueV2i( gl, v ) {
  10930. const cache = this.cache;
  10931. if ( v.x !== undefined ) {
  10932. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10933. gl.uniform2i( this.addr, v.x, v.y );
  10934. cache[ 0 ] = v.x;
  10935. cache[ 1 ] = v.y;
  10936. }
  10937. } else {
  10938. if ( arraysEqual( cache, v ) ) return;
  10939. gl.uniform2iv( this.addr, v );
  10940. copyArray( cache, v );
  10941. }
  10942. }
  10943. function setValueV3i( gl, v ) {
  10944. const cache = this.cache;
  10945. if ( v.x !== undefined ) {
  10946. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10947. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10948. cache[ 0 ] = v.x;
  10949. cache[ 1 ] = v.y;
  10950. cache[ 2 ] = v.z;
  10951. }
  10952. } else {
  10953. if ( arraysEqual( cache, v ) ) return;
  10954. gl.uniform3iv( this.addr, v );
  10955. copyArray( cache, v );
  10956. }
  10957. }
  10958. function setValueV4i( gl, v ) {
  10959. const cache = this.cache;
  10960. if ( v.x !== undefined ) {
  10961. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10962. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10963. cache[ 0 ] = v.x;
  10964. cache[ 1 ] = v.y;
  10965. cache[ 2 ] = v.z;
  10966. cache[ 3 ] = v.w;
  10967. }
  10968. } else {
  10969. if ( arraysEqual( cache, v ) ) return;
  10970. gl.uniform4iv( this.addr, v );
  10971. copyArray( cache, v );
  10972. }
  10973. }
  10974. // Single unsigned integer
  10975. function setValueV1ui( gl, v ) {
  10976. const cache = this.cache;
  10977. if ( cache[ 0 ] === v ) return;
  10978. gl.uniform1ui( this.addr, v );
  10979. cache[ 0 ] = v;
  10980. }
  10981. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10982. function setValueV2ui( gl, v ) {
  10983. const cache = this.cache;
  10984. if ( v.x !== undefined ) {
  10985. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10986. gl.uniform2ui( this.addr, v.x, v.y );
  10987. cache[ 0 ] = v.x;
  10988. cache[ 1 ] = v.y;
  10989. }
  10990. } else {
  10991. if ( arraysEqual( cache, v ) ) return;
  10992. gl.uniform2uiv( this.addr, v );
  10993. copyArray( cache, v );
  10994. }
  10995. }
  10996. function setValueV3ui( gl, v ) {
  10997. const cache = this.cache;
  10998. if ( v.x !== undefined ) {
  10999. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11000. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11001. cache[ 0 ] = v.x;
  11002. cache[ 1 ] = v.y;
  11003. cache[ 2 ] = v.z;
  11004. }
  11005. } else {
  11006. if ( arraysEqual( cache, v ) ) return;
  11007. gl.uniform3uiv( this.addr, v );
  11008. copyArray( cache, v );
  11009. }
  11010. }
  11011. function setValueV4ui( gl, v ) {
  11012. const cache = this.cache;
  11013. if ( v.x !== undefined ) {
  11014. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11015. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11016. cache[ 0 ] = v.x;
  11017. cache[ 1 ] = v.y;
  11018. cache[ 2 ] = v.z;
  11019. cache[ 3 ] = v.w;
  11020. }
  11021. } else {
  11022. if ( arraysEqual( cache, v ) ) return;
  11023. gl.uniform4uiv( this.addr, v );
  11024. copyArray( cache, v );
  11025. }
  11026. }
  11027. // Single texture (2D / Cube)
  11028. function setValueT1( gl, v, textures ) {
  11029. const cache = this.cache;
  11030. const unit = textures.allocateTextureUnit();
  11031. if ( cache[ 0 ] !== unit ) {
  11032. gl.uniform1i( this.addr, unit );
  11033. cache[ 0 ] = unit;
  11034. }
  11035. textures.setTexture2D( v || emptyTexture, unit );
  11036. }
  11037. function setValueT3D1( gl, v, textures ) {
  11038. const cache = this.cache;
  11039. const unit = textures.allocateTextureUnit();
  11040. if ( cache[ 0 ] !== unit ) {
  11041. gl.uniform1i( this.addr, unit );
  11042. cache[ 0 ] = unit;
  11043. }
  11044. textures.setTexture3D( v || empty3dTexture, unit );
  11045. }
  11046. function setValueT6( gl, v, textures ) {
  11047. const cache = this.cache;
  11048. const unit = textures.allocateTextureUnit();
  11049. if ( cache[ 0 ] !== unit ) {
  11050. gl.uniform1i( this.addr, unit );
  11051. cache[ 0 ] = unit;
  11052. }
  11053. textures.setTextureCube( v || emptyCubeTexture, unit );
  11054. }
  11055. function setValueT2DArray1( gl, v, textures ) {
  11056. const cache = this.cache;
  11057. const unit = textures.allocateTextureUnit();
  11058. if ( cache[ 0 ] !== unit ) {
  11059. gl.uniform1i( this.addr, unit );
  11060. cache[ 0 ] = unit;
  11061. }
  11062. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11063. }
  11064. // Helper to pick the right setter for the singular case
  11065. function getSingularSetter( type ) {
  11066. switch ( type ) {
  11067. case 0x1406: return setValueV1f; // FLOAT
  11068. case 0x8b50: return setValueV2f; // _VEC2
  11069. case 0x8b51: return setValueV3f; // _VEC3
  11070. case 0x8b52: return setValueV4f; // _VEC4
  11071. case 0x8b5a: return setValueM2; // _MAT2
  11072. case 0x8b5b: return setValueM3; // _MAT3
  11073. case 0x8b5c: return setValueM4; // _MAT4
  11074. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11075. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11076. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11077. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11078. case 0x1405: return setValueV1ui; // UINT
  11079. case 0x8dc6: return setValueV2ui; // _VEC2
  11080. case 0x8dc7: return setValueV3ui; // _VEC3
  11081. case 0x8dc8: return setValueV4ui; // _VEC4
  11082. case 0x8b5e: // SAMPLER_2D
  11083. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11084. case 0x8dca: // INT_SAMPLER_2D
  11085. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11086. case 0x8b62: // SAMPLER_2D_SHADOW
  11087. return setValueT1;
  11088. case 0x8b5f: // SAMPLER_3D
  11089. case 0x8dcb: // INT_SAMPLER_3D
  11090. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11091. return setValueT3D1;
  11092. case 0x8b60: // SAMPLER_CUBE
  11093. case 0x8dcc: // INT_SAMPLER_CUBE
  11094. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11095. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11096. return setValueT6;
  11097. case 0x8dc1: // SAMPLER_2D_ARRAY
  11098. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11099. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11100. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11101. return setValueT2DArray1;
  11102. }
  11103. }
  11104. // Array of scalars
  11105. function setValueV1fArray( gl, v ) {
  11106. gl.uniform1fv( this.addr, v );
  11107. }
  11108. // Array of vectors (from flat array or array of THREE.VectorN)
  11109. function setValueV2fArray( gl, v ) {
  11110. const data = flatten( v, this.size, 2 );
  11111. gl.uniform2fv( this.addr, data );
  11112. }
  11113. function setValueV3fArray( gl, v ) {
  11114. const data = flatten( v, this.size, 3 );
  11115. gl.uniform3fv( this.addr, data );
  11116. }
  11117. function setValueV4fArray( gl, v ) {
  11118. const data = flatten( v, this.size, 4 );
  11119. gl.uniform4fv( this.addr, data );
  11120. }
  11121. // Array of matrices (from flat array or array of THREE.MatrixN)
  11122. function setValueM2Array( gl, v ) {
  11123. const data = flatten( v, this.size, 4 );
  11124. gl.uniformMatrix2fv( this.addr, false, data );
  11125. }
  11126. function setValueM3Array( gl, v ) {
  11127. const data = flatten( v, this.size, 9 );
  11128. gl.uniformMatrix3fv( this.addr, false, data );
  11129. }
  11130. function setValueM4Array( gl, v ) {
  11131. const data = flatten( v, this.size, 16 );
  11132. gl.uniformMatrix4fv( this.addr, false, data );
  11133. }
  11134. // Array of integer / boolean
  11135. function setValueV1iArray( gl, v ) {
  11136. gl.uniform1iv( this.addr, v );
  11137. }
  11138. // Array of integer / boolean vectors (from flat array)
  11139. function setValueV2iArray( gl, v ) {
  11140. gl.uniform2iv( this.addr, v );
  11141. }
  11142. function setValueV3iArray( gl, v ) {
  11143. gl.uniform3iv( this.addr, v );
  11144. }
  11145. function setValueV4iArray( gl, v ) {
  11146. gl.uniform4iv( this.addr, v );
  11147. }
  11148. // Array of unsigned integer
  11149. function setValueV1uiArray( gl, v ) {
  11150. gl.uniform1uiv( this.addr, v );
  11151. }
  11152. // Array of unsigned integer vectors (from flat array)
  11153. function setValueV2uiArray( gl, v ) {
  11154. gl.uniform2uiv( this.addr, v );
  11155. }
  11156. function setValueV3uiArray( gl, v ) {
  11157. gl.uniform3uiv( this.addr, v );
  11158. }
  11159. function setValueV4uiArray( gl, v ) {
  11160. gl.uniform4uiv( this.addr, v );
  11161. }
  11162. // Array of textures (2D / 3D / Cube / 2DArray)
  11163. function setValueT1Array( gl, v, textures ) {
  11164. const cache = this.cache;
  11165. const n = v.length;
  11166. const units = allocTexUnits( textures, n );
  11167. if ( ! arraysEqual( cache, units ) ) {
  11168. gl.uniform1iv( this.addr, units );
  11169. copyArray( cache, units );
  11170. }
  11171. for ( let i = 0; i !== n; ++ i ) {
  11172. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11173. }
  11174. }
  11175. function setValueT3DArray( gl, v, textures ) {
  11176. const cache = this.cache;
  11177. const n = v.length;
  11178. const units = allocTexUnits( textures, n );
  11179. if ( ! arraysEqual( cache, units ) ) {
  11180. gl.uniform1iv( this.addr, units );
  11181. copyArray( cache, units );
  11182. }
  11183. for ( let i = 0; i !== n; ++ i ) {
  11184. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11185. }
  11186. }
  11187. function setValueT6Array( gl, v, textures ) {
  11188. const cache = this.cache;
  11189. const n = v.length;
  11190. const units = allocTexUnits( textures, n );
  11191. if ( ! arraysEqual( cache, units ) ) {
  11192. gl.uniform1iv( this.addr, units );
  11193. copyArray( cache, units );
  11194. }
  11195. for ( let i = 0; i !== n; ++ i ) {
  11196. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11197. }
  11198. }
  11199. function setValueT2DArrayArray( gl, v, textures ) {
  11200. const cache = this.cache;
  11201. const n = v.length;
  11202. const units = allocTexUnits( textures, n );
  11203. if ( ! arraysEqual( cache, units ) ) {
  11204. gl.uniform1iv( this.addr, units );
  11205. copyArray( cache, units );
  11206. }
  11207. for ( let i = 0; i !== n; ++ i ) {
  11208. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11209. }
  11210. }
  11211. // Helper to pick the right setter for a pure (bottom-level) array
  11212. function getPureArraySetter( type ) {
  11213. switch ( type ) {
  11214. case 0x1406: return setValueV1fArray; // FLOAT
  11215. case 0x8b50: return setValueV2fArray; // _VEC2
  11216. case 0x8b51: return setValueV3fArray; // _VEC3
  11217. case 0x8b52: return setValueV4fArray; // _VEC4
  11218. case 0x8b5a: return setValueM2Array; // _MAT2
  11219. case 0x8b5b: return setValueM3Array; // _MAT3
  11220. case 0x8b5c: return setValueM4Array; // _MAT4
  11221. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11222. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11223. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11224. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11225. case 0x1405: return setValueV1uiArray; // UINT
  11226. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11227. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11228. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11229. case 0x8b5e: // SAMPLER_2D
  11230. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11231. case 0x8dca: // INT_SAMPLER_2D
  11232. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11233. case 0x8b62: // SAMPLER_2D_SHADOW
  11234. return setValueT1Array;
  11235. case 0x8b5f: // SAMPLER_3D
  11236. case 0x8dcb: // INT_SAMPLER_3D
  11237. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11238. return setValueT3DArray;
  11239. case 0x8b60: // SAMPLER_CUBE
  11240. case 0x8dcc: // INT_SAMPLER_CUBE
  11241. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11242. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11243. return setValueT6Array;
  11244. case 0x8dc1: // SAMPLER_2D_ARRAY
  11245. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11246. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11247. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11248. return setValueT2DArrayArray;
  11249. }
  11250. }
  11251. // --- Uniform Classes ---
  11252. class SingleUniform {
  11253. constructor( id, activeInfo, addr ) {
  11254. this.id = id;
  11255. this.addr = addr;
  11256. this.cache = [];
  11257. this.setValue = getSingularSetter( activeInfo.type );
  11258. // this.path = activeInfo.name; // DEBUG
  11259. }
  11260. }
  11261. class PureArrayUniform {
  11262. constructor( id, activeInfo, addr ) {
  11263. this.id = id;
  11264. this.addr = addr;
  11265. this.cache = [];
  11266. this.size = activeInfo.size;
  11267. this.setValue = getPureArraySetter( activeInfo.type );
  11268. // this.path = activeInfo.name; // DEBUG
  11269. }
  11270. }
  11271. class StructuredUniform {
  11272. constructor( id ) {
  11273. this.id = id;
  11274. this.seq = [];
  11275. this.map = {};
  11276. }
  11277. setValue( gl, value, textures ) {
  11278. const seq = this.seq;
  11279. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11280. const u = seq[ i ];
  11281. u.setValue( gl, value[ u.id ], textures );
  11282. }
  11283. }
  11284. }
  11285. // --- Top-level ---
  11286. // Parser - builds up the property tree from the path strings
  11287. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11288. // extracts
  11289. // - the identifier (member name or array index)
  11290. // - followed by an optional right bracket (found when array index)
  11291. // - followed by an optional left bracket or dot (type of subscript)
  11292. //
  11293. // Note: These portions can be read in a non-overlapping fashion and
  11294. // allow straightforward parsing of the hierarchy that WebGL encodes
  11295. // in the uniform names.
  11296. function addUniform( container, uniformObject ) {
  11297. container.seq.push( uniformObject );
  11298. container.map[ uniformObject.id ] = uniformObject;
  11299. }
  11300. function parseUniform( activeInfo, addr, container ) {
  11301. const path = activeInfo.name,
  11302. pathLength = path.length;
  11303. // reset RegExp object, because of the early exit of a previous run
  11304. RePathPart.lastIndex = 0;
  11305. while ( true ) {
  11306. const match = RePathPart.exec( path ),
  11307. matchEnd = RePathPart.lastIndex;
  11308. let id = match[ 1 ];
  11309. const idIsIndex = match[ 2 ] === ']',
  11310. subscript = match[ 3 ];
  11311. if ( idIsIndex ) id = id | 0; // convert to integer
  11312. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11313. // bare name or "pure" bottom-level array "[0]" suffix
  11314. addUniform( container, subscript === undefined ?
  11315. new SingleUniform( id, activeInfo, addr ) :
  11316. new PureArrayUniform( id, activeInfo, addr ) );
  11317. break;
  11318. } else {
  11319. // step into inner node / create it in case it doesn't exist
  11320. const map = container.map;
  11321. let next = map[ id ];
  11322. if ( next === undefined ) {
  11323. next = new StructuredUniform( id );
  11324. addUniform( container, next );
  11325. }
  11326. container = next;
  11327. }
  11328. }
  11329. }
  11330. // Root Container
  11331. class WebGLUniforms {
  11332. constructor( gl, program ) {
  11333. this.seq = [];
  11334. this.map = {};
  11335. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11336. for ( let i = 0; i < n; ++ i ) {
  11337. const info = gl.getActiveUniform( program, i ),
  11338. addr = gl.getUniformLocation( program, info.name );
  11339. parseUniform( info, addr, this );
  11340. }
  11341. }
  11342. setValue( gl, name, value, textures ) {
  11343. const u = this.map[ name ];
  11344. if ( u !== undefined ) u.setValue( gl, value, textures );
  11345. }
  11346. setOptional( gl, object, name ) {
  11347. const v = object[ name ];
  11348. if ( v !== undefined ) this.setValue( gl, name, v );
  11349. }
  11350. static upload( gl, seq, values, textures ) {
  11351. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11352. const u = seq[ i ],
  11353. v = values[ u.id ];
  11354. if ( v.needsUpdate !== false ) {
  11355. // note: always updating when .needsUpdate is undefined
  11356. u.setValue( gl, v.value, textures );
  11357. }
  11358. }
  11359. }
  11360. static seqWithValue( seq, values ) {
  11361. const r = [];
  11362. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11363. const u = seq[ i ];
  11364. if ( u.id in values ) r.push( u );
  11365. }
  11366. return r;
  11367. }
  11368. }
  11369. function WebGLShader( gl, type, string ) {
  11370. const shader = gl.createShader( type );
  11371. gl.shaderSource( shader, string );
  11372. gl.compileShader( shader );
  11373. return shader;
  11374. }
  11375. let programIdCount = 0;
  11376. function handleSource( string, errorLine ) {
  11377. const lines = string.split( '\n' );
  11378. const lines2 = [];
  11379. const from = Math.max( errorLine - 6, 0 );
  11380. const to = Math.min( errorLine + 6, lines.length );
  11381. for ( let i = from; i < to; i ++ ) {
  11382. const line = i + 1;
  11383. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11384. }
  11385. return lines2.join( '\n' );
  11386. }
  11387. function getEncodingComponents( colorSpace ) {
  11388. switch ( colorSpace ) {
  11389. case LinearSRGBColorSpace:
  11390. return [ 'Linear', '( value )' ];
  11391. case SRGBColorSpace:
  11392. return [ 'sRGB', '( value )' ];
  11393. default:
  11394. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11395. return [ 'Linear', '( value )' ];
  11396. }
  11397. }
  11398. function getShaderErrors( gl, shader, type ) {
  11399. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11400. const errors = gl.getShaderInfoLog( shader ).trim();
  11401. if ( status && errors === '' ) return '';
  11402. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11403. if ( errorMatches ) {
  11404. // --enable-privileged-webgl-extension
  11405. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11406. const errorLine = parseInt( errorMatches[ 1 ] );
  11407. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11408. } else {
  11409. return errors;
  11410. }
  11411. }
  11412. function getTexelEncodingFunction( functionName, colorSpace ) {
  11413. const components = getEncodingComponents( colorSpace );
  11414. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11415. }
  11416. function getToneMappingFunction( functionName, toneMapping ) {
  11417. let toneMappingName;
  11418. switch ( toneMapping ) {
  11419. case LinearToneMapping:
  11420. toneMappingName = 'Linear';
  11421. break;
  11422. case ReinhardToneMapping:
  11423. toneMappingName = 'Reinhard';
  11424. break;
  11425. case CineonToneMapping:
  11426. toneMappingName = 'OptimizedCineon';
  11427. break;
  11428. case ACESFilmicToneMapping:
  11429. toneMappingName = 'ACESFilmic';
  11430. break;
  11431. case CustomToneMapping:
  11432. toneMappingName = 'Custom';
  11433. break;
  11434. default:
  11435. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11436. toneMappingName = 'Linear';
  11437. }
  11438. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11439. }
  11440. function generateExtensions( parameters ) {
  11441. const chunks = [
  11442. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11443. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11444. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11445. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11446. ];
  11447. return chunks.filter( filterEmptyLine ).join( '\n' );
  11448. }
  11449. function generateDefines( defines ) {
  11450. const chunks = [];
  11451. for ( const name in defines ) {
  11452. const value = defines[ name ];
  11453. if ( value === false ) continue;
  11454. chunks.push( '#define ' + name + ' ' + value );
  11455. }
  11456. return chunks.join( '\n' );
  11457. }
  11458. function fetchAttributeLocations( gl, program ) {
  11459. const attributes = {};
  11460. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11461. for ( let i = 0; i < n; i ++ ) {
  11462. const info = gl.getActiveAttrib( program, i );
  11463. const name = info.name;
  11464. let locationSize = 1;
  11465. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11466. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11467. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11468. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11469. attributes[ name ] = {
  11470. type: info.type,
  11471. location: gl.getAttribLocation( program, name ),
  11472. locationSize: locationSize
  11473. };
  11474. }
  11475. return attributes;
  11476. }
  11477. function filterEmptyLine( string ) {
  11478. return string !== '';
  11479. }
  11480. function replaceLightNums( string, parameters ) {
  11481. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11482. return string
  11483. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11484. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11485. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11486. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11487. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11488. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11489. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11490. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11491. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11492. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11493. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11494. }
  11495. function replaceClippingPlaneNums( string, parameters ) {
  11496. return string
  11497. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11498. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11499. }
  11500. // Resolve Includes
  11501. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11502. function resolveIncludes( string ) {
  11503. return string.replace( includePattern, includeReplacer );
  11504. }
  11505. function includeReplacer( match, include ) {
  11506. const string = ShaderChunk[ include ];
  11507. if ( string === undefined ) {
  11508. throw new Error( 'Can not resolve #include <' + include + '>' );
  11509. }
  11510. return resolveIncludes( string );
  11511. }
  11512. // Unroll Loops
  11513. 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;
  11514. function unrollLoops( string ) {
  11515. return string.replace( unrollLoopPattern, loopReplacer );
  11516. }
  11517. function loopReplacer( match, start, end, snippet ) {
  11518. let string = '';
  11519. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11520. string += snippet
  11521. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11522. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11523. }
  11524. return string;
  11525. }
  11526. //
  11527. function generatePrecision( parameters ) {
  11528. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11529. if ( parameters.precision === 'highp' ) {
  11530. precisionstring += '\n#define HIGH_PRECISION';
  11531. } else if ( parameters.precision === 'mediump' ) {
  11532. precisionstring += '\n#define MEDIUM_PRECISION';
  11533. } else if ( parameters.precision === 'lowp' ) {
  11534. precisionstring += '\n#define LOW_PRECISION';
  11535. }
  11536. return precisionstring;
  11537. }
  11538. function generateShadowMapTypeDefine( parameters ) {
  11539. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11540. if ( parameters.shadowMapType === PCFShadowMap ) {
  11541. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11542. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11543. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11544. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11545. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11546. }
  11547. return shadowMapTypeDefine;
  11548. }
  11549. function generateEnvMapTypeDefine( parameters ) {
  11550. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11551. if ( parameters.envMap ) {
  11552. switch ( parameters.envMapMode ) {
  11553. case CubeReflectionMapping:
  11554. case CubeRefractionMapping:
  11555. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11556. break;
  11557. case CubeUVReflectionMapping:
  11558. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11559. break;
  11560. }
  11561. }
  11562. return envMapTypeDefine;
  11563. }
  11564. function generateEnvMapModeDefine( parameters ) {
  11565. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11566. if ( parameters.envMap ) {
  11567. switch ( parameters.envMapMode ) {
  11568. case CubeRefractionMapping:
  11569. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11570. break;
  11571. }
  11572. }
  11573. return envMapModeDefine;
  11574. }
  11575. function generateEnvMapBlendingDefine( parameters ) {
  11576. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11577. if ( parameters.envMap ) {
  11578. switch ( parameters.combine ) {
  11579. case MultiplyOperation:
  11580. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11581. break;
  11582. case MixOperation:
  11583. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11584. break;
  11585. case AddOperation:
  11586. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11587. break;
  11588. }
  11589. }
  11590. return envMapBlendingDefine;
  11591. }
  11592. function generateCubeUVSize( parameters ) {
  11593. const imageHeight = parameters.envMapCubeUVHeight;
  11594. if ( imageHeight === null ) return null;
  11595. const maxMip = Math.log2( imageHeight ) - 2;
  11596. const texelHeight = 1.0 / imageHeight;
  11597. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11598. return { texelWidth, texelHeight, maxMip };
  11599. }
  11600. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11601. // TODO Send this event to Three.js DevTools
  11602. // console.log( 'WebGLProgram', cacheKey );
  11603. const gl = renderer.getContext();
  11604. const defines = parameters.defines;
  11605. let vertexShader = parameters.vertexShader;
  11606. let fragmentShader = parameters.fragmentShader;
  11607. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11608. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11609. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11610. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11611. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11612. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11613. const customDefines = generateDefines( defines );
  11614. const program = gl.createProgram();
  11615. let prefixVertex, prefixFragment;
  11616. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11617. if ( parameters.isRawShaderMaterial ) {
  11618. prefixVertex = [
  11619. '#define SHADER_TYPE ' + parameters.shaderType,
  11620. '#define SHADER_NAME ' + parameters.shaderName,
  11621. customDefines
  11622. ].filter( filterEmptyLine ).join( '\n' );
  11623. if ( prefixVertex.length > 0 ) {
  11624. prefixVertex += '\n';
  11625. }
  11626. prefixFragment = [
  11627. customExtensions,
  11628. '#define SHADER_TYPE ' + parameters.shaderType,
  11629. '#define SHADER_NAME ' + parameters.shaderName,
  11630. customDefines
  11631. ].filter( filterEmptyLine ).join( '\n' );
  11632. if ( prefixFragment.length > 0 ) {
  11633. prefixFragment += '\n';
  11634. }
  11635. } else {
  11636. prefixVertex = [
  11637. generatePrecision( parameters ),
  11638. '#define SHADER_TYPE ' + parameters.shaderType,
  11639. '#define SHADER_NAME ' + parameters.shaderName,
  11640. customDefines,
  11641. parameters.instancing ? '#define USE_INSTANCING' : '',
  11642. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11643. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11644. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11645. parameters.map ? '#define USE_MAP' : '',
  11646. parameters.envMap ? '#define USE_ENVMAP' : '',
  11647. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11648. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11649. parameters.aoMap ? '#define USE_AOMAP' : '',
  11650. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11651. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11652. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11653. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11654. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11655. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11656. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11657. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11658. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11659. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11660. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11661. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11662. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11663. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11664. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11665. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11666. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11667. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11668. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11669. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11670. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11671. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11672. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11673. //
  11674. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11675. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11676. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11677. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11678. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11679. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11680. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11681. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11682. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11683. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11684. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11685. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11686. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11687. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11688. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11689. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11690. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11691. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11692. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11693. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11694. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11695. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11696. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11697. //
  11698. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11699. parameters.vertexColors ? '#define USE_COLOR' : '',
  11700. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11701. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11702. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11703. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11704. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11705. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11706. parameters.skinning ? '#define USE_SKINNING' : '',
  11707. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11708. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11709. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11710. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11711. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11712. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11713. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11714. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11715. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11716. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11717. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11718. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11719. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11720. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11721. 'uniform mat4 modelMatrix;',
  11722. 'uniform mat4 modelViewMatrix;',
  11723. 'uniform mat4 projectionMatrix;',
  11724. 'uniform mat4 viewMatrix;',
  11725. 'uniform mat3 normalMatrix;',
  11726. 'uniform vec3 cameraPosition;',
  11727. 'uniform bool isOrthographic;',
  11728. '#ifdef USE_INSTANCING',
  11729. ' attribute mat4 instanceMatrix;',
  11730. '#endif',
  11731. '#ifdef USE_INSTANCING_COLOR',
  11732. ' attribute vec3 instanceColor;',
  11733. '#endif',
  11734. 'attribute vec3 position;',
  11735. 'attribute vec3 normal;',
  11736. 'attribute vec2 uv;',
  11737. '#ifdef USE_UV1',
  11738. ' attribute vec2 uv1;',
  11739. '#endif',
  11740. '#ifdef USE_UV2',
  11741. ' attribute vec2 uv2;',
  11742. '#endif',
  11743. '#ifdef USE_UV3',
  11744. ' attribute vec2 uv3;',
  11745. '#endif',
  11746. '#ifdef USE_TANGENT',
  11747. ' attribute vec4 tangent;',
  11748. '#endif',
  11749. '#if defined( USE_COLOR_ALPHA )',
  11750. ' attribute vec4 color;',
  11751. '#elif defined( USE_COLOR )',
  11752. ' attribute vec3 color;',
  11753. '#endif',
  11754. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11755. ' attribute vec3 morphTarget0;',
  11756. ' attribute vec3 morphTarget1;',
  11757. ' attribute vec3 morphTarget2;',
  11758. ' attribute vec3 morphTarget3;',
  11759. ' #ifdef USE_MORPHNORMALS',
  11760. ' attribute vec3 morphNormal0;',
  11761. ' attribute vec3 morphNormal1;',
  11762. ' attribute vec3 morphNormal2;',
  11763. ' attribute vec3 morphNormal3;',
  11764. ' #else',
  11765. ' attribute vec3 morphTarget4;',
  11766. ' attribute vec3 morphTarget5;',
  11767. ' attribute vec3 morphTarget6;',
  11768. ' attribute vec3 morphTarget7;',
  11769. ' #endif',
  11770. '#endif',
  11771. '#ifdef USE_SKINNING',
  11772. ' attribute vec4 skinIndex;',
  11773. ' attribute vec4 skinWeight;',
  11774. '#endif',
  11775. '\n'
  11776. ].filter( filterEmptyLine ).join( '\n' );
  11777. prefixFragment = [
  11778. customExtensions,
  11779. generatePrecision( parameters ),
  11780. '#define SHADER_TYPE ' + parameters.shaderType,
  11781. '#define SHADER_NAME ' + parameters.shaderName,
  11782. customDefines,
  11783. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11784. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11785. parameters.map ? '#define USE_MAP' : '',
  11786. parameters.matcap ? '#define USE_MATCAP' : '',
  11787. parameters.envMap ? '#define USE_ENVMAP' : '',
  11788. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11789. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11790. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11791. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11792. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11793. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11794. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11795. parameters.aoMap ? '#define USE_AOMAP' : '',
  11796. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11797. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11798. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11799. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11800. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11801. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11802. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11803. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11804. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11805. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11806. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11807. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11808. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11809. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11810. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11811. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11812. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11813. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11814. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11815. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11816. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11817. parameters.sheen ? '#define USE_SHEEN' : '',
  11818. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11819. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11820. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11821. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11822. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11823. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11824. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11825. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11826. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11827. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11828. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11829. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11830. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11831. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11832. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11833. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11834. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11835. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11836. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11837. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11838. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11839. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11840. 'uniform mat4 viewMatrix;',
  11841. 'uniform vec3 cameraPosition;',
  11842. 'uniform bool isOrthographic;',
  11843. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11844. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11845. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11846. parameters.dithering ? '#define DITHERING' : '',
  11847. parameters.opaque ? '#define OPAQUE' : '',
  11848. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11849. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  11850. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11851. '\n'
  11852. ].filter( filterEmptyLine ).join( '\n' );
  11853. }
  11854. vertexShader = resolveIncludes( vertexShader );
  11855. vertexShader = replaceLightNums( vertexShader, parameters );
  11856. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11857. fragmentShader = resolveIncludes( fragmentShader );
  11858. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11859. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11860. vertexShader = unrollLoops( vertexShader );
  11861. fragmentShader = unrollLoops( fragmentShader );
  11862. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11863. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11864. versionString = '#version 300 es\n';
  11865. prefixVertex = [
  11866. 'precision mediump sampler2DArray;',
  11867. '#define attribute in',
  11868. '#define varying out',
  11869. '#define texture2D texture'
  11870. ].join( '\n' ) + '\n' + prefixVertex;
  11871. prefixFragment = [
  11872. '#define varying in',
  11873. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11874. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11875. '#define gl_FragDepthEXT gl_FragDepth',
  11876. '#define texture2D texture',
  11877. '#define textureCube texture',
  11878. '#define texture2DProj textureProj',
  11879. '#define texture2DLodEXT textureLod',
  11880. '#define texture2DProjLodEXT textureProjLod',
  11881. '#define textureCubeLodEXT textureLod',
  11882. '#define texture2DGradEXT textureGrad',
  11883. '#define texture2DProjGradEXT textureProjGrad',
  11884. '#define textureCubeGradEXT textureGrad'
  11885. ].join( '\n' ) + '\n' + prefixFragment;
  11886. }
  11887. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11888. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11889. // console.log( '*VERTEX*', vertexGlsl );
  11890. // console.log( '*FRAGMENT*', fragmentGlsl );
  11891. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11892. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11893. gl.attachShader( program, glVertexShader );
  11894. gl.attachShader( program, glFragmentShader );
  11895. // Force a particular attribute to index 0.
  11896. if ( parameters.index0AttributeName !== undefined ) {
  11897. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11898. } else if ( parameters.morphTargets === true ) {
  11899. // programs with morphTargets displace position out of attribute 0
  11900. gl.bindAttribLocation( program, 0, 'position' );
  11901. }
  11902. gl.linkProgram( program );
  11903. // check for link errors
  11904. if ( renderer.debug.checkShaderErrors ) {
  11905. const programLog = gl.getProgramInfoLog( program ).trim();
  11906. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11907. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11908. let runnable = true;
  11909. let haveDiagnostics = true;
  11910. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11911. runnable = false;
  11912. if ( typeof renderer.debug.onShaderError === 'function' ) {
  11913. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  11914. } else {
  11915. // default error reporting
  11916. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11917. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11918. console.error(
  11919. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11920. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11921. 'Program Info Log: ' + programLog + '\n' +
  11922. vertexErrors + '\n' +
  11923. fragmentErrors
  11924. );
  11925. }
  11926. } else if ( programLog !== '' ) {
  11927. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11928. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11929. haveDiagnostics = false;
  11930. }
  11931. if ( haveDiagnostics ) {
  11932. this.diagnostics = {
  11933. runnable: runnable,
  11934. programLog: programLog,
  11935. vertexShader: {
  11936. log: vertexLog,
  11937. prefix: prefixVertex
  11938. },
  11939. fragmentShader: {
  11940. log: fragmentLog,
  11941. prefix: prefixFragment
  11942. }
  11943. };
  11944. }
  11945. }
  11946. // Clean up
  11947. // Crashes in iOS9 and iOS10. #18402
  11948. // gl.detachShader( program, glVertexShader );
  11949. // gl.detachShader( program, glFragmentShader );
  11950. gl.deleteShader( glVertexShader );
  11951. gl.deleteShader( glFragmentShader );
  11952. // set up caching for uniform locations
  11953. let cachedUniforms;
  11954. this.getUniforms = function () {
  11955. if ( cachedUniforms === undefined ) {
  11956. cachedUniforms = new WebGLUniforms( gl, program );
  11957. }
  11958. return cachedUniforms;
  11959. };
  11960. // set up caching for attribute locations
  11961. let cachedAttributes;
  11962. this.getAttributes = function () {
  11963. if ( cachedAttributes === undefined ) {
  11964. cachedAttributes = fetchAttributeLocations( gl, program );
  11965. }
  11966. return cachedAttributes;
  11967. };
  11968. // free resource
  11969. this.destroy = function () {
  11970. bindingStates.releaseStatesOfProgram( this );
  11971. gl.deleteProgram( program );
  11972. this.program = undefined;
  11973. };
  11974. //
  11975. this.type = parameters.shaderType;
  11976. this.name = parameters.shaderName;
  11977. this.id = programIdCount ++;
  11978. this.cacheKey = cacheKey;
  11979. this.usedTimes = 1;
  11980. this.program = program;
  11981. this.vertexShader = glVertexShader;
  11982. this.fragmentShader = glFragmentShader;
  11983. return this;
  11984. }
  11985. let _id = 0;
  11986. class WebGLShaderCache {
  11987. constructor() {
  11988. this.shaderCache = new Map();
  11989. this.materialCache = new Map();
  11990. }
  11991. update( material ) {
  11992. const vertexShader = material.vertexShader;
  11993. const fragmentShader = material.fragmentShader;
  11994. const vertexShaderStage = this._getShaderStage( vertexShader );
  11995. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11996. const materialShaders = this._getShaderCacheForMaterial( material );
  11997. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11998. materialShaders.add( vertexShaderStage );
  11999. vertexShaderStage.usedTimes ++;
  12000. }
  12001. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12002. materialShaders.add( fragmentShaderStage );
  12003. fragmentShaderStage.usedTimes ++;
  12004. }
  12005. return this;
  12006. }
  12007. remove( material ) {
  12008. const materialShaders = this.materialCache.get( material );
  12009. for ( const shaderStage of materialShaders ) {
  12010. shaderStage.usedTimes --;
  12011. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12012. }
  12013. this.materialCache.delete( material );
  12014. return this;
  12015. }
  12016. getVertexShaderID( material ) {
  12017. return this._getShaderStage( material.vertexShader ).id;
  12018. }
  12019. getFragmentShaderID( material ) {
  12020. return this._getShaderStage( material.fragmentShader ).id;
  12021. }
  12022. dispose() {
  12023. this.shaderCache.clear();
  12024. this.materialCache.clear();
  12025. }
  12026. _getShaderCacheForMaterial( material ) {
  12027. const cache = this.materialCache;
  12028. let set = cache.get( material );
  12029. if ( set === undefined ) {
  12030. set = new Set();
  12031. cache.set( material, set );
  12032. }
  12033. return set;
  12034. }
  12035. _getShaderStage( code ) {
  12036. const cache = this.shaderCache;
  12037. let stage = cache.get( code );
  12038. if ( stage === undefined ) {
  12039. stage = new WebGLShaderStage( code );
  12040. cache.set( code, stage );
  12041. }
  12042. return stage;
  12043. }
  12044. }
  12045. class WebGLShaderStage {
  12046. constructor( code ) {
  12047. this.id = _id ++;
  12048. this.code = code;
  12049. this.usedTimes = 0;
  12050. }
  12051. }
  12052. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12053. const _programLayers = new Layers();
  12054. const _customShaders = new WebGLShaderCache();
  12055. const programs = [];
  12056. const IS_WEBGL2 = capabilities.isWebGL2;
  12057. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12058. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12059. let precision = capabilities.precision;
  12060. const shaderIDs = {
  12061. MeshDepthMaterial: 'depth',
  12062. MeshDistanceMaterial: 'distanceRGBA',
  12063. MeshNormalMaterial: 'normal',
  12064. MeshBasicMaterial: 'basic',
  12065. MeshLambertMaterial: 'lambert',
  12066. MeshPhongMaterial: 'phong',
  12067. MeshToonMaterial: 'toon',
  12068. MeshStandardMaterial: 'physical',
  12069. MeshPhysicalMaterial: 'physical',
  12070. MeshMatcapMaterial: 'matcap',
  12071. LineBasicMaterial: 'basic',
  12072. LineDashedMaterial: 'dashed',
  12073. PointsMaterial: 'points',
  12074. ShadowMaterial: 'shadow',
  12075. SpriteMaterial: 'sprite'
  12076. };
  12077. function getChannel( value ) {
  12078. if ( value === 0 ) return 'uv';
  12079. return `uv${ value }`;
  12080. }
  12081. function getParameters( material, lights, shadows, scene, object ) {
  12082. const fog = scene.fog;
  12083. const geometry = object.geometry;
  12084. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12085. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12086. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12087. const shaderID = shaderIDs[ material.type ];
  12088. // heuristics to create shader parameters according to lights in the scene
  12089. // (not to blow over maxLights budget)
  12090. if ( material.precision !== null ) {
  12091. precision = capabilities.getMaxPrecision( material.precision );
  12092. if ( precision !== material.precision ) {
  12093. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12094. }
  12095. }
  12096. //
  12097. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12098. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12099. let morphTextureStride = 0;
  12100. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12101. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12102. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12103. //
  12104. let vertexShader, fragmentShader;
  12105. let customVertexShaderID, customFragmentShaderID;
  12106. if ( shaderID ) {
  12107. const shader = ShaderLib[ shaderID ];
  12108. vertexShader = shader.vertexShader;
  12109. fragmentShader = shader.fragmentShader;
  12110. } else {
  12111. vertexShader = material.vertexShader;
  12112. fragmentShader = material.fragmentShader;
  12113. _customShaders.update( material );
  12114. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12115. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12116. }
  12117. const currentRenderTarget = renderer.getRenderTarget();
  12118. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12119. const HAS_MAP = !! material.map;
  12120. const HAS_MATCAP = !! material.matcap;
  12121. const HAS_ENVMAP = !! envMap;
  12122. const HAS_AOMAP = !! material.aoMap;
  12123. const HAS_LIGHTMAP = !! material.lightMap;
  12124. const HAS_BUMPMAP = !! material.bumpMap;
  12125. const HAS_NORMALMAP = !! material.normalMap;
  12126. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12127. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12128. const HAS_METALNESSMAP = !! material.metalnessMap;
  12129. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12130. const HAS_ANISOTROPY = material.anisotropy > 0;
  12131. const HAS_CLEARCOAT = material.clearcoat > 0;
  12132. const HAS_IRIDESCENCE = material.iridescence > 0;
  12133. const HAS_SHEEN = material.sheen > 0;
  12134. const HAS_TRANSMISSION = material.transmission > 0;
  12135. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12136. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12137. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12138. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12139. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12140. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12141. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12142. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12143. const HAS_SPECULARMAP = !! material.specularMap;
  12144. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12145. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12146. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12147. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12148. const HAS_GRADIENTMAP = !! material.gradientMap;
  12149. const HAS_ALPHAMAP = !! material.alphaMap;
  12150. const HAS_ALPHATEST = material.alphaTest > 0;
  12151. const HAS_EXTENSIONS = !! material.extensions;
  12152. const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1;
  12153. const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;
  12154. const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3;
  12155. const parameters = {
  12156. isWebGL2: IS_WEBGL2,
  12157. shaderID: shaderID,
  12158. shaderType: material.type,
  12159. shaderName: material.name,
  12160. vertexShader: vertexShader,
  12161. fragmentShader: fragmentShader,
  12162. defines: material.defines,
  12163. customVertexShaderID: customVertexShaderID,
  12164. customFragmentShaderID: customFragmentShaderID,
  12165. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12166. glslVersion: material.glslVersion,
  12167. precision: precision,
  12168. instancing: IS_INSTANCEDMESH,
  12169. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12170. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12171. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12172. map: HAS_MAP,
  12173. matcap: HAS_MATCAP,
  12174. envMap: HAS_ENVMAP,
  12175. envMapMode: HAS_ENVMAP && envMap.mapping,
  12176. envMapCubeUVHeight: envMapCubeUVHeight,
  12177. aoMap: HAS_AOMAP,
  12178. lightMap: HAS_LIGHTMAP,
  12179. bumpMap: HAS_BUMPMAP,
  12180. normalMap: HAS_NORMALMAP,
  12181. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12182. emissiveMap: HAS_EMISSIVEMAP,
  12183. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12184. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12185. metalnessMap: HAS_METALNESSMAP,
  12186. roughnessMap: HAS_ROUGHNESSMAP,
  12187. anisotropy: HAS_ANISOTROPY,
  12188. anisotropyMap: HAS_ANISOTROPYMAP,
  12189. clearcoat: HAS_CLEARCOAT,
  12190. clearcoatMap: HAS_CLEARCOATMAP,
  12191. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12192. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12193. iridescence: HAS_IRIDESCENCE,
  12194. iridescenceMap: HAS_IRIDESCENCEMAP,
  12195. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12196. sheen: HAS_SHEEN,
  12197. sheenColorMap: HAS_SHEEN_COLORMAP,
  12198. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12199. specularMap: HAS_SPECULARMAP,
  12200. specularColorMap: HAS_SPECULAR_COLORMAP,
  12201. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12202. transmission: HAS_TRANSMISSION,
  12203. transmissionMap: HAS_TRANSMISSIONMAP,
  12204. thicknessMap: HAS_THICKNESSMAP,
  12205. gradientMap: HAS_GRADIENTMAP,
  12206. opaque: material.transparent === false && material.blending === NormalBlending,
  12207. alphaMap: HAS_ALPHAMAP,
  12208. alphaTest: HAS_ALPHATEST,
  12209. combine: material.combine,
  12210. //
  12211. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12212. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12213. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12214. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12215. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12216. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12217. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12218. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12219. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12220. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12221. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12222. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12223. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12224. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12225. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12226. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12227. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12228. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12229. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12230. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12231. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12232. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12233. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12234. //
  12235. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12236. vertexColors: material.vertexColors,
  12237. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12238. vertexUv1s: HAS_ATTRIBUTE_UV1,
  12239. vertexUv2s: HAS_ATTRIBUTE_UV2,
  12240. vertexUv3s: HAS_ATTRIBUTE_UV3,
  12241. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12242. fog: !! fog,
  12243. useFog: material.fog === true,
  12244. fogExp2: ( fog && fog.isFogExp2 ),
  12245. flatShading: material.flatShading === true,
  12246. sizeAttenuation: material.sizeAttenuation === true,
  12247. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12248. skinning: object.isSkinnedMesh === true,
  12249. morphTargets: geometry.morphAttributes.position !== undefined,
  12250. morphNormals: geometry.morphAttributes.normal !== undefined,
  12251. morphColors: geometry.morphAttributes.color !== undefined,
  12252. morphTargetsCount: morphTargetsCount,
  12253. morphTextureStride: morphTextureStride,
  12254. numDirLights: lights.directional.length,
  12255. numPointLights: lights.point.length,
  12256. numSpotLights: lights.spot.length,
  12257. numSpotLightMaps: lights.spotLightMap.length,
  12258. numRectAreaLights: lights.rectArea.length,
  12259. numHemiLights: lights.hemi.length,
  12260. numDirLightShadows: lights.directionalShadowMap.length,
  12261. numPointLightShadows: lights.pointShadowMap.length,
  12262. numSpotLightShadows: lights.spotShadowMap.length,
  12263. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12264. numClippingPlanes: clipping.numPlanes,
  12265. numClipIntersection: clipping.numIntersection,
  12266. dithering: material.dithering,
  12267. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12268. shadowMapType: renderer.shadowMap.type,
  12269. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12270. useLegacyLights: renderer.useLegacyLights,
  12271. premultipliedAlpha: material.premultipliedAlpha,
  12272. doubleSided: material.side === DoubleSide,
  12273. flipSided: material.side === BackSide,
  12274. useDepthPacking: material.depthPacking >= 0,
  12275. depthPacking: material.depthPacking || 0,
  12276. index0AttributeName: material.index0AttributeName,
  12277. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12278. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12279. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12280. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12281. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12282. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12283. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12284. customProgramCacheKey: material.customProgramCacheKey()
  12285. };
  12286. return parameters;
  12287. }
  12288. function getProgramCacheKey( parameters ) {
  12289. const array = [];
  12290. if ( parameters.shaderID ) {
  12291. array.push( parameters.shaderID );
  12292. } else {
  12293. array.push( parameters.customVertexShaderID );
  12294. array.push( parameters.customFragmentShaderID );
  12295. }
  12296. if ( parameters.defines !== undefined ) {
  12297. for ( const name in parameters.defines ) {
  12298. array.push( name );
  12299. array.push( parameters.defines[ name ] );
  12300. }
  12301. }
  12302. if ( parameters.isRawShaderMaterial === false ) {
  12303. getProgramCacheKeyParameters( array, parameters );
  12304. getProgramCacheKeyBooleans( array, parameters );
  12305. array.push( renderer.outputColorSpace );
  12306. }
  12307. array.push( parameters.customProgramCacheKey );
  12308. return array.join();
  12309. }
  12310. function getProgramCacheKeyParameters( array, parameters ) {
  12311. array.push( parameters.precision );
  12312. array.push( parameters.outputColorSpace );
  12313. array.push( parameters.envMapMode );
  12314. array.push( parameters.envMapCubeUVHeight );
  12315. array.push( parameters.mapUv );
  12316. array.push( parameters.alphaMapUv );
  12317. array.push( parameters.lightMapUv );
  12318. array.push( parameters.aoMapUv );
  12319. array.push( parameters.bumpMapUv );
  12320. array.push( parameters.normalMapUv );
  12321. array.push( parameters.displacementMapUv );
  12322. array.push( parameters.emissiveMapUv );
  12323. array.push( parameters.metalnessMapUv );
  12324. array.push( parameters.roughnessMapUv );
  12325. array.push( parameters.anisotropyMapUv );
  12326. array.push( parameters.clearcoatMapUv );
  12327. array.push( parameters.clearcoatNormalMapUv );
  12328. array.push( parameters.clearcoatRoughnessMapUv );
  12329. array.push( parameters.iridescenceMapUv );
  12330. array.push( parameters.iridescenceThicknessMapUv );
  12331. array.push( parameters.sheenColorMapUv );
  12332. array.push( parameters.sheenRoughnessMapUv );
  12333. array.push( parameters.specularMapUv );
  12334. array.push( parameters.specularColorMapUv );
  12335. array.push( parameters.specularIntensityMapUv );
  12336. array.push( parameters.transmissionMapUv );
  12337. array.push( parameters.thicknessMapUv );
  12338. array.push( parameters.combine );
  12339. array.push( parameters.fogExp2 );
  12340. array.push( parameters.sizeAttenuation );
  12341. array.push( parameters.morphTargetsCount );
  12342. array.push( parameters.morphAttributeCount );
  12343. array.push( parameters.numDirLights );
  12344. array.push( parameters.numPointLights );
  12345. array.push( parameters.numSpotLights );
  12346. array.push( parameters.numSpotLightMaps );
  12347. array.push( parameters.numHemiLights );
  12348. array.push( parameters.numRectAreaLights );
  12349. array.push( parameters.numDirLightShadows );
  12350. array.push( parameters.numPointLightShadows );
  12351. array.push( parameters.numSpotLightShadows );
  12352. array.push( parameters.numSpotLightShadowsWithMaps );
  12353. array.push( parameters.shadowMapType );
  12354. array.push( parameters.toneMapping );
  12355. array.push( parameters.numClippingPlanes );
  12356. array.push( parameters.numClipIntersection );
  12357. array.push( parameters.depthPacking );
  12358. }
  12359. function getProgramCacheKeyBooleans( array, parameters ) {
  12360. _programLayers.disableAll();
  12361. if ( parameters.isWebGL2 )
  12362. _programLayers.enable( 0 );
  12363. if ( parameters.supportsVertexTextures )
  12364. _programLayers.enable( 1 );
  12365. if ( parameters.instancing )
  12366. _programLayers.enable( 2 );
  12367. if ( parameters.instancingColor )
  12368. _programLayers.enable( 3 );
  12369. if ( parameters.matcap )
  12370. _programLayers.enable( 4 );
  12371. if ( parameters.envMap )
  12372. _programLayers.enable( 5 );
  12373. if ( parameters.normalMapObjectSpace )
  12374. _programLayers.enable( 6 );
  12375. if ( parameters.normalMapTangentSpace )
  12376. _programLayers.enable( 7 );
  12377. if ( parameters.clearcoat )
  12378. _programLayers.enable( 8 );
  12379. if ( parameters.iridescence )
  12380. _programLayers.enable( 9 );
  12381. if ( parameters.alphaTest )
  12382. _programLayers.enable( 10 );
  12383. if ( parameters.vertexColors )
  12384. _programLayers.enable( 11 );
  12385. if ( parameters.vertexAlphas )
  12386. _programLayers.enable( 12 );
  12387. if ( parameters.vertexUv1s )
  12388. _programLayers.enable( 13 );
  12389. if ( parameters.vertexUv2s )
  12390. _programLayers.enable( 14 );
  12391. if ( parameters.vertexUv3s )
  12392. _programLayers.enable( 15 );
  12393. if ( parameters.vertexTangents )
  12394. _programLayers.enable( 16 );
  12395. if ( parameters.anisotropy )
  12396. _programLayers.enable( 17 );
  12397. array.push( _programLayers.mask );
  12398. _programLayers.disableAll();
  12399. if ( parameters.fog )
  12400. _programLayers.enable( 0 );
  12401. if ( parameters.useFog )
  12402. _programLayers.enable( 1 );
  12403. if ( parameters.flatShading )
  12404. _programLayers.enable( 2 );
  12405. if ( parameters.logarithmicDepthBuffer )
  12406. _programLayers.enable( 3 );
  12407. if ( parameters.skinning )
  12408. _programLayers.enable( 4 );
  12409. if ( parameters.morphTargets )
  12410. _programLayers.enable( 5 );
  12411. if ( parameters.morphNormals )
  12412. _programLayers.enable( 6 );
  12413. if ( parameters.morphColors )
  12414. _programLayers.enable( 7 );
  12415. if ( parameters.premultipliedAlpha )
  12416. _programLayers.enable( 8 );
  12417. if ( parameters.shadowMapEnabled )
  12418. _programLayers.enable( 9 );
  12419. if ( parameters.useLegacyLights )
  12420. _programLayers.enable( 10 );
  12421. if ( parameters.doubleSided )
  12422. _programLayers.enable( 11 );
  12423. if ( parameters.flipSided )
  12424. _programLayers.enable( 12 );
  12425. if ( parameters.useDepthPacking )
  12426. _programLayers.enable( 13 );
  12427. if ( parameters.dithering )
  12428. _programLayers.enable( 14 );
  12429. if ( parameters.transmission )
  12430. _programLayers.enable( 15 );
  12431. if ( parameters.sheen )
  12432. _programLayers.enable( 16 );
  12433. if ( parameters.opaque )
  12434. _programLayers.enable( 17 );
  12435. if ( parameters.pointsUvs )
  12436. _programLayers.enable( 18 );
  12437. array.push( _programLayers.mask );
  12438. }
  12439. function getUniforms( material ) {
  12440. const shaderID = shaderIDs[ material.type ];
  12441. let uniforms;
  12442. if ( shaderID ) {
  12443. const shader = ShaderLib[ shaderID ];
  12444. uniforms = UniformsUtils.clone( shader.uniforms );
  12445. } else {
  12446. uniforms = material.uniforms;
  12447. }
  12448. return uniforms;
  12449. }
  12450. function acquireProgram( parameters, cacheKey ) {
  12451. let program;
  12452. // Check if code has been already compiled
  12453. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12454. const preexistingProgram = programs[ p ];
  12455. if ( preexistingProgram.cacheKey === cacheKey ) {
  12456. program = preexistingProgram;
  12457. ++ program.usedTimes;
  12458. break;
  12459. }
  12460. }
  12461. if ( program === undefined ) {
  12462. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12463. programs.push( program );
  12464. }
  12465. return program;
  12466. }
  12467. function releaseProgram( program ) {
  12468. if ( -- program.usedTimes === 0 ) {
  12469. // Remove from unordered set
  12470. const i = programs.indexOf( program );
  12471. programs[ i ] = programs[ programs.length - 1 ];
  12472. programs.pop();
  12473. // Free WebGL resources
  12474. program.destroy();
  12475. }
  12476. }
  12477. function releaseShaderCache( material ) {
  12478. _customShaders.remove( material );
  12479. }
  12480. function dispose() {
  12481. _customShaders.dispose();
  12482. }
  12483. return {
  12484. getParameters: getParameters,
  12485. getProgramCacheKey: getProgramCacheKey,
  12486. getUniforms: getUniforms,
  12487. acquireProgram: acquireProgram,
  12488. releaseProgram: releaseProgram,
  12489. releaseShaderCache: releaseShaderCache,
  12490. // Exposed for resource monitoring & error feedback via renderer.info:
  12491. programs: programs,
  12492. dispose: dispose
  12493. };
  12494. }
  12495. function WebGLProperties() {
  12496. let properties = new WeakMap();
  12497. function get( object ) {
  12498. let map = properties.get( object );
  12499. if ( map === undefined ) {
  12500. map = {};
  12501. properties.set( object, map );
  12502. }
  12503. return map;
  12504. }
  12505. function remove( object ) {
  12506. properties.delete( object );
  12507. }
  12508. function update( object, key, value ) {
  12509. properties.get( object )[ key ] = value;
  12510. }
  12511. function dispose() {
  12512. properties = new WeakMap();
  12513. }
  12514. return {
  12515. get: get,
  12516. remove: remove,
  12517. update: update,
  12518. dispose: dispose
  12519. };
  12520. }
  12521. function painterSortStable( a, b ) {
  12522. if ( a.groupOrder !== b.groupOrder ) {
  12523. return a.groupOrder - b.groupOrder;
  12524. } else if ( a.renderOrder !== b.renderOrder ) {
  12525. return a.renderOrder - b.renderOrder;
  12526. } else if ( a.material.id !== b.material.id ) {
  12527. return a.material.id - b.material.id;
  12528. } else if ( a.z !== b.z ) {
  12529. return a.z - b.z;
  12530. } else {
  12531. return a.id - b.id;
  12532. }
  12533. }
  12534. function reversePainterSortStable( a, b ) {
  12535. if ( a.groupOrder !== b.groupOrder ) {
  12536. return a.groupOrder - b.groupOrder;
  12537. } else if ( a.renderOrder !== b.renderOrder ) {
  12538. return a.renderOrder - b.renderOrder;
  12539. } else if ( a.z !== b.z ) {
  12540. return b.z - a.z;
  12541. } else {
  12542. return a.id - b.id;
  12543. }
  12544. }
  12545. function WebGLRenderList() {
  12546. const renderItems = [];
  12547. let renderItemsIndex = 0;
  12548. const opaque = [];
  12549. const transmissive = [];
  12550. const transparent = [];
  12551. function init() {
  12552. renderItemsIndex = 0;
  12553. opaque.length = 0;
  12554. transmissive.length = 0;
  12555. transparent.length = 0;
  12556. }
  12557. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12558. let renderItem = renderItems[ renderItemsIndex ];
  12559. if ( renderItem === undefined ) {
  12560. renderItem = {
  12561. id: object.id,
  12562. object: object,
  12563. geometry: geometry,
  12564. material: material,
  12565. groupOrder: groupOrder,
  12566. renderOrder: object.renderOrder,
  12567. z: z,
  12568. group: group
  12569. };
  12570. renderItems[ renderItemsIndex ] = renderItem;
  12571. } else {
  12572. renderItem.id = object.id;
  12573. renderItem.object = object;
  12574. renderItem.geometry = geometry;
  12575. renderItem.material = material;
  12576. renderItem.groupOrder = groupOrder;
  12577. renderItem.renderOrder = object.renderOrder;
  12578. renderItem.z = z;
  12579. renderItem.group = group;
  12580. }
  12581. renderItemsIndex ++;
  12582. return renderItem;
  12583. }
  12584. function push( object, geometry, material, groupOrder, z, group ) {
  12585. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12586. if ( material.transmission > 0.0 ) {
  12587. transmissive.push( renderItem );
  12588. } else if ( material.transparent === true ) {
  12589. transparent.push( renderItem );
  12590. } else {
  12591. opaque.push( renderItem );
  12592. }
  12593. }
  12594. function unshift( object, geometry, material, groupOrder, z, group ) {
  12595. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12596. if ( material.transmission > 0.0 ) {
  12597. transmissive.unshift( renderItem );
  12598. } else if ( material.transparent === true ) {
  12599. transparent.unshift( renderItem );
  12600. } else {
  12601. opaque.unshift( renderItem );
  12602. }
  12603. }
  12604. function sort( customOpaqueSort, customTransparentSort ) {
  12605. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12606. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12607. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12608. }
  12609. function finish() {
  12610. // Clear references from inactive renderItems in the list
  12611. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12612. const renderItem = renderItems[ i ];
  12613. if ( renderItem.id === null ) break;
  12614. renderItem.id = null;
  12615. renderItem.object = null;
  12616. renderItem.geometry = null;
  12617. renderItem.material = null;
  12618. renderItem.group = null;
  12619. }
  12620. }
  12621. return {
  12622. opaque: opaque,
  12623. transmissive: transmissive,
  12624. transparent: transparent,
  12625. init: init,
  12626. push: push,
  12627. unshift: unshift,
  12628. finish: finish,
  12629. sort: sort
  12630. };
  12631. }
  12632. function WebGLRenderLists() {
  12633. let lists = new WeakMap();
  12634. function get( scene, renderCallDepth ) {
  12635. const listArray = lists.get( scene );
  12636. let list;
  12637. if ( listArray === undefined ) {
  12638. list = new WebGLRenderList();
  12639. lists.set( scene, [ list ] );
  12640. } else {
  12641. if ( renderCallDepth >= listArray.length ) {
  12642. list = new WebGLRenderList();
  12643. listArray.push( list );
  12644. } else {
  12645. list = listArray[ renderCallDepth ];
  12646. }
  12647. }
  12648. return list;
  12649. }
  12650. function dispose() {
  12651. lists = new WeakMap();
  12652. }
  12653. return {
  12654. get: get,
  12655. dispose: dispose
  12656. };
  12657. }
  12658. function UniformsCache() {
  12659. const lights = {};
  12660. return {
  12661. get: function ( light ) {
  12662. if ( lights[ light.id ] !== undefined ) {
  12663. return lights[ light.id ];
  12664. }
  12665. let uniforms;
  12666. switch ( light.type ) {
  12667. case 'DirectionalLight':
  12668. uniforms = {
  12669. direction: new Vector3(),
  12670. color: new Color()
  12671. };
  12672. break;
  12673. case 'SpotLight':
  12674. uniforms = {
  12675. position: new Vector3(),
  12676. direction: new Vector3(),
  12677. color: new Color(),
  12678. distance: 0,
  12679. coneCos: 0,
  12680. penumbraCos: 0,
  12681. decay: 0
  12682. };
  12683. break;
  12684. case 'PointLight':
  12685. uniforms = {
  12686. position: new Vector3(),
  12687. color: new Color(),
  12688. distance: 0,
  12689. decay: 0
  12690. };
  12691. break;
  12692. case 'HemisphereLight':
  12693. uniforms = {
  12694. direction: new Vector3(),
  12695. skyColor: new Color(),
  12696. groundColor: new Color()
  12697. };
  12698. break;
  12699. case 'RectAreaLight':
  12700. uniforms = {
  12701. color: new Color(),
  12702. position: new Vector3(),
  12703. halfWidth: new Vector3(),
  12704. halfHeight: new Vector3()
  12705. };
  12706. break;
  12707. }
  12708. lights[ light.id ] = uniforms;
  12709. return uniforms;
  12710. }
  12711. };
  12712. }
  12713. function ShadowUniformsCache() {
  12714. const lights = {};
  12715. return {
  12716. get: function ( light ) {
  12717. if ( lights[ light.id ] !== undefined ) {
  12718. return lights[ light.id ];
  12719. }
  12720. let uniforms;
  12721. switch ( light.type ) {
  12722. case 'DirectionalLight':
  12723. uniforms = {
  12724. shadowBias: 0,
  12725. shadowNormalBias: 0,
  12726. shadowRadius: 1,
  12727. shadowMapSize: new Vector2()
  12728. };
  12729. break;
  12730. case 'SpotLight':
  12731. uniforms = {
  12732. shadowBias: 0,
  12733. shadowNormalBias: 0,
  12734. shadowRadius: 1,
  12735. shadowMapSize: new Vector2()
  12736. };
  12737. break;
  12738. case 'PointLight':
  12739. uniforms = {
  12740. shadowBias: 0,
  12741. shadowNormalBias: 0,
  12742. shadowRadius: 1,
  12743. shadowMapSize: new Vector2(),
  12744. shadowCameraNear: 1,
  12745. shadowCameraFar: 1000
  12746. };
  12747. break;
  12748. // TODO (abelnation): set RectAreaLight shadow uniforms
  12749. }
  12750. lights[ light.id ] = uniforms;
  12751. return uniforms;
  12752. }
  12753. };
  12754. }
  12755. let nextVersion = 0;
  12756. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12757. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12758. }
  12759. function WebGLLights( extensions, capabilities ) {
  12760. const cache = new UniformsCache();
  12761. const shadowCache = ShadowUniformsCache();
  12762. const state = {
  12763. version: 0,
  12764. hash: {
  12765. directionalLength: - 1,
  12766. pointLength: - 1,
  12767. spotLength: - 1,
  12768. rectAreaLength: - 1,
  12769. hemiLength: - 1,
  12770. numDirectionalShadows: - 1,
  12771. numPointShadows: - 1,
  12772. numSpotShadows: - 1,
  12773. numSpotMaps: - 1
  12774. },
  12775. ambient: [ 0, 0, 0 ],
  12776. probe: [],
  12777. directional: [],
  12778. directionalShadow: [],
  12779. directionalShadowMap: [],
  12780. directionalShadowMatrix: [],
  12781. spot: [],
  12782. spotLightMap: [],
  12783. spotShadow: [],
  12784. spotShadowMap: [],
  12785. spotLightMatrix: [],
  12786. rectArea: [],
  12787. rectAreaLTC1: null,
  12788. rectAreaLTC2: null,
  12789. point: [],
  12790. pointShadow: [],
  12791. pointShadowMap: [],
  12792. pointShadowMatrix: [],
  12793. hemi: [],
  12794. numSpotLightShadowsWithMaps: 0
  12795. };
  12796. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12797. const vector3 = new Vector3();
  12798. const matrix4 = new Matrix4();
  12799. const matrix42 = new Matrix4();
  12800. function setup( lights, useLegacyLights ) {
  12801. let r = 0, g = 0, b = 0;
  12802. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12803. let directionalLength = 0;
  12804. let pointLength = 0;
  12805. let spotLength = 0;
  12806. let rectAreaLength = 0;
  12807. let hemiLength = 0;
  12808. let numDirectionalShadows = 0;
  12809. let numPointShadows = 0;
  12810. let numSpotShadows = 0;
  12811. let numSpotMaps = 0;
  12812. let numSpotShadowsWithMaps = 0;
  12813. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12814. lights.sort( shadowCastingAndTexturingLightsFirst );
  12815. // artist-friendly light intensity scaling factor
  12816. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12817. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12818. const light = lights[ i ];
  12819. const color = light.color;
  12820. const intensity = light.intensity;
  12821. const distance = light.distance;
  12822. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12823. if ( light.isAmbientLight ) {
  12824. r += color.r * intensity * scaleFactor;
  12825. g += color.g * intensity * scaleFactor;
  12826. b += color.b * intensity * scaleFactor;
  12827. } else if ( light.isLightProbe ) {
  12828. for ( let j = 0; j < 9; j ++ ) {
  12829. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12830. }
  12831. } else if ( light.isDirectionalLight ) {
  12832. const uniforms = cache.get( light );
  12833. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12834. if ( light.castShadow ) {
  12835. const shadow = light.shadow;
  12836. const shadowUniforms = shadowCache.get( light );
  12837. shadowUniforms.shadowBias = shadow.bias;
  12838. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12839. shadowUniforms.shadowRadius = shadow.radius;
  12840. shadowUniforms.shadowMapSize = shadow.mapSize;
  12841. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12842. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12843. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12844. numDirectionalShadows ++;
  12845. }
  12846. state.directional[ directionalLength ] = uniforms;
  12847. directionalLength ++;
  12848. } else if ( light.isSpotLight ) {
  12849. const uniforms = cache.get( light );
  12850. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12851. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12852. uniforms.distance = distance;
  12853. uniforms.coneCos = Math.cos( light.angle );
  12854. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12855. uniforms.decay = light.decay;
  12856. state.spot[ spotLength ] = uniforms;
  12857. const shadow = light.shadow;
  12858. if ( light.map ) {
  12859. state.spotLightMap[ numSpotMaps ] = light.map;
  12860. numSpotMaps ++;
  12861. // make sure the lightMatrix is up to date
  12862. // TODO : do it if required only
  12863. shadow.updateMatrices( light );
  12864. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12865. }
  12866. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12867. if ( light.castShadow ) {
  12868. const shadowUniforms = shadowCache.get( light );
  12869. shadowUniforms.shadowBias = shadow.bias;
  12870. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12871. shadowUniforms.shadowRadius = shadow.radius;
  12872. shadowUniforms.shadowMapSize = shadow.mapSize;
  12873. state.spotShadow[ spotLength ] = shadowUniforms;
  12874. state.spotShadowMap[ spotLength ] = shadowMap;
  12875. numSpotShadows ++;
  12876. }
  12877. spotLength ++;
  12878. } else if ( light.isRectAreaLight ) {
  12879. const uniforms = cache.get( light );
  12880. uniforms.color.copy( color ).multiplyScalar( intensity );
  12881. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12882. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12883. state.rectArea[ rectAreaLength ] = uniforms;
  12884. rectAreaLength ++;
  12885. } else if ( light.isPointLight ) {
  12886. const uniforms = cache.get( light );
  12887. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12888. uniforms.distance = light.distance;
  12889. uniforms.decay = light.decay;
  12890. if ( light.castShadow ) {
  12891. const shadow = light.shadow;
  12892. const shadowUniforms = shadowCache.get( light );
  12893. shadowUniforms.shadowBias = shadow.bias;
  12894. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12895. shadowUniforms.shadowRadius = shadow.radius;
  12896. shadowUniforms.shadowMapSize = shadow.mapSize;
  12897. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12898. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12899. state.pointShadow[ pointLength ] = shadowUniforms;
  12900. state.pointShadowMap[ pointLength ] = shadowMap;
  12901. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12902. numPointShadows ++;
  12903. }
  12904. state.point[ pointLength ] = uniforms;
  12905. pointLength ++;
  12906. } else if ( light.isHemisphereLight ) {
  12907. const uniforms = cache.get( light );
  12908. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12909. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12910. state.hemi[ hemiLength ] = uniforms;
  12911. hemiLength ++;
  12912. }
  12913. }
  12914. if ( rectAreaLength > 0 ) {
  12915. if ( capabilities.isWebGL2 ) {
  12916. // WebGL 2
  12917. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12918. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12919. } else {
  12920. // WebGL 1
  12921. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12922. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12923. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12924. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12925. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12926. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12927. } else {
  12928. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12929. }
  12930. }
  12931. }
  12932. state.ambient[ 0 ] = r;
  12933. state.ambient[ 1 ] = g;
  12934. state.ambient[ 2 ] = b;
  12935. const hash = state.hash;
  12936. if ( hash.directionalLength !== directionalLength ||
  12937. hash.pointLength !== pointLength ||
  12938. hash.spotLength !== spotLength ||
  12939. hash.rectAreaLength !== rectAreaLength ||
  12940. hash.hemiLength !== hemiLength ||
  12941. hash.numDirectionalShadows !== numDirectionalShadows ||
  12942. hash.numPointShadows !== numPointShadows ||
  12943. hash.numSpotShadows !== numSpotShadows ||
  12944. hash.numSpotMaps !== numSpotMaps ) {
  12945. state.directional.length = directionalLength;
  12946. state.spot.length = spotLength;
  12947. state.rectArea.length = rectAreaLength;
  12948. state.point.length = pointLength;
  12949. state.hemi.length = hemiLength;
  12950. state.directionalShadow.length = numDirectionalShadows;
  12951. state.directionalShadowMap.length = numDirectionalShadows;
  12952. state.pointShadow.length = numPointShadows;
  12953. state.pointShadowMap.length = numPointShadows;
  12954. state.spotShadow.length = numSpotShadows;
  12955. state.spotShadowMap.length = numSpotShadows;
  12956. state.directionalShadowMatrix.length = numDirectionalShadows;
  12957. state.pointShadowMatrix.length = numPointShadows;
  12958. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12959. state.spotLightMap.length = numSpotMaps;
  12960. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12961. hash.directionalLength = directionalLength;
  12962. hash.pointLength = pointLength;
  12963. hash.spotLength = spotLength;
  12964. hash.rectAreaLength = rectAreaLength;
  12965. hash.hemiLength = hemiLength;
  12966. hash.numDirectionalShadows = numDirectionalShadows;
  12967. hash.numPointShadows = numPointShadows;
  12968. hash.numSpotShadows = numSpotShadows;
  12969. hash.numSpotMaps = numSpotMaps;
  12970. state.version = nextVersion ++;
  12971. }
  12972. }
  12973. function setupView( lights, camera ) {
  12974. let directionalLength = 0;
  12975. let pointLength = 0;
  12976. let spotLength = 0;
  12977. let rectAreaLength = 0;
  12978. let hemiLength = 0;
  12979. const viewMatrix = camera.matrixWorldInverse;
  12980. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12981. const light = lights[ i ];
  12982. if ( light.isDirectionalLight ) {
  12983. const uniforms = state.directional[ directionalLength ];
  12984. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12985. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12986. uniforms.direction.sub( vector3 );
  12987. uniforms.direction.transformDirection( viewMatrix );
  12988. directionalLength ++;
  12989. } else if ( light.isSpotLight ) {
  12990. const uniforms = state.spot[ spotLength ];
  12991. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12992. uniforms.position.applyMatrix4( viewMatrix );
  12993. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12994. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12995. uniforms.direction.sub( vector3 );
  12996. uniforms.direction.transformDirection( viewMatrix );
  12997. spotLength ++;
  12998. } else if ( light.isRectAreaLight ) {
  12999. const uniforms = state.rectArea[ rectAreaLength ];
  13000. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13001. uniforms.position.applyMatrix4( viewMatrix );
  13002. // extract local rotation of light to derive width/height half vectors
  13003. matrix42.identity();
  13004. matrix4.copy( light.matrixWorld );
  13005. matrix4.premultiply( viewMatrix );
  13006. matrix42.extractRotation( matrix4 );
  13007. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13008. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13009. uniforms.halfWidth.applyMatrix4( matrix42 );
  13010. uniforms.halfHeight.applyMatrix4( matrix42 );
  13011. rectAreaLength ++;
  13012. } else if ( light.isPointLight ) {
  13013. const uniforms = state.point[ pointLength ];
  13014. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13015. uniforms.position.applyMatrix4( viewMatrix );
  13016. pointLength ++;
  13017. } else if ( light.isHemisphereLight ) {
  13018. const uniforms = state.hemi[ hemiLength ];
  13019. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13020. uniforms.direction.transformDirection( viewMatrix );
  13021. hemiLength ++;
  13022. }
  13023. }
  13024. }
  13025. return {
  13026. setup: setup,
  13027. setupView: setupView,
  13028. state: state
  13029. };
  13030. }
  13031. function WebGLRenderState( extensions, capabilities ) {
  13032. const lights = new WebGLLights( extensions, capabilities );
  13033. const lightsArray = [];
  13034. const shadowsArray = [];
  13035. function init() {
  13036. lightsArray.length = 0;
  13037. shadowsArray.length = 0;
  13038. }
  13039. function pushLight( light ) {
  13040. lightsArray.push( light );
  13041. }
  13042. function pushShadow( shadowLight ) {
  13043. shadowsArray.push( shadowLight );
  13044. }
  13045. function setupLights( useLegacyLights ) {
  13046. lights.setup( lightsArray, useLegacyLights );
  13047. }
  13048. function setupLightsView( camera ) {
  13049. lights.setupView( lightsArray, camera );
  13050. }
  13051. const state = {
  13052. lightsArray: lightsArray,
  13053. shadowsArray: shadowsArray,
  13054. lights: lights
  13055. };
  13056. return {
  13057. init: init,
  13058. state: state,
  13059. setupLights: setupLights,
  13060. setupLightsView: setupLightsView,
  13061. pushLight: pushLight,
  13062. pushShadow: pushShadow
  13063. };
  13064. }
  13065. function WebGLRenderStates( extensions, capabilities ) {
  13066. let renderStates = new WeakMap();
  13067. function get( scene, renderCallDepth = 0 ) {
  13068. const renderStateArray = renderStates.get( scene );
  13069. let renderState;
  13070. if ( renderStateArray === undefined ) {
  13071. renderState = new WebGLRenderState( extensions, capabilities );
  13072. renderStates.set( scene, [ renderState ] );
  13073. } else {
  13074. if ( renderCallDepth >= renderStateArray.length ) {
  13075. renderState = new WebGLRenderState( extensions, capabilities );
  13076. renderStateArray.push( renderState );
  13077. } else {
  13078. renderState = renderStateArray[ renderCallDepth ];
  13079. }
  13080. }
  13081. return renderState;
  13082. }
  13083. function dispose() {
  13084. renderStates = new WeakMap();
  13085. }
  13086. return {
  13087. get: get,
  13088. dispose: dispose
  13089. };
  13090. }
  13091. class MeshDepthMaterial extends Material {
  13092. constructor( parameters ) {
  13093. super();
  13094. this.isMeshDepthMaterial = true;
  13095. this.type = 'MeshDepthMaterial';
  13096. this.depthPacking = BasicDepthPacking;
  13097. this.map = null;
  13098. this.alphaMap = null;
  13099. this.displacementMap = null;
  13100. this.displacementScale = 1;
  13101. this.displacementBias = 0;
  13102. this.wireframe = false;
  13103. this.wireframeLinewidth = 1;
  13104. this.setValues( parameters );
  13105. }
  13106. copy( source ) {
  13107. super.copy( source );
  13108. this.depthPacking = source.depthPacking;
  13109. this.map = source.map;
  13110. this.alphaMap = source.alphaMap;
  13111. this.displacementMap = source.displacementMap;
  13112. this.displacementScale = source.displacementScale;
  13113. this.displacementBias = source.displacementBias;
  13114. this.wireframe = source.wireframe;
  13115. this.wireframeLinewidth = source.wireframeLinewidth;
  13116. return this;
  13117. }
  13118. }
  13119. class MeshDistanceMaterial extends Material {
  13120. constructor( parameters ) {
  13121. super();
  13122. this.isMeshDistanceMaterial = true;
  13123. this.type = 'MeshDistanceMaterial';
  13124. this.map = null;
  13125. this.alphaMap = null;
  13126. this.displacementMap = null;
  13127. this.displacementScale = 1;
  13128. this.displacementBias = 0;
  13129. this.setValues( parameters );
  13130. }
  13131. copy( source ) {
  13132. super.copy( source );
  13133. this.map = source.map;
  13134. this.alphaMap = source.alphaMap;
  13135. this.displacementMap = source.displacementMap;
  13136. this.displacementScale = source.displacementScale;
  13137. this.displacementBias = source.displacementBias;
  13138. return this;
  13139. }
  13140. }
  13141. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13142. 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}";
  13143. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13144. let _frustum = new Frustum();
  13145. const _shadowMapSize = new Vector2(),
  13146. _viewportSize = new Vector2(),
  13147. _viewport = new Vector4(),
  13148. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13149. _distanceMaterial = new MeshDistanceMaterial(),
  13150. _materialCache = {},
  13151. _maxTextureSize = _capabilities.maxTextureSize;
  13152. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13153. const shadowMaterialVertical = new ShaderMaterial( {
  13154. defines: {
  13155. VSM_SAMPLES: 8
  13156. },
  13157. uniforms: {
  13158. shadow_pass: { value: null },
  13159. resolution: { value: new Vector2() },
  13160. radius: { value: 4.0 }
  13161. },
  13162. vertexShader: vertex,
  13163. fragmentShader: fragment
  13164. } );
  13165. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13166. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13167. const fullScreenTri = new BufferGeometry();
  13168. fullScreenTri.setAttribute(
  13169. 'position',
  13170. new BufferAttribute(
  13171. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13172. 3
  13173. )
  13174. );
  13175. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13176. const scope = this;
  13177. this.enabled = false;
  13178. this.autoUpdate = true;
  13179. this.needsUpdate = false;
  13180. this.type = PCFShadowMap;
  13181. let _previousType = this.type;
  13182. this.render = function ( lights, scene, camera ) {
  13183. if ( scope.enabled === false ) return;
  13184. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13185. if ( lights.length === 0 ) return;
  13186. const currentRenderTarget = _renderer.getRenderTarget();
  13187. const activeCubeFace = _renderer.getActiveCubeFace();
  13188. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13189. const _state = _renderer.state;
  13190. // Set GL state for depth map.
  13191. _state.setBlending( NoBlending );
  13192. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13193. _state.buffers.depth.setTest( true );
  13194. _state.setScissorTest( false );
  13195. // check for shadow map type changes
  13196. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13197. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13198. // render depth map
  13199. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13200. const light = lights[ i ];
  13201. const shadow = light.shadow;
  13202. if ( shadow === undefined ) {
  13203. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13204. continue;
  13205. }
  13206. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13207. _shadowMapSize.copy( shadow.mapSize );
  13208. const shadowFrameExtents = shadow.getFrameExtents();
  13209. _shadowMapSize.multiply( shadowFrameExtents );
  13210. _viewportSize.copy( shadow.mapSize );
  13211. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13212. if ( _shadowMapSize.x > _maxTextureSize ) {
  13213. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13214. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13215. shadow.mapSize.x = _viewportSize.x;
  13216. }
  13217. if ( _shadowMapSize.y > _maxTextureSize ) {
  13218. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13219. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13220. shadow.mapSize.y = _viewportSize.y;
  13221. }
  13222. }
  13223. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13224. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13225. if ( shadow.map !== null ) {
  13226. shadow.map.dispose();
  13227. }
  13228. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13229. shadow.map.texture.name = light.name + '.shadowMap';
  13230. shadow.camera.updateProjectionMatrix();
  13231. }
  13232. _renderer.setRenderTarget( shadow.map );
  13233. _renderer.clear();
  13234. const viewportCount = shadow.getViewportCount();
  13235. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13236. const viewport = shadow.getViewport( vp );
  13237. _viewport.set(
  13238. _viewportSize.x * viewport.x,
  13239. _viewportSize.y * viewport.y,
  13240. _viewportSize.x * viewport.z,
  13241. _viewportSize.y * viewport.w
  13242. );
  13243. _state.viewport( _viewport );
  13244. shadow.updateMatrices( light, vp );
  13245. _frustum = shadow.getFrustum();
  13246. renderObject( scene, camera, shadow.camera, light, this.type );
  13247. }
  13248. // do blur pass for VSM
  13249. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13250. VSMPass( shadow, camera );
  13251. }
  13252. shadow.needsUpdate = false;
  13253. }
  13254. _previousType = this.type;
  13255. scope.needsUpdate = false;
  13256. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13257. };
  13258. function VSMPass( shadow, camera ) {
  13259. const geometry = _objects.update( fullScreenMesh );
  13260. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13261. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13262. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13263. shadowMaterialVertical.needsUpdate = true;
  13264. shadowMaterialHorizontal.needsUpdate = true;
  13265. }
  13266. if ( shadow.mapPass === null ) {
  13267. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13268. }
  13269. // vertical pass
  13270. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13271. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13272. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13273. _renderer.setRenderTarget( shadow.mapPass );
  13274. _renderer.clear();
  13275. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13276. // horizontal pass
  13277. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13278. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13279. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13280. _renderer.setRenderTarget( shadow.map );
  13281. _renderer.clear();
  13282. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13283. }
  13284. function getDepthMaterial( object, material, light, type ) {
  13285. let result = null;
  13286. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13287. if ( customMaterial !== undefined ) {
  13288. result = customMaterial;
  13289. } else {
  13290. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13291. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13292. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13293. ( material.alphaMap && material.alphaTest > 0 ) ||
  13294. ( material.map && material.alphaTest > 0 ) ) {
  13295. // in this case we need a unique material instance reflecting the
  13296. // appropriate state
  13297. const keyA = result.uuid, keyB = material.uuid;
  13298. let materialsForVariant = _materialCache[ keyA ];
  13299. if ( materialsForVariant === undefined ) {
  13300. materialsForVariant = {};
  13301. _materialCache[ keyA ] = materialsForVariant;
  13302. }
  13303. let cachedMaterial = materialsForVariant[ keyB ];
  13304. if ( cachedMaterial === undefined ) {
  13305. cachedMaterial = result.clone();
  13306. materialsForVariant[ keyB ] = cachedMaterial;
  13307. }
  13308. result = cachedMaterial;
  13309. }
  13310. }
  13311. result.visible = material.visible;
  13312. result.wireframe = material.wireframe;
  13313. if ( type === VSMShadowMap ) {
  13314. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13315. } else {
  13316. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13317. }
  13318. result.alphaMap = material.alphaMap;
  13319. result.alphaTest = material.alphaTest;
  13320. result.map = material.map;
  13321. result.clipShadows = material.clipShadows;
  13322. result.clippingPlanes = material.clippingPlanes;
  13323. result.clipIntersection = material.clipIntersection;
  13324. result.displacementMap = material.displacementMap;
  13325. result.displacementScale = material.displacementScale;
  13326. result.displacementBias = material.displacementBias;
  13327. result.wireframeLinewidth = material.wireframeLinewidth;
  13328. result.linewidth = material.linewidth;
  13329. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13330. const materialProperties = _renderer.properties.get( result );
  13331. materialProperties.light = light;
  13332. }
  13333. return result;
  13334. }
  13335. function renderObject( object, camera, shadowCamera, light, type ) {
  13336. if ( object.visible === false ) return;
  13337. const visible = object.layers.test( camera.layers );
  13338. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13339. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13340. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13341. const geometry = _objects.update( object );
  13342. const material = object.material;
  13343. if ( Array.isArray( material ) ) {
  13344. const groups = geometry.groups;
  13345. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13346. const group = groups[ k ];
  13347. const groupMaterial = material[ group.materialIndex ];
  13348. if ( groupMaterial && groupMaterial.visible ) {
  13349. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13350. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13351. }
  13352. }
  13353. } else if ( material.visible ) {
  13354. const depthMaterial = getDepthMaterial( object, material, light, type );
  13355. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13356. }
  13357. }
  13358. }
  13359. const children = object.children;
  13360. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13361. renderObject( children[ i ], camera, shadowCamera, light, type );
  13362. }
  13363. }
  13364. }
  13365. function WebGLState( gl, extensions, capabilities ) {
  13366. const isWebGL2 = capabilities.isWebGL2;
  13367. function ColorBuffer() {
  13368. let locked = false;
  13369. const color = new Vector4();
  13370. let currentColorMask = null;
  13371. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13372. return {
  13373. setMask: function ( colorMask ) {
  13374. if ( currentColorMask !== colorMask && ! locked ) {
  13375. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13376. currentColorMask = colorMask;
  13377. }
  13378. },
  13379. setLocked: function ( lock ) {
  13380. locked = lock;
  13381. },
  13382. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13383. if ( premultipliedAlpha === true ) {
  13384. r *= a; g *= a; b *= a;
  13385. }
  13386. color.set( r, g, b, a );
  13387. if ( currentColorClear.equals( color ) === false ) {
  13388. gl.clearColor( r, g, b, a );
  13389. currentColorClear.copy( color );
  13390. }
  13391. },
  13392. reset: function () {
  13393. locked = false;
  13394. currentColorMask = null;
  13395. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13396. }
  13397. };
  13398. }
  13399. function DepthBuffer() {
  13400. let locked = false;
  13401. let currentDepthMask = null;
  13402. let currentDepthFunc = null;
  13403. let currentDepthClear = null;
  13404. return {
  13405. setTest: function ( depthTest ) {
  13406. if ( depthTest ) {
  13407. enable( gl.DEPTH_TEST );
  13408. } else {
  13409. disable( gl.DEPTH_TEST );
  13410. }
  13411. },
  13412. setMask: function ( depthMask ) {
  13413. if ( currentDepthMask !== depthMask && ! locked ) {
  13414. gl.depthMask( depthMask );
  13415. currentDepthMask = depthMask;
  13416. }
  13417. },
  13418. setFunc: function ( depthFunc ) {
  13419. if ( currentDepthFunc !== depthFunc ) {
  13420. switch ( depthFunc ) {
  13421. case NeverDepth:
  13422. gl.depthFunc( gl.NEVER );
  13423. break;
  13424. case AlwaysDepth:
  13425. gl.depthFunc( gl.ALWAYS );
  13426. break;
  13427. case LessDepth:
  13428. gl.depthFunc( gl.LESS );
  13429. break;
  13430. case LessEqualDepth:
  13431. gl.depthFunc( gl.LEQUAL );
  13432. break;
  13433. case EqualDepth:
  13434. gl.depthFunc( gl.EQUAL );
  13435. break;
  13436. case GreaterEqualDepth:
  13437. gl.depthFunc( gl.GEQUAL );
  13438. break;
  13439. case GreaterDepth:
  13440. gl.depthFunc( gl.GREATER );
  13441. break;
  13442. case NotEqualDepth:
  13443. gl.depthFunc( gl.NOTEQUAL );
  13444. break;
  13445. default:
  13446. gl.depthFunc( gl.LEQUAL );
  13447. }
  13448. currentDepthFunc = depthFunc;
  13449. }
  13450. },
  13451. setLocked: function ( lock ) {
  13452. locked = lock;
  13453. },
  13454. setClear: function ( depth ) {
  13455. if ( currentDepthClear !== depth ) {
  13456. gl.clearDepth( depth );
  13457. currentDepthClear = depth;
  13458. }
  13459. },
  13460. reset: function () {
  13461. locked = false;
  13462. currentDepthMask = null;
  13463. currentDepthFunc = null;
  13464. currentDepthClear = null;
  13465. }
  13466. };
  13467. }
  13468. function StencilBuffer() {
  13469. let locked = false;
  13470. let currentStencilMask = null;
  13471. let currentStencilFunc = null;
  13472. let currentStencilRef = null;
  13473. let currentStencilFuncMask = null;
  13474. let currentStencilFail = null;
  13475. let currentStencilZFail = null;
  13476. let currentStencilZPass = null;
  13477. let currentStencilClear = null;
  13478. return {
  13479. setTest: function ( stencilTest ) {
  13480. if ( ! locked ) {
  13481. if ( stencilTest ) {
  13482. enable( gl.STENCIL_TEST );
  13483. } else {
  13484. disable( gl.STENCIL_TEST );
  13485. }
  13486. }
  13487. },
  13488. setMask: function ( stencilMask ) {
  13489. if ( currentStencilMask !== stencilMask && ! locked ) {
  13490. gl.stencilMask( stencilMask );
  13491. currentStencilMask = stencilMask;
  13492. }
  13493. },
  13494. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13495. if ( currentStencilFunc !== stencilFunc ||
  13496. currentStencilRef !== stencilRef ||
  13497. currentStencilFuncMask !== stencilMask ) {
  13498. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13499. currentStencilFunc = stencilFunc;
  13500. currentStencilRef = stencilRef;
  13501. currentStencilFuncMask = stencilMask;
  13502. }
  13503. },
  13504. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13505. if ( currentStencilFail !== stencilFail ||
  13506. currentStencilZFail !== stencilZFail ||
  13507. currentStencilZPass !== stencilZPass ) {
  13508. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13509. currentStencilFail = stencilFail;
  13510. currentStencilZFail = stencilZFail;
  13511. currentStencilZPass = stencilZPass;
  13512. }
  13513. },
  13514. setLocked: function ( lock ) {
  13515. locked = lock;
  13516. },
  13517. setClear: function ( stencil ) {
  13518. if ( currentStencilClear !== stencil ) {
  13519. gl.clearStencil( stencil );
  13520. currentStencilClear = stencil;
  13521. }
  13522. },
  13523. reset: function () {
  13524. locked = false;
  13525. currentStencilMask = null;
  13526. currentStencilFunc = null;
  13527. currentStencilRef = null;
  13528. currentStencilFuncMask = null;
  13529. currentStencilFail = null;
  13530. currentStencilZFail = null;
  13531. currentStencilZPass = null;
  13532. currentStencilClear = null;
  13533. }
  13534. };
  13535. }
  13536. //
  13537. const colorBuffer = new ColorBuffer();
  13538. const depthBuffer = new DepthBuffer();
  13539. const stencilBuffer = new StencilBuffer();
  13540. const uboBindings = new WeakMap();
  13541. const uboProgramMap = new WeakMap();
  13542. let enabledCapabilities = {};
  13543. let currentBoundFramebuffers = {};
  13544. let currentDrawbuffers = new WeakMap();
  13545. let defaultDrawbuffers = [];
  13546. let currentProgram = null;
  13547. let currentBlendingEnabled = false;
  13548. let currentBlending = null;
  13549. let currentBlendEquation = null;
  13550. let currentBlendSrc = null;
  13551. let currentBlendDst = null;
  13552. let currentBlendEquationAlpha = null;
  13553. let currentBlendSrcAlpha = null;
  13554. let currentBlendDstAlpha = null;
  13555. let currentPremultipledAlpha = false;
  13556. let currentFlipSided = null;
  13557. let currentCullFace = null;
  13558. let currentLineWidth = null;
  13559. let currentPolygonOffsetFactor = null;
  13560. let currentPolygonOffsetUnits = null;
  13561. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13562. let lineWidthAvailable = false;
  13563. let version = 0;
  13564. const glVersion = gl.getParameter( gl.VERSION );
  13565. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13566. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13567. lineWidthAvailable = ( version >= 1.0 );
  13568. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13569. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13570. lineWidthAvailable = ( version >= 2.0 );
  13571. }
  13572. let currentTextureSlot = null;
  13573. let currentBoundTextures = {};
  13574. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13575. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13576. const currentScissor = new Vector4().fromArray( scissorParam );
  13577. const currentViewport = new Vector4().fromArray( viewportParam );
  13578. function createTexture( type, target, count, dimensions ) {
  13579. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13580. const texture = gl.createTexture();
  13581. gl.bindTexture( type, texture );
  13582. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13583. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13584. for ( let i = 0; i < count; i ++ ) {
  13585. if ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) {
  13586. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13587. } else {
  13588. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13589. }
  13590. }
  13591. return texture;
  13592. }
  13593. const emptyTextures = {};
  13594. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13595. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13596. if ( isWebGL2 ) {
  13597. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13598. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13599. }
  13600. // init
  13601. colorBuffer.setClear( 0, 0, 0, 1 );
  13602. depthBuffer.setClear( 1 );
  13603. stencilBuffer.setClear( 0 );
  13604. enable( gl.DEPTH_TEST );
  13605. depthBuffer.setFunc( LessEqualDepth );
  13606. setFlipSided( false );
  13607. setCullFace( CullFaceBack );
  13608. enable( gl.CULL_FACE );
  13609. setBlending( NoBlending );
  13610. //
  13611. function enable( id ) {
  13612. if ( enabledCapabilities[ id ] !== true ) {
  13613. gl.enable( id );
  13614. enabledCapabilities[ id ] = true;
  13615. }
  13616. }
  13617. function disable( id ) {
  13618. if ( enabledCapabilities[ id ] !== false ) {
  13619. gl.disable( id );
  13620. enabledCapabilities[ id ] = false;
  13621. }
  13622. }
  13623. function bindFramebuffer( target, framebuffer ) {
  13624. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13625. gl.bindFramebuffer( target, framebuffer );
  13626. currentBoundFramebuffers[ target ] = framebuffer;
  13627. if ( isWebGL2 ) {
  13628. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13629. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13630. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13631. }
  13632. if ( target === gl.FRAMEBUFFER ) {
  13633. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13634. }
  13635. }
  13636. return true;
  13637. }
  13638. return false;
  13639. }
  13640. function drawBuffers( renderTarget, framebuffer ) {
  13641. let drawBuffers = defaultDrawbuffers;
  13642. let needsUpdate = false;
  13643. if ( renderTarget ) {
  13644. drawBuffers = currentDrawbuffers.get( framebuffer );
  13645. if ( drawBuffers === undefined ) {
  13646. drawBuffers = [];
  13647. currentDrawbuffers.set( framebuffer, drawBuffers );
  13648. }
  13649. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13650. const textures = renderTarget.texture;
  13651. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13652. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13653. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13654. }
  13655. drawBuffers.length = textures.length;
  13656. needsUpdate = true;
  13657. }
  13658. } else {
  13659. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13660. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13661. needsUpdate = true;
  13662. }
  13663. }
  13664. } else {
  13665. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13666. drawBuffers[ 0 ] = gl.BACK;
  13667. needsUpdate = true;
  13668. }
  13669. }
  13670. if ( needsUpdate ) {
  13671. if ( capabilities.isWebGL2 ) {
  13672. gl.drawBuffers( drawBuffers );
  13673. } else {
  13674. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13675. }
  13676. }
  13677. }
  13678. function useProgram( program ) {
  13679. if ( currentProgram !== program ) {
  13680. gl.useProgram( program );
  13681. currentProgram = program;
  13682. return true;
  13683. }
  13684. return false;
  13685. }
  13686. const equationToGL = {
  13687. [ AddEquation ]: gl.FUNC_ADD,
  13688. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13689. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13690. };
  13691. if ( isWebGL2 ) {
  13692. equationToGL[ MinEquation ] = gl.MIN;
  13693. equationToGL[ MaxEquation ] = gl.MAX;
  13694. } else {
  13695. const extension = extensions.get( 'EXT_blend_minmax' );
  13696. if ( extension !== null ) {
  13697. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13698. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13699. }
  13700. }
  13701. const factorToGL = {
  13702. [ ZeroFactor ]: gl.ZERO,
  13703. [ OneFactor ]: gl.ONE,
  13704. [ SrcColorFactor ]: gl.SRC_COLOR,
  13705. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13706. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13707. [ DstColorFactor ]: gl.DST_COLOR,
  13708. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13709. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13710. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13711. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13712. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13713. };
  13714. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13715. if ( blending === NoBlending ) {
  13716. if ( currentBlendingEnabled === true ) {
  13717. disable( gl.BLEND );
  13718. currentBlendingEnabled = false;
  13719. }
  13720. return;
  13721. }
  13722. if ( currentBlendingEnabled === false ) {
  13723. enable( gl.BLEND );
  13724. currentBlendingEnabled = true;
  13725. }
  13726. if ( blending !== CustomBlending ) {
  13727. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13728. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13729. gl.blendEquation( gl.FUNC_ADD );
  13730. currentBlendEquation = AddEquation;
  13731. currentBlendEquationAlpha = AddEquation;
  13732. }
  13733. if ( premultipliedAlpha ) {
  13734. switch ( blending ) {
  13735. case NormalBlending:
  13736. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13737. break;
  13738. case AdditiveBlending:
  13739. gl.blendFunc( gl.ONE, gl.ONE );
  13740. break;
  13741. case SubtractiveBlending:
  13742. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13743. break;
  13744. case MultiplyBlending:
  13745. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13746. break;
  13747. default:
  13748. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13749. break;
  13750. }
  13751. } else {
  13752. switch ( blending ) {
  13753. case NormalBlending:
  13754. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13755. break;
  13756. case AdditiveBlending:
  13757. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13758. break;
  13759. case SubtractiveBlending:
  13760. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13761. break;
  13762. case MultiplyBlending:
  13763. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13764. break;
  13765. default:
  13766. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13767. break;
  13768. }
  13769. }
  13770. currentBlendSrc = null;
  13771. currentBlendDst = null;
  13772. currentBlendSrcAlpha = null;
  13773. currentBlendDstAlpha = null;
  13774. currentBlending = blending;
  13775. currentPremultipledAlpha = premultipliedAlpha;
  13776. }
  13777. return;
  13778. }
  13779. // custom blending
  13780. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13781. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13782. blendDstAlpha = blendDstAlpha || blendDst;
  13783. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13784. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13785. currentBlendEquation = blendEquation;
  13786. currentBlendEquationAlpha = blendEquationAlpha;
  13787. }
  13788. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13789. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13790. currentBlendSrc = blendSrc;
  13791. currentBlendDst = blendDst;
  13792. currentBlendSrcAlpha = blendSrcAlpha;
  13793. currentBlendDstAlpha = blendDstAlpha;
  13794. }
  13795. currentBlending = blending;
  13796. currentPremultipledAlpha = false;
  13797. }
  13798. function setMaterial( material, frontFaceCW ) {
  13799. material.side === DoubleSide
  13800. ? disable( gl.CULL_FACE )
  13801. : enable( gl.CULL_FACE );
  13802. let flipSided = ( material.side === BackSide );
  13803. if ( frontFaceCW ) flipSided = ! flipSided;
  13804. setFlipSided( flipSided );
  13805. ( material.blending === NormalBlending && material.transparent === false )
  13806. ? setBlending( NoBlending )
  13807. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13808. depthBuffer.setFunc( material.depthFunc );
  13809. depthBuffer.setTest( material.depthTest );
  13810. depthBuffer.setMask( material.depthWrite );
  13811. colorBuffer.setMask( material.colorWrite );
  13812. const stencilWrite = material.stencilWrite;
  13813. stencilBuffer.setTest( stencilWrite );
  13814. if ( stencilWrite ) {
  13815. stencilBuffer.setMask( material.stencilWriteMask );
  13816. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13817. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13818. }
  13819. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13820. material.alphaToCoverage === true
  13821. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13822. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13823. }
  13824. //
  13825. function setFlipSided( flipSided ) {
  13826. if ( currentFlipSided !== flipSided ) {
  13827. if ( flipSided ) {
  13828. gl.frontFace( gl.CW );
  13829. } else {
  13830. gl.frontFace( gl.CCW );
  13831. }
  13832. currentFlipSided = flipSided;
  13833. }
  13834. }
  13835. function setCullFace( cullFace ) {
  13836. if ( cullFace !== CullFaceNone ) {
  13837. enable( gl.CULL_FACE );
  13838. if ( cullFace !== currentCullFace ) {
  13839. if ( cullFace === CullFaceBack ) {
  13840. gl.cullFace( gl.BACK );
  13841. } else if ( cullFace === CullFaceFront ) {
  13842. gl.cullFace( gl.FRONT );
  13843. } else {
  13844. gl.cullFace( gl.FRONT_AND_BACK );
  13845. }
  13846. }
  13847. } else {
  13848. disable( gl.CULL_FACE );
  13849. }
  13850. currentCullFace = cullFace;
  13851. }
  13852. function setLineWidth( width ) {
  13853. if ( width !== currentLineWidth ) {
  13854. if ( lineWidthAvailable ) gl.lineWidth( width );
  13855. currentLineWidth = width;
  13856. }
  13857. }
  13858. function setPolygonOffset( polygonOffset, factor, units ) {
  13859. if ( polygonOffset ) {
  13860. enable( gl.POLYGON_OFFSET_FILL );
  13861. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13862. gl.polygonOffset( factor, units );
  13863. currentPolygonOffsetFactor = factor;
  13864. currentPolygonOffsetUnits = units;
  13865. }
  13866. } else {
  13867. disable( gl.POLYGON_OFFSET_FILL );
  13868. }
  13869. }
  13870. function setScissorTest( scissorTest ) {
  13871. if ( scissorTest ) {
  13872. enable( gl.SCISSOR_TEST );
  13873. } else {
  13874. disable( gl.SCISSOR_TEST );
  13875. }
  13876. }
  13877. // texture
  13878. function activeTexture( webglSlot ) {
  13879. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13880. if ( currentTextureSlot !== webglSlot ) {
  13881. gl.activeTexture( webglSlot );
  13882. currentTextureSlot = webglSlot;
  13883. }
  13884. }
  13885. function bindTexture( webglType, webglTexture, webglSlot ) {
  13886. if ( webglSlot === undefined ) {
  13887. if ( currentTextureSlot === null ) {
  13888. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13889. } else {
  13890. webglSlot = currentTextureSlot;
  13891. }
  13892. }
  13893. let boundTexture = currentBoundTextures[ webglSlot ];
  13894. if ( boundTexture === undefined ) {
  13895. boundTexture = { type: undefined, texture: undefined };
  13896. currentBoundTextures[ webglSlot ] = boundTexture;
  13897. }
  13898. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13899. if ( currentTextureSlot !== webglSlot ) {
  13900. gl.activeTexture( webglSlot );
  13901. currentTextureSlot = webglSlot;
  13902. }
  13903. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13904. boundTexture.type = webglType;
  13905. boundTexture.texture = webglTexture;
  13906. }
  13907. }
  13908. function unbindTexture() {
  13909. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13910. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13911. gl.bindTexture( boundTexture.type, null );
  13912. boundTexture.type = undefined;
  13913. boundTexture.texture = undefined;
  13914. }
  13915. }
  13916. function compressedTexImage2D() {
  13917. try {
  13918. gl.compressedTexImage2D.apply( gl, arguments );
  13919. } catch ( error ) {
  13920. console.error( 'THREE.WebGLState:', error );
  13921. }
  13922. }
  13923. function compressedTexImage3D() {
  13924. try {
  13925. gl.compressedTexImage3D.apply( gl, arguments );
  13926. } catch ( error ) {
  13927. console.error( 'THREE.WebGLState:', error );
  13928. }
  13929. }
  13930. function texSubImage2D() {
  13931. try {
  13932. gl.texSubImage2D.apply( gl, arguments );
  13933. } catch ( error ) {
  13934. console.error( 'THREE.WebGLState:', error );
  13935. }
  13936. }
  13937. function texSubImage3D() {
  13938. try {
  13939. gl.texSubImage3D.apply( gl, arguments );
  13940. } catch ( error ) {
  13941. console.error( 'THREE.WebGLState:', error );
  13942. }
  13943. }
  13944. function compressedTexSubImage2D() {
  13945. try {
  13946. gl.compressedTexSubImage2D.apply( gl, arguments );
  13947. } catch ( error ) {
  13948. console.error( 'THREE.WebGLState:', error );
  13949. }
  13950. }
  13951. function compressedTexSubImage3D() {
  13952. try {
  13953. gl.compressedTexSubImage3D.apply( gl, arguments );
  13954. } catch ( error ) {
  13955. console.error( 'THREE.WebGLState:', error );
  13956. }
  13957. }
  13958. function texStorage2D() {
  13959. try {
  13960. gl.texStorage2D.apply( gl, arguments );
  13961. } catch ( error ) {
  13962. console.error( 'THREE.WebGLState:', error );
  13963. }
  13964. }
  13965. function texStorage3D() {
  13966. try {
  13967. gl.texStorage3D.apply( gl, arguments );
  13968. } catch ( error ) {
  13969. console.error( 'THREE.WebGLState:', error );
  13970. }
  13971. }
  13972. function texImage2D() {
  13973. try {
  13974. gl.texImage2D.apply( gl, arguments );
  13975. } catch ( error ) {
  13976. console.error( 'THREE.WebGLState:', error );
  13977. }
  13978. }
  13979. function texImage3D() {
  13980. try {
  13981. gl.texImage3D.apply( gl, arguments );
  13982. } catch ( error ) {
  13983. console.error( 'THREE.WebGLState:', error );
  13984. }
  13985. }
  13986. //
  13987. function scissor( scissor ) {
  13988. if ( currentScissor.equals( scissor ) === false ) {
  13989. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13990. currentScissor.copy( scissor );
  13991. }
  13992. }
  13993. function viewport( viewport ) {
  13994. if ( currentViewport.equals( viewport ) === false ) {
  13995. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13996. currentViewport.copy( viewport );
  13997. }
  13998. }
  13999. function updateUBOMapping( uniformsGroup, program ) {
  14000. let mapping = uboProgramMap.get( program );
  14001. if ( mapping === undefined ) {
  14002. mapping = new WeakMap();
  14003. uboProgramMap.set( program, mapping );
  14004. }
  14005. let blockIndex = mapping.get( uniformsGroup );
  14006. if ( blockIndex === undefined ) {
  14007. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14008. mapping.set( uniformsGroup, blockIndex );
  14009. }
  14010. }
  14011. function uniformBlockBinding( uniformsGroup, program ) {
  14012. const mapping = uboProgramMap.get( program );
  14013. const blockIndex = mapping.get( uniformsGroup );
  14014. if ( uboBindings.get( program ) !== blockIndex ) {
  14015. // bind shader specific block index to global block point
  14016. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14017. uboBindings.set( program, blockIndex );
  14018. }
  14019. }
  14020. //
  14021. function reset() {
  14022. // reset state
  14023. gl.disable( gl.BLEND );
  14024. gl.disable( gl.CULL_FACE );
  14025. gl.disable( gl.DEPTH_TEST );
  14026. gl.disable( gl.POLYGON_OFFSET_FILL );
  14027. gl.disable( gl.SCISSOR_TEST );
  14028. gl.disable( gl.STENCIL_TEST );
  14029. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14030. gl.blendEquation( gl.FUNC_ADD );
  14031. gl.blendFunc( gl.ONE, gl.ZERO );
  14032. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14033. gl.colorMask( true, true, true, true );
  14034. gl.clearColor( 0, 0, 0, 0 );
  14035. gl.depthMask( true );
  14036. gl.depthFunc( gl.LESS );
  14037. gl.clearDepth( 1 );
  14038. gl.stencilMask( 0xffffffff );
  14039. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14040. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14041. gl.clearStencil( 0 );
  14042. gl.cullFace( gl.BACK );
  14043. gl.frontFace( gl.CCW );
  14044. gl.polygonOffset( 0, 0 );
  14045. gl.activeTexture( gl.TEXTURE0 );
  14046. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14047. if ( isWebGL2 === true ) {
  14048. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14049. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14050. }
  14051. gl.useProgram( null );
  14052. gl.lineWidth( 1 );
  14053. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14054. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14055. // reset internals
  14056. enabledCapabilities = {};
  14057. currentTextureSlot = null;
  14058. currentBoundTextures = {};
  14059. currentBoundFramebuffers = {};
  14060. currentDrawbuffers = new WeakMap();
  14061. defaultDrawbuffers = [];
  14062. currentProgram = null;
  14063. currentBlendingEnabled = false;
  14064. currentBlending = null;
  14065. currentBlendEquation = null;
  14066. currentBlendSrc = null;
  14067. currentBlendDst = null;
  14068. currentBlendEquationAlpha = null;
  14069. currentBlendSrcAlpha = null;
  14070. currentBlendDstAlpha = null;
  14071. currentPremultipledAlpha = false;
  14072. currentFlipSided = null;
  14073. currentCullFace = null;
  14074. currentLineWidth = null;
  14075. currentPolygonOffsetFactor = null;
  14076. currentPolygonOffsetUnits = null;
  14077. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14078. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14079. colorBuffer.reset();
  14080. depthBuffer.reset();
  14081. stencilBuffer.reset();
  14082. }
  14083. return {
  14084. buffers: {
  14085. color: colorBuffer,
  14086. depth: depthBuffer,
  14087. stencil: stencilBuffer
  14088. },
  14089. enable: enable,
  14090. disable: disable,
  14091. bindFramebuffer: bindFramebuffer,
  14092. drawBuffers: drawBuffers,
  14093. useProgram: useProgram,
  14094. setBlending: setBlending,
  14095. setMaterial: setMaterial,
  14096. setFlipSided: setFlipSided,
  14097. setCullFace: setCullFace,
  14098. setLineWidth: setLineWidth,
  14099. setPolygonOffset: setPolygonOffset,
  14100. setScissorTest: setScissorTest,
  14101. activeTexture: activeTexture,
  14102. bindTexture: bindTexture,
  14103. unbindTexture: unbindTexture,
  14104. compressedTexImage2D: compressedTexImage2D,
  14105. compressedTexImage3D: compressedTexImage3D,
  14106. texImage2D: texImage2D,
  14107. texImage3D: texImage3D,
  14108. updateUBOMapping: updateUBOMapping,
  14109. uniformBlockBinding: uniformBlockBinding,
  14110. texStorage2D: texStorage2D,
  14111. texStorage3D: texStorage3D,
  14112. texSubImage2D: texSubImage2D,
  14113. texSubImage3D: texSubImage3D,
  14114. compressedTexSubImage2D: compressedTexSubImage2D,
  14115. compressedTexSubImage3D: compressedTexSubImage3D,
  14116. scissor: scissor,
  14117. viewport: viewport,
  14118. reset: reset
  14119. };
  14120. }
  14121. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14122. const isWebGL2 = capabilities.isWebGL2;
  14123. const maxTextures = capabilities.maxTextures;
  14124. const maxCubemapSize = capabilities.maxCubemapSize;
  14125. const maxTextureSize = capabilities.maxTextureSize;
  14126. const maxSamples = capabilities.maxSamples;
  14127. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14128. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14129. const _videoTextures = new WeakMap();
  14130. let _canvas;
  14131. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14132. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14133. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14134. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14135. let useOffscreenCanvas = false;
  14136. try {
  14137. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14138. // eslint-disable-next-line compat/compat
  14139. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14140. } catch ( err ) {
  14141. // Ignore any errors
  14142. }
  14143. function createCanvas( width, height ) {
  14144. // Use OffscreenCanvas when available. Specially needed in web workers
  14145. return useOffscreenCanvas ?
  14146. // eslint-disable-next-line compat/compat
  14147. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14148. }
  14149. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14150. let scale = 1;
  14151. // handle case if texture exceeds max size
  14152. if ( image.width > maxSize || image.height > maxSize ) {
  14153. scale = maxSize / Math.max( image.width, image.height );
  14154. }
  14155. // only perform resize if necessary
  14156. if ( scale < 1 || needsPowerOfTwo === true ) {
  14157. // only perform resize for certain image types
  14158. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14159. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14160. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14161. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14162. const width = floor( scale * image.width );
  14163. const height = floor( scale * image.height );
  14164. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14165. // cube textures can't reuse the same canvas
  14166. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14167. canvas.width = width;
  14168. canvas.height = height;
  14169. const context = canvas.getContext( '2d' );
  14170. context.drawImage( image, 0, 0, width, height );
  14171. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14172. return canvas;
  14173. } else {
  14174. if ( 'data' in image ) {
  14175. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14176. }
  14177. return image;
  14178. }
  14179. }
  14180. return image;
  14181. }
  14182. function isPowerOfTwo$1( image ) {
  14183. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14184. }
  14185. function textureNeedsPowerOfTwo( texture ) {
  14186. if ( isWebGL2 ) return false;
  14187. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14188. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14189. }
  14190. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14191. return texture.generateMipmaps && supportsMips &&
  14192. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14193. }
  14194. function generateMipmap( target ) {
  14195. _gl.generateMipmap( target );
  14196. }
  14197. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14198. if ( isWebGL2 === false ) return glFormat;
  14199. if ( internalFormatName !== null ) {
  14200. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14201. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14202. }
  14203. let internalFormat = glFormat;
  14204. if ( glFormat === _gl.RED ) {
  14205. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14206. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14207. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14208. }
  14209. if ( glFormat === _gl.RG ) {
  14210. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14211. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14212. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14213. }
  14214. if ( glFormat === _gl.RGBA ) {
  14215. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14216. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14217. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14218. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14219. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14220. }
  14221. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14222. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14223. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14224. extensions.get( 'EXT_color_buffer_float' );
  14225. }
  14226. return internalFormat;
  14227. }
  14228. function getMipLevels( texture, image, supportsMips ) {
  14229. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14230. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14231. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14232. // user-defined mipmaps
  14233. return texture.mipmaps.length;
  14234. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14235. return image.mipmaps.length;
  14236. } else {
  14237. // texture without mipmaps (only base level)
  14238. return 1;
  14239. }
  14240. }
  14241. // Fallback filters for non-power-of-2 textures
  14242. function filterFallback( f ) {
  14243. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14244. return _gl.NEAREST;
  14245. }
  14246. return _gl.LINEAR;
  14247. }
  14248. //
  14249. function onTextureDispose( event ) {
  14250. const texture = event.target;
  14251. texture.removeEventListener( 'dispose', onTextureDispose );
  14252. deallocateTexture( texture );
  14253. if ( texture.isVideoTexture ) {
  14254. _videoTextures.delete( texture );
  14255. }
  14256. }
  14257. function onRenderTargetDispose( event ) {
  14258. const renderTarget = event.target;
  14259. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14260. deallocateRenderTarget( renderTarget );
  14261. }
  14262. //
  14263. function deallocateTexture( texture ) {
  14264. const textureProperties = properties.get( texture );
  14265. if ( textureProperties.__webglInit === undefined ) return;
  14266. // check if it's necessary to remove the WebGLTexture object
  14267. const source = texture.source;
  14268. const webglTextures = _sources.get( source );
  14269. if ( webglTextures ) {
  14270. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14271. webglTexture.usedTimes --;
  14272. // the WebGLTexture object is not used anymore, remove it
  14273. if ( webglTexture.usedTimes === 0 ) {
  14274. deleteTexture( texture );
  14275. }
  14276. // remove the weak map entry if no WebGLTexture uses the source anymore
  14277. if ( Object.keys( webglTextures ).length === 0 ) {
  14278. _sources.delete( source );
  14279. }
  14280. }
  14281. properties.remove( texture );
  14282. }
  14283. function deleteTexture( texture ) {
  14284. const textureProperties = properties.get( texture );
  14285. _gl.deleteTexture( textureProperties.__webglTexture );
  14286. const source = texture.source;
  14287. const webglTextures = _sources.get( source );
  14288. delete webglTextures[ textureProperties.__cacheKey ];
  14289. info.memory.textures --;
  14290. }
  14291. function deallocateRenderTarget( renderTarget ) {
  14292. const texture = renderTarget.texture;
  14293. const renderTargetProperties = properties.get( renderTarget );
  14294. const textureProperties = properties.get( texture );
  14295. if ( textureProperties.__webglTexture !== undefined ) {
  14296. _gl.deleteTexture( textureProperties.__webglTexture );
  14297. info.memory.textures --;
  14298. }
  14299. if ( renderTarget.depthTexture ) {
  14300. renderTarget.depthTexture.dispose();
  14301. }
  14302. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14303. for ( let i = 0; i < 6; i ++ ) {
  14304. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14305. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14306. }
  14307. } else {
  14308. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14309. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14310. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14311. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14312. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14313. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14314. }
  14315. }
  14316. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14317. }
  14318. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14319. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14320. const attachmentProperties = properties.get( texture[ i ] );
  14321. if ( attachmentProperties.__webglTexture ) {
  14322. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14323. info.memory.textures --;
  14324. }
  14325. properties.remove( texture[ i ] );
  14326. }
  14327. }
  14328. properties.remove( texture );
  14329. properties.remove( renderTarget );
  14330. }
  14331. //
  14332. let textureUnits = 0;
  14333. function resetTextureUnits() {
  14334. textureUnits = 0;
  14335. }
  14336. function allocateTextureUnit() {
  14337. const textureUnit = textureUnits;
  14338. if ( textureUnit >= maxTextures ) {
  14339. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14340. }
  14341. textureUnits += 1;
  14342. return textureUnit;
  14343. }
  14344. function getTextureCacheKey( texture ) {
  14345. const array = [];
  14346. array.push( texture.wrapS );
  14347. array.push( texture.wrapT );
  14348. array.push( texture.wrapR || 0 );
  14349. array.push( texture.magFilter );
  14350. array.push( texture.minFilter );
  14351. array.push( texture.anisotropy );
  14352. array.push( texture.internalFormat );
  14353. array.push( texture.format );
  14354. array.push( texture.type );
  14355. array.push( texture.generateMipmaps );
  14356. array.push( texture.premultiplyAlpha );
  14357. array.push( texture.flipY );
  14358. array.push( texture.unpackAlignment );
  14359. array.push( texture.colorSpace );
  14360. return array.join();
  14361. }
  14362. //
  14363. function setTexture2D( texture, slot ) {
  14364. const textureProperties = properties.get( texture );
  14365. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14366. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14367. const image = texture.image;
  14368. if ( image === null ) {
  14369. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14370. } else if ( image.complete === false ) {
  14371. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14372. } else {
  14373. uploadTexture( textureProperties, texture, slot );
  14374. return;
  14375. }
  14376. }
  14377. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14378. }
  14379. function setTexture2DArray( texture, slot ) {
  14380. const textureProperties = properties.get( texture );
  14381. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14382. uploadTexture( textureProperties, texture, slot );
  14383. return;
  14384. }
  14385. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14386. }
  14387. function setTexture3D( texture, slot ) {
  14388. const textureProperties = properties.get( texture );
  14389. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14390. uploadTexture( textureProperties, texture, slot );
  14391. return;
  14392. }
  14393. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14394. }
  14395. function setTextureCube( texture, slot ) {
  14396. const textureProperties = properties.get( texture );
  14397. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14398. uploadCubeTexture( textureProperties, texture, slot );
  14399. return;
  14400. }
  14401. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14402. }
  14403. const wrappingToGL = {
  14404. [ RepeatWrapping ]: _gl.REPEAT,
  14405. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14406. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14407. };
  14408. const filterToGL = {
  14409. [ NearestFilter ]: _gl.NEAREST,
  14410. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14411. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14412. [ LinearFilter ]: _gl.LINEAR,
  14413. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14414. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14415. };
  14416. const compareToGL = {
  14417. [ NeverCompare ]: _gl.NEVER,
  14418. [ AlwaysCompare ]: _gl.ALWAYS,
  14419. [ LessCompare ]: _gl.LESS,
  14420. [ LessEqualCompare ]: _gl.LEQUAL,
  14421. [ EqualCompare ]: _gl.EQUAL,
  14422. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14423. [ GreaterCompare ]: _gl.GREATER,
  14424. [ NotEqualCompare ]: _gl.NOTEQUAL
  14425. };
  14426. function setTextureParameters( textureType, texture, supportsMips ) {
  14427. if ( supportsMips ) {
  14428. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14429. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14430. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14431. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14432. }
  14433. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14434. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14435. } else {
  14436. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14437. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14438. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14439. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  14440. }
  14441. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14442. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14443. }
  14444. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14445. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14446. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14447. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14448. }
  14449. }
  14450. if ( texture.compareFunction ) {
  14451. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14452. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14453. }
  14454. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14455. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14456. if ( texture.magFilter === NearestFilter ) return;
  14457. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14458. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14459. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14460. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14461. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14462. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14463. }
  14464. }
  14465. }
  14466. function initTexture( textureProperties, texture ) {
  14467. let forceUpload = false;
  14468. if ( textureProperties.__webglInit === undefined ) {
  14469. textureProperties.__webglInit = true;
  14470. texture.addEventListener( 'dispose', onTextureDispose );
  14471. }
  14472. // create Source <-> WebGLTextures mapping if necessary
  14473. const source = texture.source;
  14474. let webglTextures = _sources.get( source );
  14475. if ( webglTextures === undefined ) {
  14476. webglTextures = {};
  14477. _sources.set( source, webglTextures );
  14478. }
  14479. // check if there is already a WebGLTexture object for the given texture parameters
  14480. const textureCacheKey = getTextureCacheKey( texture );
  14481. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14482. // if not, create a new instance of WebGLTexture
  14483. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14484. // create new entry
  14485. webglTextures[ textureCacheKey ] = {
  14486. texture: _gl.createTexture(),
  14487. usedTimes: 0
  14488. };
  14489. info.memory.textures ++;
  14490. // when a new instance of WebGLTexture was created, a texture upload is required
  14491. // even if the image contents are identical
  14492. forceUpload = true;
  14493. }
  14494. webglTextures[ textureCacheKey ].usedTimes ++;
  14495. // every time the texture cache key changes, it's necessary to check if an instance of
  14496. // WebGLTexture can be deleted in order to avoid a memory leak.
  14497. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14498. if ( webglTexture !== undefined ) {
  14499. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14500. if ( webglTexture.usedTimes === 0 ) {
  14501. deleteTexture( texture );
  14502. }
  14503. }
  14504. // store references to cache key and WebGLTexture object
  14505. textureProperties.__cacheKey = textureCacheKey;
  14506. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14507. }
  14508. return forceUpload;
  14509. }
  14510. function uploadTexture( textureProperties, texture, slot ) {
  14511. let textureType = _gl.TEXTURE_2D;
  14512. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14513. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14514. const forceUpload = initTexture( textureProperties, texture );
  14515. const source = texture.source;
  14516. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14517. const sourceProperties = properties.get( source );
  14518. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14519. state.activeTexture( _gl.TEXTURE0 + slot );
  14520. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14521. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14522. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14523. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14524. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14525. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14526. image = verifyColorSpace( texture, image );
  14527. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14528. glFormat = utils.convert( texture.format, texture.colorSpace );
  14529. let glType = utils.convert( texture.type ),
  14530. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14531. setTextureParameters( textureType, texture, supportsMips );
  14532. let mipmap;
  14533. const mipmaps = texture.mipmaps;
  14534. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14535. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14536. const levels = getMipLevels( texture, image, supportsMips );
  14537. if ( texture.isDepthTexture ) {
  14538. // populate depth texture with dummy data
  14539. glInternalFormat = _gl.DEPTH_COMPONENT;
  14540. if ( isWebGL2 ) {
  14541. if ( texture.type === FloatType ) {
  14542. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14543. } else if ( texture.type === UnsignedIntType ) {
  14544. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14545. } else if ( texture.type === UnsignedInt248Type ) {
  14546. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14547. } else {
  14548. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14549. }
  14550. } else {
  14551. if ( texture.type === FloatType ) {
  14552. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14553. }
  14554. }
  14555. // validation checks for WebGL 1
  14556. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14557. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14558. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14559. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14560. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14561. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14562. texture.type = UnsignedIntType;
  14563. glType = utils.convert( texture.type );
  14564. }
  14565. }
  14566. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14567. // Depth stencil textures need the DEPTH_STENCIL internal format
  14568. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14569. glInternalFormat = _gl.DEPTH_STENCIL;
  14570. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14571. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14572. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14573. if ( texture.type !== UnsignedInt248Type ) {
  14574. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14575. texture.type = UnsignedInt248Type;
  14576. glType = utils.convert( texture.type );
  14577. }
  14578. }
  14579. //
  14580. if ( allocateMemory ) {
  14581. if ( useTexStorage ) {
  14582. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14583. } else {
  14584. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14585. }
  14586. }
  14587. } else if ( texture.isDataTexture ) {
  14588. // use manually created mipmaps if available
  14589. // if there are no manual mipmaps
  14590. // set 0 level mipmap and then use GL to generate other mipmap levels
  14591. if ( mipmaps.length > 0 && supportsMips ) {
  14592. if ( useTexStorage && allocateMemory ) {
  14593. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14594. }
  14595. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14596. mipmap = mipmaps[ i ];
  14597. if ( useTexStorage ) {
  14598. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14599. } else {
  14600. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14601. }
  14602. }
  14603. texture.generateMipmaps = false;
  14604. } else {
  14605. if ( useTexStorage ) {
  14606. if ( allocateMemory ) {
  14607. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14608. }
  14609. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14610. } else {
  14611. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14612. }
  14613. }
  14614. } else if ( texture.isCompressedTexture ) {
  14615. if ( texture.isCompressedArrayTexture ) {
  14616. if ( useTexStorage && allocateMemory ) {
  14617. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14618. }
  14619. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14620. mipmap = mipmaps[ i ];
  14621. if ( texture.format !== RGBAFormat ) {
  14622. if ( glFormat !== null ) {
  14623. if ( useTexStorage ) {
  14624. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14625. } else {
  14626. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14627. }
  14628. } else {
  14629. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14630. }
  14631. } else {
  14632. if ( useTexStorage ) {
  14633. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14634. } else {
  14635. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14636. }
  14637. }
  14638. }
  14639. } else {
  14640. if ( useTexStorage && allocateMemory ) {
  14641. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14642. }
  14643. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14644. mipmap = mipmaps[ i ];
  14645. if ( texture.format !== RGBAFormat ) {
  14646. if ( glFormat !== null ) {
  14647. if ( useTexStorage ) {
  14648. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14649. } else {
  14650. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14651. }
  14652. } else {
  14653. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14654. }
  14655. } else {
  14656. if ( useTexStorage ) {
  14657. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14658. } else {
  14659. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14660. }
  14661. }
  14662. }
  14663. }
  14664. } else if ( texture.isDataArrayTexture ) {
  14665. if ( useTexStorage ) {
  14666. if ( allocateMemory ) {
  14667. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14668. }
  14669. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14670. } else {
  14671. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14672. }
  14673. } else if ( texture.isData3DTexture ) {
  14674. if ( useTexStorage ) {
  14675. if ( allocateMemory ) {
  14676. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14677. }
  14678. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14679. } else {
  14680. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14681. }
  14682. } else if ( texture.isFramebufferTexture ) {
  14683. if ( allocateMemory ) {
  14684. if ( useTexStorage ) {
  14685. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14686. } else {
  14687. let width = image.width, height = image.height;
  14688. for ( let i = 0; i < levels; i ++ ) {
  14689. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14690. width >>= 1;
  14691. height >>= 1;
  14692. }
  14693. }
  14694. }
  14695. } else {
  14696. // regular Texture (image, video, canvas)
  14697. // use manually created mipmaps if available
  14698. // if there are no manual mipmaps
  14699. // set 0 level mipmap and then use GL to generate other mipmap levels
  14700. if ( mipmaps.length > 0 && supportsMips ) {
  14701. if ( useTexStorage && allocateMemory ) {
  14702. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14703. }
  14704. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14705. mipmap = mipmaps[ i ];
  14706. if ( useTexStorage ) {
  14707. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14708. } else {
  14709. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14710. }
  14711. }
  14712. texture.generateMipmaps = false;
  14713. } else {
  14714. if ( useTexStorage ) {
  14715. if ( allocateMemory ) {
  14716. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14717. }
  14718. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14719. } else {
  14720. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14721. }
  14722. }
  14723. }
  14724. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14725. generateMipmap( textureType );
  14726. }
  14727. sourceProperties.__version = source.version;
  14728. if ( texture.onUpdate ) texture.onUpdate( texture );
  14729. }
  14730. textureProperties.__version = texture.version;
  14731. }
  14732. function uploadCubeTexture( textureProperties, texture, slot ) {
  14733. if ( texture.image.length !== 6 ) return;
  14734. const forceUpload = initTexture( textureProperties, texture );
  14735. const source = texture.source;
  14736. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14737. const sourceProperties = properties.get( source );
  14738. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14739. state.activeTexture( _gl.TEXTURE0 + slot );
  14740. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14741. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14742. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14743. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14744. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14745. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14746. const cubeImage = [];
  14747. for ( let i = 0; i < 6; i ++ ) {
  14748. if ( ! isCompressed && ! isDataTexture ) {
  14749. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14750. } else {
  14751. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14752. }
  14753. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14754. }
  14755. const image = cubeImage[ 0 ],
  14756. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14757. glFormat = utils.convert( texture.format, texture.colorSpace ),
  14758. glType = utils.convert( texture.type ),
  14759. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14760. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14761. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14762. let levels = getMipLevels( texture, image, supportsMips );
  14763. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14764. let mipmaps;
  14765. if ( isCompressed ) {
  14766. if ( useTexStorage && allocateMemory ) {
  14767. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14768. }
  14769. for ( let i = 0; i < 6; i ++ ) {
  14770. mipmaps = cubeImage[ i ].mipmaps;
  14771. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14772. const mipmap = mipmaps[ j ];
  14773. if ( texture.format !== RGBAFormat ) {
  14774. if ( glFormat !== null ) {
  14775. if ( useTexStorage ) {
  14776. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14777. } else {
  14778. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14779. }
  14780. } else {
  14781. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14782. }
  14783. } else {
  14784. if ( useTexStorage ) {
  14785. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14786. } else {
  14787. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14788. }
  14789. }
  14790. }
  14791. }
  14792. } else {
  14793. mipmaps = texture.mipmaps;
  14794. if ( useTexStorage && allocateMemory ) {
  14795. // TODO: Uniformly handle mipmap definitions
  14796. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14797. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14798. if ( mipmaps.length > 0 ) levels ++;
  14799. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14800. }
  14801. for ( let i = 0; i < 6; i ++ ) {
  14802. if ( isDataTexture ) {
  14803. if ( useTexStorage ) {
  14804. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14805. } else {
  14806. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14807. }
  14808. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14809. const mipmap = mipmaps[ j ];
  14810. const mipmapImage = mipmap.image[ i ].image;
  14811. if ( useTexStorage ) {
  14812. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14813. } else {
  14814. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14815. }
  14816. }
  14817. } else {
  14818. if ( useTexStorage ) {
  14819. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14820. } else {
  14821. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14822. }
  14823. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14824. const mipmap = mipmaps[ j ];
  14825. if ( useTexStorage ) {
  14826. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14827. } else {
  14828. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14829. }
  14830. }
  14831. }
  14832. }
  14833. }
  14834. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14835. // We assume images for cube map have the same size.
  14836. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14837. }
  14838. sourceProperties.__version = source.version;
  14839. if ( texture.onUpdate ) texture.onUpdate( texture );
  14840. }
  14841. textureProperties.__version = texture.version;
  14842. }
  14843. // Render targets
  14844. // Setup storage for target texture and bind it to correct framebuffer
  14845. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14846. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14847. const glType = utils.convert( texture.type );
  14848. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14849. const renderTargetProperties = properties.get( renderTarget );
  14850. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14851. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14852. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14853. } else {
  14854. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14855. }
  14856. }
  14857. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14858. if ( useMultisampledRTT( renderTarget ) ) {
  14859. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14860. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14861. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14862. }
  14863. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14864. }
  14865. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14866. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14867. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14868. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14869. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14870. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14871. const depthTexture = renderTarget.depthTexture;
  14872. if ( depthTexture && depthTexture.isDepthTexture ) {
  14873. if ( depthTexture.type === FloatType ) {
  14874. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14875. } else if ( depthTexture.type === UnsignedIntType ) {
  14876. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14877. }
  14878. }
  14879. const samples = getRenderTargetSamples( renderTarget );
  14880. if ( useMultisampledRTT( renderTarget ) ) {
  14881. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14882. } else {
  14883. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14884. }
  14885. } else {
  14886. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14887. }
  14888. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14889. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14890. const samples = getRenderTargetSamples( renderTarget );
  14891. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14892. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14893. } else if ( useMultisampledRTT( renderTarget ) ) {
  14894. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14895. } else {
  14896. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14897. }
  14898. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14899. } else {
  14900. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14901. for ( let i = 0; i < textures.length; i ++ ) {
  14902. const texture = textures[ i ];
  14903. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14904. const glType = utils.convert( texture.type );
  14905. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14906. const samples = getRenderTargetSamples( renderTarget );
  14907. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14908. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14909. } else if ( useMultisampledRTT( renderTarget ) ) {
  14910. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14911. } else {
  14912. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14913. }
  14914. }
  14915. }
  14916. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14917. }
  14918. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14919. function setupDepthTexture( framebuffer, renderTarget ) {
  14920. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14921. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14922. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14923. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14924. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14925. }
  14926. // upload an empty depth texture with framebuffer size
  14927. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14928. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14929. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14930. renderTarget.depthTexture.image.width = renderTarget.width;
  14931. renderTarget.depthTexture.image.height = renderTarget.height;
  14932. renderTarget.depthTexture.needsUpdate = true;
  14933. }
  14934. setTexture2D( renderTarget.depthTexture, 0 );
  14935. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14936. const samples = getRenderTargetSamples( renderTarget );
  14937. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14938. if ( useMultisampledRTT( renderTarget ) ) {
  14939. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14940. } else {
  14941. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14942. }
  14943. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14944. if ( useMultisampledRTT( renderTarget ) ) {
  14945. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14946. } else {
  14947. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14948. }
  14949. } else {
  14950. throw new Error( 'Unknown depthTexture format' );
  14951. }
  14952. }
  14953. // Setup GL resources for a non-texture depth buffer
  14954. function setupDepthRenderbuffer( renderTarget ) {
  14955. const renderTargetProperties = properties.get( renderTarget );
  14956. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14957. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14958. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14959. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14960. } else {
  14961. if ( isCube ) {
  14962. renderTargetProperties.__webglDepthbuffer = [];
  14963. for ( let i = 0; i < 6; i ++ ) {
  14964. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14965. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14966. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14967. }
  14968. } else {
  14969. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14970. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14971. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14972. }
  14973. }
  14974. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14975. }
  14976. // rebind framebuffer with external textures
  14977. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14978. const renderTargetProperties = properties.get( renderTarget );
  14979. if ( colorTexture !== undefined ) {
  14980. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  14981. }
  14982. if ( depthTexture !== undefined ) {
  14983. setupDepthRenderbuffer( renderTarget );
  14984. }
  14985. }
  14986. // Set up GL resources for the render target
  14987. function setupRenderTarget( renderTarget ) {
  14988. const texture = renderTarget.texture;
  14989. const renderTargetProperties = properties.get( renderTarget );
  14990. const textureProperties = properties.get( texture );
  14991. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14992. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14993. if ( textureProperties.__webglTexture === undefined ) {
  14994. textureProperties.__webglTexture = _gl.createTexture();
  14995. }
  14996. textureProperties.__version = texture.version;
  14997. info.memory.textures ++;
  14998. }
  14999. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15000. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15001. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15002. // Setup framebuffer
  15003. if ( isCube ) {
  15004. renderTargetProperties.__webglFramebuffer = [];
  15005. for ( let i = 0; i < 6; i ++ ) {
  15006. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15007. }
  15008. } else {
  15009. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15010. if ( isMultipleRenderTargets ) {
  15011. if ( capabilities.drawBuffers ) {
  15012. const textures = renderTarget.texture;
  15013. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15014. const attachmentProperties = properties.get( textures[ i ] );
  15015. if ( attachmentProperties.__webglTexture === undefined ) {
  15016. attachmentProperties.__webglTexture = _gl.createTexture();
  15017. info.memory.textures ++;
  15018. }
  15019. }
  15020. } else {
  15021. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  15022. }
  15023. }
  15024. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15025. const textures = isMultipleRenderTargets ? texture : [ texture ];
  15026. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15027. renderTargetProperties.__webglColorRenderbuffer = [];
  15028. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15029. for ( let i = 0; i < textures.length; i ++ ) {
  15030. const texture = textures[ i ];
  15031. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15032. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15033. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15034. const glType = utils.convert( texture.type );
  15035. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15036. const samples = getRenderTargetSamples( renderTarget );
  15037. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15038. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15039. }
  15040. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15041. if ( renderTarget.depthBuffer ) {
  15042. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15043. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15044. }
  15045. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15046. }
  15047. }
  15048. // Setup color buffer
  15049. if ( isCube ) {
  15050. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15051. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  15052. for ( let i = 0; i < 6; i ++ ) {
  15053. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15054. }
  15055. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15056. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15057. }
  15058. state.unbindTexture();
  15059. } else if ( isMultipleRenderTargets ) {
  15060. const textures = renderTarget.texture;
  15061. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15062. const attachment = textures[ i ];
  15063. const attachmentProperties = properties.get( attachment );
  15064. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15065. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  15066. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );
  15067. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  15068. generateMipmap( _gl.TEXTURE_2D );
  15069. }
  15070. }
  15071. state.unbindTexture();
  15072. } else {
  15073. let glTextureType = _gl.TEXTURE_2D;
  15074. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15075. if ( isWebGL2 ) {
  15076. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15077. } else {
  15078. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  15079. }
  15080. }
  15081. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15082. setTextureParameters( glTextureType, texture, supportsMips );
  15083. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );
  15084. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15085. generateMipmap( glTextureType );
  15086. }
  15087. state.unbindTexture();
  15088. }
  15089. // Setup depth and stencil buffers
  15090. if ( renderTarget.depthBuffer ) {
  15091. setupDepthRenderbuffer( renderTarget );
  15092. }
  15093. }
  15094. function updateRenderTargetMipmap( renderTarget ) {
  15095. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15096. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  15097. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15098. const texture = textures[ i ];
  15099. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15100. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15101. const webglTexture = properties.get( texture ).__webglTexture;
  15102. state.bindTexture( target, webglTexture );
  15103. generateMipmap( target );
  15104. state.unbindTexture();
  15105. }
  15106. }
  15107. }
  15108. function updateMultisampleRenderTarget( renderTarget ) {
  15109. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15110. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  15111. const width = renderTarget.width;
  15112. const height = renderTarget.height;
  15113. let mask = _gl.COLOR_BUFFER_BIT;
  15114. const invalidationArray = [];
  15115. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15116. const renderTargetProperties = properties.get( renderTarget );
  15117. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15118. // If MRT we need to remove FBO attachments
  15119. if ( isMultipleRenderTargets ) {
  15120. for ( let i = 0; i < textures.length; i ++ ) {
  15121. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15122. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15123. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15124. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15125. }
  15126. }
  15127. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15128. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15129. for ( let i = 0; i < textures.length; i ++ ) {
  15130. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  15131. if ( renderTarget.depthBuffer ) {
  15132. invalidationArray.push( depthStyle );
  15133. }
  15134. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  15135. if ( ignoreDepthValues === false ) {
  15136. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15137. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15138. }
  15139. if ( isMultipleRenderTargets ) {
  15140. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15141. }
  15142. if ( ignoreDepthValues === true ) {
  15143. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  15144. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15145. }
  15146. if ( isMultipleRenderTargets ) {
  15147. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15148. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15149. }
  15150. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15151. if ( supportsInvalidateFramebuffer ) {
  15152. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  15153. }
  15154. }
  15155. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15156. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15157. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15158. if ( isMultipleRenderTargets ) {
  15159. for ( let i = 0; i < textures.length; i ++ ) {
  15160. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15161. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15162. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15163. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15164. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15165. }
  15166. }
  15167. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15168. }
  15169. }
  15170. function getRenderTargetSamples( renderTarget ) {
  15171. return Math.min( maxSamples, renderTarget.samples );
  15172. }
  15173. function useMultisampledRTT( renderTarget ) {
  15174. const renderTargetProperties = properties.get( renderTarget );
  15175. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15176. }
  15177. function updateVideoTexture( texture ) {
  15178. const frame = info.render.frame;
  15179. // Check the last frame we updated the VideoTexture
  15180. if ( _videoTextures.get( texture ) !== frame ) {
  15181. _videoTextures.set( texture, frame );
  15182. texture.update();
  15183. }
  15184. }
  15185. function verifyColorSpace( texture, image ) {
  15186. const colorSpace = texture.colorSpace;
  15187. const format = texture.format;
  15188. const type = texture.type;
  15189. if ( texture.isCompressedTexture === true || texture.format === _SRGBAFormat ) return image;
  15190. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15191. // sRGB
  15192. if ( colorSpace === SRGBColorSpace ) {
  15193. if ( isWebGL2 === false ) {
  15194. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  15195. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  15196. texture.format = _SRGBAFormat;
  15197. // it's not possible to generate mips in WebGL 1 with this extension
  15198. texture.minFilter = LinearFilter;
  15199. texture.generateMipmaps = false;
  15200. } else {
  15201. // slow fallback (CPU decode)
  15202. image = ImageUtils.sRGBToLinear( image );
  15203. }
  15204. } else {
  15205. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15206. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15207. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15208. }
  15209. }
  15210. } else {
  15211. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15212. }
  15213. }
  15214. return image;
  15215. }
  15216. //
  15217. this.allocateTextureUnit = allocateTextureUnit;
  15218. this.resetTextureUnits = resetTextureUnits;
  15219. this.setTexture2D = setTexture2D;
  15220. this.setTexture2DArray = setTexture2DArray;
  15221. this.setTexture3D = setTexture3D;
  15222. this.setTextureCube = setTextureCube;
  15223. this.rebindTextures = rebindTextures;
  15224. this.setupRenderTarget = setupRenderTarget;
  15225. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15226. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15227. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15228. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15229. this.useMultisampledRTT = useMultisampledRTT;
  15230. }
  15231. function WebGLUtils( gl, extensions, capabilities ) {
  15232. const isWebGL2 = capabilities.isWebGL2;
  15233. function convert( p, colorSpace = NoColorSpace ) {
  15234. let extension;
  15235. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15236. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15237. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15238. if ( p === ByteType ) return gl.BYTE;
  15239. if ( p === ShortType ) return gl.SHORT;
  15240. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15241. if ( p === IntType ) return gl.INT;
  15242. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15243. if ( p === FloatType ) return gl.FLOAT;
  15244. if ( p === HalfFloatType ) {
  15245. if ( isWebGL2 ) return gl.HALF_FLOAT;
  15246. extension = extensions.get( 'OES_texture_half_float' );
  15247. if ( extension !== null ) {
  15248. return extension.HALF_FLOAT_OES;
  15249. } else {
  15250. return null;
  15251. }
  15252. }
  15253. if ( p === AlphaFormat ) return gl.ALPHA;
  15254. if ( p === RGBAFormat ) return gl.RGBA;
  15255. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15256. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15257. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15258. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15259. // WebGL 1 sRGB fallback
  15260. if ( p === _SRGBAFormat ) {
  15261. extension = extensions.get( 'EXT_sRGB' );
  15262. if ( extension !== null ) {
  15263. return extension.SRGB_ALPHA_EXT;
  15264. } else {
  15265. return null;
  15266. }
  15267. }
  15268. // WebGL2 formats.
  15269. if ( p === RedFormat ) return gl.RED;
  15270. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15271. if ( p === RGFormat ) return gl.RG;
  15272. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15273. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15274. // S3TC
  15275. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15276. if ( colorSpace === SRGBColorSpace ) {
  15277. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15278. if ( extension !== null ) {
  15279. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15280. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15281. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15282. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15283. } else {
  15284. return null;
  15285. }
  15286. } else {
  15287. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15288. if ( extension !== null ) {
  15289. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15290. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15291. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15292. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15293. } else {
  15294. return null;
  15295. }
  15296. }
  15297. }
  15298. // PVRTC
  15299. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15300. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15301. if ( extension !== null ) {
  15302. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15303. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15304. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15305. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15306. } else {
  15307. return null;
  15308. }
  15309. }
  15310. // ETC1
  15311. if ( p === RGB_ETC1_Format ) {
  15312. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15313. if ( extension !== null ) {
  15314. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15315. } else {
  15316. return null;
  15317. }
  15318. }
  15319. // ETC2
  15320. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15321. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15322. if ( extension !== null ) {
  15323. if ( p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15324. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15325. } else {
  15326. return null;
  15327. }
  15328. }
  15329. // ASTC
  15330. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15331. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15332. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15333. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15334. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15335. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15336. if ( extension !== null ) {
  15337. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15338. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15339. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15340. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15341. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15342. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15343. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15344. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15345. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15346. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15347. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15348. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15349. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15350. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15351. } else {
  15352. return null;
  15353. }
  15354. }
  15355. // BPTC
  15356. if ( p === RGBA_BPTC_Format ) {
  15357. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15358. if ( extension !== null ) {
  15359. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15360. } else {
  15361. return null;
  15362. }
  15363. }
  15364. // RGTC
  15365. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15366. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15367. if ( extension !== null ) {
  15368. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15369. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15370. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15371. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15372. } else {
  15373. return null;
  15374. }
  15375. }
  15376. //
  15377. if ( p === UnsignedInt248Type ) {
  15378. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  15379. extension = extensions.get( 'WEBGL_depth_texture' );
  15380. if ( extension !== null ) {
  15381. return extension.UNSIGNED_INT_24_8_WEBGL;
  15382. } else {
  15383. return null;
  15384. }
  15385. }
  15386. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15387. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15388. }
  15389. return { convert: convert };
  15390. }
  15391. class ArrayCamera extends PerspectiveCamera {
  15392. constructor( array = [] ) {
  15393. super();
  15394. this.isArrayCamera = true;
  15395. this.cameras = array;
  15396. }
  15397. }
  15398. class Group extends Object3D {
  15399. constructor() {
  15400. super();
  15401. this.isGroup = true;
  15402. this.type = 'Group';
  15403. }
  15404. }
  15405. const _moveEvent = { type: 'move' };
  15406. class WebXRController {
  15407. constructor() {
  15408. this._targetRay = null;
  15409. this._grip = null;
  15410. this._hand = null;
  15411. }
  15412. getHandSpace() {
  15413. if ( this._hand === null ) {
  15414. this._hand = new Group();
  15415. this._hand.matrixAutoUpdate = false;
  15416. this._hand.visible = false;
  15417. this._hand.joints = {};
  15418. this._hand.inputState = { pinching: false };
  15419. }
  15420. return this._hand;
  15421. }
  15422. getTargetRaySpace() {
  15423. if ( this._targetRay === null ) {
  15424. this._targetRay = new Group();
  15425. this._targetRay.matrixAutoUpdate = false;
  15426. this._targetRay.visible = false;
  15427. this._targetRay.hasLinearVelocity = false;
  15428. this._targetRay.linearVelocity = new Vector3();
  15429. this._targetRay.hasAngularVelocity = false;
  15430. this._targetRay.angularVelocity = new Vector3();
  15431. }
  15432. return this._targetRay;
  15433. }
  15434. getGripSpace() {
  15435. if ( this._grip === null ) {
  15436. this._grip = new Group();
  15437. this._grip.matrixAutoUpdate = false;
  15438. this._grip.visible = false;
  15439. this._grip.hasLinearVelocity = false;
  15440. this._grip.linearVelocity = new Vector3();
  15441. this._grip.hasAngularVelocity = false;
  15442. this._grip.angularVelocity = new Vector3();
  15443. }
  15444. return this._grip;
  15445. }
  15446. dispatchEvent( event ) {
  15447. if ( this._targetRay !== null ) {
  15448. this._targetRay.dispatchEvent( event );
  15449. }
  15450. if ( this._grip !== null ) {
  15451. this._grip.dispatchEvent( event );
  15452. }
  15453. if ( this._hand !== null ) {
  15454. this._hand.dispatchEvent( event );
  15455. }
  15456. return this;
  15457. }
  15458. connect( inputSource ) {
  15459. if ( inputSource && inputSource.hand ) {
  15460. const hand = this._hand;
  15461. if ( hand ) {
  15462. for ( const inputjoint of inputSource.hand.values() ) {
  15463. // Initialize hand with joints when connected
  15464. this._getHandJoint( hand, inputjoint );
  15465. }
  15466. }
  15467. }
  15468. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15469. return this;
  15470. }
  15471. disconnect( inputSource ) {
  15472. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15473. if ( this._targetRay !== null ) {
  15474. this._targetRay.visible = false;
  15475. }
  15476. if ( this._grip !== null ) {
  15477. this._grip.visible = false;
  15478. }
  15479. if ( this._hand !== null ) {
  15480. this._hand.visible = false;
  15481. }
  15482. return this;
  15483. }
  15484. update( inputSource, frame, referenceSpace ) {
  15485. let inputPose = null;
  15486. let gripPose = null;
  15487. let handPose = null;
  15488. const targetRay = this._targetRay;
  15489. const grip = this._grip;
  15490. const hand = this._hand;
  15491. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15492. if ( hand && inputSource.hand ) {
  15493. handPose = true;
  15494. for ( const inputjoint of inputSource.hand.values() ) {
  15495. // Update the joints groups with the XRJoint poses
  15496. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15497. // The transform of this joint will be updated with the joint pose on each frame
  15498. const joint = this._getHandJoint( hand, inputjoint );
  15499. if ( jointPose !== null ) {
  15500. joint.matrix.fromArray( jointPose.transform.matrix );
  15501. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15502. joint.matrixWorldNeedsUpdate = true;
  15503. joint.jointRadius = jointPose.radius;
  15504. }
  15505. joint.visible = jointPose !== null;
  15506. }
  15507. // Custom events
  15508. // Check pinchz
  15509. const indexTip = hand.joints[ 'index-finger-tip' ];
  15510. const thumbTip = hand.joints[ 'thumb-tip' ];
  15511. const distance = indexTip.position.distanceTo( thumbTip.position );
  15512. const distanceToPinch = 0.02;
  15513. const threshold = 0.005;
  15514. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15515. hand.inputState.pinching = false;
  15516. this.dispatchEvent( {
  15517. type: 'pinchend',
  15518. handedness: inputSource.handedness,
  15519. target: this
  15520. } );
  15521. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15522. hand.inputState.pinching = true;
  15523. this.dispatchEvent( {
  15524. type: 'pinchstart',
  15525. handedness: inputSource.handedness,
  15526. target: this
  15527. } );
  15528. }
  15529. } else {
  15530. if ( grip !== null && inputSource.gripSpace ) {
  15531. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15532. if ( gripPose !== null ) {
  15533. grip.matrix.fromArray( gripPose.transform.matrix );
  15534. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15535. grip.matrixWorldNeedsUpdate = true;
  15536. if ( gripPose.linearVelocity ) {
  15537. grip.hasLinearVelocity = true;
  15538. grip.linearVelocity.copy( gripPose.linearVelocity );
  15539. } else {
  15540. grip.hasLinearVelocity = false;
  15541. }
  15542. if ( gripPose.angularVelocity ) {
  15543. grip.hasAngularVelocity = true;
  15544. grip.angularVelocity.copy( gripPose.angularVelocity );
  15545. } else {
  15546. grip.hasAngularVelocity = false;
  15547. }
  15548. }
  15549. }
  15550. }
  15551. if ( targetRay !== null ) {
  15552. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15553. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15554. if ( inputPose === null && gripPose !== null ) {
  15555. inputPose = gripPose;
  15556. }
  15557. if ( inputPose !== null ) {
  15558. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15559. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15560. targetRay.matrixWorldNeedsUpdate = true;
  15561. if ( inputPose.linearVelocity ) {
  15562. targetRay.hasLinearVelocity = true;
  15563. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15564. } else {
  15565. targetRay.hasLinearVelocity = false;
  15566. }
  15567. if ( inputPose.angularVelocity ) {
  15568. targetRay.hasAngularVelocity = true;
  15569. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15570. } else {
  15571. targetRay.hasAngularVelocity = false;
  15572. }
  15573. this.dispatchEvent( _moveEvent );
  15574. }
  15575. }
  15576. }
  15577. if ( targetRay !== null ) {
  15578. targetRay.visible = ( inputPose !== null );
  15579. }
  15580. if ( grip !== null ) {
  15581. grip.visible = ( gripPose !== null );
  15582. }
  15583. if ( hand !== null ) {
  15584. hand.visible = ( handPose !== null );
  15585. }
  15586. return this;
  15587. }
  15588. // private method
  15589. _getHandJoint( hand, inputjoint ) {
  15590. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15591. const joint = new Group();
  15592. joint.matrixAutoUpdate = false;
  15593. joint.visible = false;
  15594. hand.joints[ inputjoint.jointName ] = joint;
  15595. hand.add( joint );
  15596. }
  15597. return hand.joints[ inputjoint.jointName ];
  15598. }
  15599. }
  15600. class DepthTexture extends Texture {
  15601. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15602. format = format !== undefined ? format : DepthFormat;
  15603. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15604. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15605. }
  15606. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15607. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15608. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15609. this.isDepthTexture = true;
  15610. this.image = { width: width, height: height };
  15611. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15612. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15613. this.flipY = false;
  15614. this.generateMipmaps = false;
  15615. this.compareFunction = null;
  15616. }
  15617. copy( source ) {
  15618. super.copy( source );
  15619. this.compareFunction = source.compareFunction;
  15620. return this;
  15621. }
  15622. toJSON( meta ) {
  15623. const data = super.toJSON( meta );
  15624. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  15625. return data;
  15626. }
  15627. }
  15628. class WebXRManager extends EventDispatcher {
  15629. constructor( renderer, gl ) {
  15630. super();
  15631. const scope = this;
  15632. let session = null;
  15633. let framebufferScaleFactor = 1.0;
  15634. let referenceSpace = null;
  15635. let referenceSpaceType = 'local-floor';
  15636. // Set default foveation to maximum.
  15637. let foveation = 1.0;
  15638. let customReferenceSpace = null;
  15639. let pose = null;
  15640. let glBinding = null;
  15641. let glProjLayer = null;
  15642. let glBaseLayer = null;
  15643. let xrFrame = null;
  15644. const attributes = gl.getContextAttributes();
  15645. let initialRenderTarget = null;
  15646. let newRenderTarget = null;
  15647. const controllers = [];
  15648. const controllerInputSources = [];
  15649. //
  15650. let userCamera = null;
  15651. const cameraL = new PerspectiveCamera();
  15652. cameraL.layers.enable( 1 );
  15653. cameraL.viewport = new Vector4();
  15654. const cameraR = new PerspectiveCamera();
  15655. cameraR.layers.enable( 2 );
  15656. cameraR.viewport = new Vector4();
  15657. const cameras = [ cameraL, cameraR ];
  15658. const cameraXR = new ArrayCamera();
  15659. cameraXR.layers.enable( 1 );
  15660. cameraXR.layers.enable( 2 );
  15661. let _currentDepthNear = null;
  15662. let _currentDepthFar = null;
  15663. //
  15664. this.cameraAutoUpdate = true; // @deprecated, r153
  15665. this.enabled = false;
  15666. this.isPresenting = false;
  15667. this.getCamera = function () {}; // @deprecated, r153
  15668. this.setUserCamera = function ( value ) {
  15669. userCamera = value;
  15670. };
  15671. this.getController = function ( index ) {
  15672. let controller = controllers[ index ];
  15673. if ( controller === undefined ) {
  15674. controller = new WebXRController();
  15675. controllers[ index ] = controller;
  15676. }
  15677. return controller.getTargetRaySpace();
  15678. };
  15679. this.getControllerGrip = function ( index ) {
  15680. let controller = controllers[ index ];
  15681. if ( controller === undefined ) {
  15682. controller = new WebXRController();
  15683. controllers[ index ] = controller;
  15684. }
  15685. return controller.getGripSpace();
  15686. };
  15687. this.getHand = function ( index ) {
  15688. let controller = controllers[ index ];
  15689. if ( controller === undefined ) {
  15690. controller = new WebXRController();
  15691. controllers[ index ] = controller;
  15692. }
  15693. return controller.getHandSpace();
  15694. };
  15695. //
  15696. function onSessionEvent( event ) {
  15697. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15698. if ( controllerIndex === - 1 ) {
  15699. return;
  15700. }
  15701. const controller = controllers[ controllerIndex ];
  15702. if ( controller !== undefined ) {
  15703. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  15704. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15705. }
  15706. }
  15707. function onSessionEnd() {
  15708. session.removeEventListener( 'select', onSessionEvent );
  15709. session.removeEventListener( 'selectstart', onSessionEvent );
  15710. session.removeEventListener( 'selectend', onSessionEvent );
  15711. session.removeEventListener( 'squeeze', onSessionEvent );
  15712. session.removeEventListener( 'squeezestart', onSessionEvent );
  15713. session.removeEventListener( 'squeezeend', onSessionEvent );
  15714. session.removeEventListener( 'end', onSessionEnd );
  15715. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15716. for ( let i = 0; i < controllers.length; i ++ ) {
  15717. const inputSource = controllerInputSources[ i ];
  15718. if ( inputSource === null ) continue;
  15719. controllerInputSources[ i ] = null;
  15720. controllers[ i ].disconnect( inputSource );
  15721. }
  15722. _currentDepthNear = null;
  15723. _currentDepthFar = null;
  15724. // restore framebuffer/rendering state
  15725. renderer.setRenderTarget( initialRenderTarget );
  15726. glBaseLayer = null;
  15727. glProjLayer = null;
  15728. glBinding = null;
  15729. session = null;
  15730. newRenderTarget = null;
  15731. //
  15732. animation.stop();
  15733. scope.isPresenting = false;
  15734. scope.dispatchEvent( { type: 'sessionend' } );
  15735. }
  15736. this.setFramebufferScaleFactor = function ( value ) {
  15737. framebufferScaleFactor = value;
  15738. if ( scope.isPresenting === true ) {
  15739. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15740. }
  15741. };
  15742. this.setReferenceSpaceType = function ( value ) {
  15743. referenceSpaceType = value;
  15744. if ( scope.isPresenting === true ) {
  15745. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15746. }
  15747. };
  15748. this.getReferenceSpace = function () {
  15749. return customReferenceSpace || referenceSpace;
  15750. };
  15751. this.setReferenceSpace = function ( space ) {
  15752. customReferenceSpace = space;
  15753. };
  15754. this.getBaseLayer = function () {
  15755. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15756. };
  15757. this.getBinding = function () {
  15758. return glBinding;
  15759. };
  15760. this.getFrame = function () {
  15761. return xrFrame;
  15762. };
  15763. this.getSession = function () {
  15764. return session;
  15765. };
  15766. this.setSession = async function ( value ) {
  15767. session = value;
  15768. if ( session !== null ) {
  15769. initialRenderTarget = renderer.getRenderTarget();
  15770. session.addEventListener( 'select', onSessionEvent );
  15771. session.addEventListener( 'selectstart', onSessionEvent );
  15772. session.addEventListener( 'selectend', onSessionEvent );
  15773. session.addEventListener( 'squeeze', onSessionEvent );
  15774. session.addEventListener( 'squeezestart', onSessionEvent );
  15775. session.addEventListener( 'squeezeend', onSessionEvent );
  15776. session.addEventListener( 'end', onSessionEnd );
  15777. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15778. if ( attributes.xrCompatible !== true ) {
  15779. await gl.makeXRCompatible();
  15780. }
  15781. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15782. const layerInit = {
  15783. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15784. alpha: true,
  15785. depth: attributes.depth,
  15786. stencil: attributes.stencil,
  15787. framebufferScaleFactor: framebufferScaleFactor
  15788. };
  15789. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15790. session.updateRenderState( { baseLayer: glBaseLayer } );
  15791. newRenderTarget = new WebGLRenderTarget(
  15792. glBaseLayer.framebufferWidth,
  15793. glBaseLayer.framebufferHeight,
  15794. {
  15795. format: RGBAFormat,
  15796. type: UnsignedByteType,
  15797. colorSpace: renderer.outputColorSpace,
  15798. stencilBuffer: attributes.stencil
  15799. }
  15800. );
  15801. } else {
  15802. let depthFormat = null;
  15803. let depthType = null;
  15804. let glDepthFormat = null;
  15805. if ( attributes.depth ) {
  15806. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15807. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15808. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15809. }
  15810. const projectionlayerInit = {
  15811. colorFormat: gl.RGBA8,
  15812. depthFormat: glDepthFormat,
  15813. scaleFactor: framebufferScaleFactor
  15814. };
  15815. glBinding = new XRWebGLBinding( session, gl );
  15816. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15817. session.updateRenderState( { layers: [ glProjLayer ] } );
  15818. newRenderTarget = new WebGLRenderTarget(
  15819. glProjLayer.textureWidth,
  15820. glProjLayer.textureHeight,
  15821. {
  15822. format: RGBAFormat,
  15823. type: UnsignedByteType,
  15824. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15825. stencilBuffer: attributes.stencil,
  15826. colorSpace: renderer.outputColorSpace,
  15827. samples: attributes.antialias ? 4 : 0
  15828. } );
  15829. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15830. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15831. }
  15832. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15833. this.setFoveation( foveation );
  15834. customReferenceSpace = null;
  15835. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15836. animation.setContext( session );
  15837. animation.start();
  15838. scope.isPresenting = true;
  15839. scope.dispatchEvent( { type: 'sessionstart' } );
  15840. }
  15841. };
  15842. this.getEnvironmentBlendMode = function () {
  15843. if ( session !== null ) {
  15844. return session.environmentBlendMode;
  15845. }
  15846. };
  15847. function onInputSourcesChange( event ) {
  15848. // Notify disconnected
  15849. for ( let i = 0; i < event.removed.length; i ++ ) {
  15850. const inputSource = event.removed[ i ];
  15851. const index = controllerInputSources.indexOf( inputSource );
  15852. if ( index >= 0 ) {
  15853. controllerInputSources[ index ] = null;
  15854. controllers[ index ].disconnect( inputSource );
  15855. }
  15856. }
  15857. // Notify connected
  15858. for ( let i = 0; i < event.added.length; i ++ ) {
  15859. const inputSource = event.added[ i ];
  15860. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15861. if ( controllerIndex === - 1 ) {
  15862. // Assign input source a controller that currently has no input source
  15863. for ( let i = 0; i < controllers.length; i ++ ) {
  15864. if ( i >= controllerInputSources.length ) {
  15865. controllerInputSources.push( inputSource );
  15866. controllerIndex = i;
  15867. break;
  15868. } else if ( controllerInputSources[ i ] === null ) {
  15869. controllerInputSources[ i ] = inputSource;
  15870. controllerIndex = i;
  15871. break;
  15872. }
  15873. }
  15874. // If all controllers do currently receive input we ignore new ones
  15875. if ( controllerIndex === - 1 ) break;
  15876. }
  15877. const controller = controllers[ controllerIndex ];
  15878. if ( controller ) {
  15879. controller.connect( inputSource );
  15880. }
  15881. }
  15882. }
  15883. //
  15884. const cameraLPos = new Vector3();
  15885. const cameraRPos = new Vector3();
  15886. /**
  15887. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15888. * the cameras' projection and world matrices have already been set.
  15889. * And that near and far planes are identical for both cameras.
  15890. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15891. */
  15892. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15893. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15894. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15895. const ipd = cameraLPos.distanceTo( cameraRPos );
  15896. const projL = cameraL.projectionMatrix.elements;
  15897. const projR = cameraR.projectionMatrix.elements;
  15898. // VR systems will have identical far and near planes, and
  15899. // most likely identical top and bottom frustum extents.
  15900. // Use the left camera for these values.
  15901. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15902. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15903. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15904. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15905. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15906. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15907. const left = near * leftFov;
  15908. const right = near * rightFov;
  15909. // Calculate the new camera's position offset from the
  15910. // left camera. xOffset should be roughly half `ipd`.
  15911. const zOffset = ipd / ( - leftFov + rightFov );
  15912. const xOffset = zOffset * - leftFov;
  15913. // TODO: Better way to apply this offset?
  15914. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15915. camera.translateX( xOffset );
  15916. camera.translateZ( zOffset );
  15917. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15918. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15919. // Find the union of the frustum values of the cameras and scale
  15920. // the values so that the near plane's position does not change in world space,
  15921. // although must now be relative to the new union camera.
  15922. const near2 = near + zOffset;
  15923. const far2 = far + zOffset;
  15924. const left2 = left - xOffset;
  15925. const right2 = right + ( ipd - xOffset );
  15926. const top2 = topFov * far / far2 * near2;
  15927. const bottom2 = bottomFov * far / far2 * near2;
  15928. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15929. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15930. }
  15931. function updateCamera( camera, parent ) {
  15932. if ( parent === null ) {
  15933. camera.matrixWorld.copy( camera.matrix );
  15934. } else {
  15935. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15936. }
  15937. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15938. }
  15939. this.updateCameraXR = function ( camera ) {
  15940. if ( session === null ) return camera;
  15941. if ( userCamera ) {
  15942. camera = userCamera;
  15943. }
  15944. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  15945. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  15946. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  15947. // Note that the new renderState won't apply until the next frame. See #18320
  15948. session.updateRenderState( {
  15949. depthNear: cameraXR.near,
  15950. depthFar: cameraXR.far
  15951. } );
  15952. _currentDepthNear = cameraXR.near;
  15953. _currentDepthFar = cameraXR.far;
  15954. }
  15955. const parent = camera.parent;
  15956. const cameras = cameraXR.cameras;
  15957. updateCamera( cameraXR, parent );
  15958. for ( let i = 0; i < cameras.length; i ++ ) {
  15959. updateCamera( cameras[ i ], parent );
  15960. }
  15961. // update projection matrix for proper view frustum culling
  15962. if ( cameras.length === 2 ) {
  15963. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  15964. } else {
  15965. // assume single camera setup (AR)
  15966. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  15967. }
  15968. // update user camera and its children
  15969. if ( userCamera ) {
  15970. updateUserCamera( cameraXR, parent );
  15971. }
  15972. return cameraXR;
  15973. };
  15974. function updateUserCamera( cameraXR, parent ) {
  15975. const camera = userCamera;
  15976. if ( parent === null ) {
  15977. camera.matrix.copy( cameraXR.matrixWorld );
  15978. } else {
  15979. camera.matrix.copy( parent.matrixWorld );
  15980. camera.matrix.invert();
  15981. camera.matrix.multiply( cameraXR.matrixWorld );
  15982. }
  15983. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15984. camera.updateMatrixWorld( true );
  15985. const children = camera.children;
  15986. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15987. children[ i ].updateMatrixWorld( true );
  15988. }
  15989. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  15990. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  15991. if ( camera.isPerspectiveCamera ) {
  15992. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  15993. camera.zoom = 1;
  15994. }
  15995. }
  15996. this.getFoveation = function () {
  15997. if ( glProjLayer === null && glBaseLayer === null ) {
  15998. return undefined;
  15999. }
  16000. return foveation;
  16001. };
  16002. this.setFoveation = function ( value ) {
  16003. // 0 = no foveation = full resolution
  16004. // 1 = maximum foveation = the edges render at lower resolution
  16005. foveation = value;
  16006. if ( glProjLayer !== null ) {
  16007. glProjLayer.fixedFoveation = value;
  16008. }
  16009. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16010. glBaseLayer.fixedFoveation = value;
  16011. }
  16012. };
  16013. // Animation Loop
  16014. let onAnimationFrameCallback = null;
  16015. function onAnimationFrame( time, frame ) {
  16016. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16017. xrFrame = frame;
  16018. if ( pose !== null ) {
  16019. const views = pose.views;
  16020. if ( glBaseLayer !== null ) {
  16021. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16022. renderer.setRenderTarget( newRenderTarget );
  16023. }
  16024. let cameraXRNeedsUpdate = false;
  16025. // check if it's necessary to rebuild cameraXR's camera list
  16026. if ( views.length !== cameraXR.cameras.length ) {
  16027. cameraXR.cameras.length = 0;
  16028. cameraXRNeedsUpdate = true;
  16029. }
  16030. for ( let i = 0; i < views.length; i ++ ) {
  16031. const view = views[ i ];
  16032. let viewport = null;
  16033. if ( glBaseLayer !== null ) {
  16034. viewport = glBaseLayer.getViewport( view );
  16035. } else {
  16036. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16037. viewport = glSubImage.viewport;
  16038. // For side-by-side projection, we only produce a single texture for both eyes.
  16039. if ( i === 0 ) {
  16040. renderer.setRenderTargetTextures(
  16041. newRenderTarget,
  16042. glSubImage.colorTexture,
  16043. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16044. renderer.setRenderTarget( newRenderTarget );
  16045. }
  16046. }
  16047. let camera = cameras[ i ];
  16048. if ( camera === undefined ) {
  16049. camera = new PerspectiveCamera();
  16050. camera.layers.enable( i );
  16051. camera.viewport = new Vector4();
  16052. cameras[ i ] = camera;
  16053. }
  16054. camera.matrix.fromArray( view.transform.matrix );
  16055. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16056. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16057. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16058. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16059. if ( i === 0 ) {
  16060. cameraXR.matrix.copy( camera.matrix );
  16061. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16062. }
  16063. if ( cameraXRNeedsUpdate === true ) {
  16064. cameraXR.cameras.push( camera );
  16065. }
  16066. }
  16067. }
  16068. //
  16069. for ( let i = 0; i < controllers.length; i ++ ) {
  16070. const inputSource = controllerInputSources[ i ];
  16071. const controller = controllers[ i ];
  16072. if ( inputSource !== null && controller !== undefined ) {
  16073. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16074. }
  16075. }
  16076. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16077. if ( frame.detectedPlanes ) {
  16078. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16079. }
  16080. xrFrame = null;
  16081. }
  16082. const animation = new WebGLAnimation();
  16083. animation.setAnimationLoop( onAnimationFrame );
  16084. this.setAnimationLoop = function ( callback ) {
  16085. onAnimationFrameCallback = callback;
  16086. };
  16087. this.dispose = function () {};
  16088. }
  16089. }
  16090. function WebGLMaterials( renderer, properties ) {
  16091. function refreshTransformUniform( map, uniform ) {
  16092. if ( map.matrixAutoUpdate === true ) {
  16093. map.updateMatrix();
  16094. }
  16095. uniform.value.copy( map.matrix );
  16096. }
  16097. function refreshFogUniforms( uniforms, fog ) {
  16098. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16099. if ( fog.isFog ) {
  16100. uniforms.fogNear.value = fog.near;
  16101. uniforms.fogFar.value = fog.far;
  16102. } else if ( fog.isFogExp2 ) {
  16103. uniforms.fogDensity.value = fog.density;
  16104. }
  16105. }
  16106. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16107. if ( material.isMeshBasicMaterial ) {
  16108. refreshUniformsCommon( uniforms, material );
  16109. } else if ( material.isMeshLambertMaterial ) {
  16110. refreshUniformsCommon( uniforms, material );
  16111. } else if ( material.isMeshToonMaterial ) {
  16112. refreshUniformsCommon( uniforms, material );
  16113. refreshUniformsToon( uniforms, material );
  16114. } else if ( material.isMeshPhongMaterial ) {
  16115. refreshUniformsCommon( uniforms, material );
  16116. refreshUniformsPhong( uniforms, material );
  16117. } else if ( material.isMeshStandardMaterial ) {
  16118. refreshUniformsCommon( uniforms, material );
  16119. refreshUniformsStandard( uniforms, material );
  16120. if ( material.isMeshPhysicalMaterial ) {
  16121. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16122. }
  16123. } else if ( material.isMeshMatcapMaterial ) {
  16124. refreshUniformsCommon( uniforms, material );
  16125. refreshUniformsMatcap( uniforms, material );
  16126. } else if ( material.isMeshDepthMaterial ) {
  16127. refreshUniformsCommon( uniforms, material );
  16128. } else if ( material.isMeshDistanceMaterial ) {
  16129. refreshUniformsCommon( uniforms, material );
  16130. refreshUniformsDistance( uniforms, material );
  16131. } else if ( material.isMeshNormalMaterial ) {
  16132. refreshUniformsCommon( uniforms, material );
  16133. } else if ( material.isLineBasicMaterial ) {
  16134. refreshUniformsLine( uniforms, material );
  16135. if ( material.isLineDashedMaterial ) {
  16136. refreshUniformsDash( uniforms, material );
  16137. }
  16138. } else if ( material.isPointsMaterial ) {
  16139. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16140. } else if ( material.isSpriteMaterial ) {
  16141. refreshUniformsSprites( uniforms, material );
  16142. } else if ( material.isShadowMaterial ) {
  16143. uniforms.color.value.copy( material.color );
  16144. uniforms.opacity.value = material.opacity;
  16145. } else if ( material.isShaderMaterial ) {
  16146. material.uniformsNeedUpdate = false; // #15581
  16147. }
  16148. }
  16149. function refreshUniformsCommon( uniforms, material ) {
  16150. uniforms.opacity.value = material.opacity;
  16151. if ( material.color ) {
  16152. uniforms.diffuse.value.copy( material.color );
  16153. }
  16154. if ( material.emissive ) {
  16155. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16156. }
  16157. if ( material.map ) {
  16158. uniforms.map.value = material.map;
  16159. refreshTransformUniform( material.map, uniforms.mapTransform );
  16160. }
  16161. if ( material.alphaMap ) {
  16162. uniforms.alphaMap.value = material.alphaMap;
  16163. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16164. }
  16165. if ( material.bumpMap ) {
  16166. uniforms.bumpMap.value = material.bumpMap;
  16167. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16168. uniforms.bumpScale.value = material.bumpScale;
  16169. if ( material.side === BackSide ) {
  16170. uniforms.bumpScale.value *= - 1;
  16171. }
  16172. }
  16173. if ( material.normalMap ) {
  16174. uniforms.normalMap.value = material.normalMap;
  16175. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16176. uniforms.normalScale.value.copy( material.normalScale );
  16177. if ( material.side === BackSide ) {
  16178. uniforms.normalScale.value.negate();
  16179. }
  16180. }
  16181. if ( material.displacementMap ) {
  16182. uniforms.displacementMap.value = material.displacementMap;
  16183. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16184. uniforms.displacementScale.value = material.displacementScale;
  16185. uniforms.displacementBias.value = material.displacementBias;
  16186. }
  16187. if ( material.emissiveMap ) {
  16188. uniforms.emissiveMap.value = material.emissiveMap;
  16189. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16190. }
  16191. if ( material.specularMap ) {
  16192. uniforms.specularMap.value = material.specularMap;
  16193. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16194. }
  16195. if ( material.alphaTest > 0 ) {
  16196. uniforms.alphaTest.value = material.alphaTest;
  16197. }
  16198. const envMap = properties.get( material ).envMap;
  16199. if ( envMap ) {
  16200. uniforms.envMap.value = envMap;
  16201. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16202. uniforms.reflectivity.value = material.reflectivity;
  16203. uniforms.ior.value = material.ior;
  16204. uniforms.refractionRatio.value = material.refractionRatio;
  16205. }
  16206. if ( material.lightMap ) {
  16207. uniforms.lightMap.value = material.lightMap;
  16208. // artist-friendly light intensity scaling factor
  16209. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  16210. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16211. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16212. }
  16213. if ( material.aoMap ) {
  16214. uniforms.aoMap.value = material.aoMap;
  16215. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16216. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16217. }
  16218. }
  16219. function refreshUniformsLine( uniforms, material ) {
  16220. uniforms.diffuse.value.copy( material.color );
  16221. uniforms.opacity.value = material.opacity;
  16222. if ( material.map ) {
  16223. uniforms.map.value = material.map;
  16224. refreshTransformUniform( material.map, uniforms.mapTransform );
  16225. }
  16226. }
  16227. function refreshUniformsDash( uniforms, material ) {
  16228. uniforms.dashSize.value = material.dashSize;
  16229. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16230. uniforms.scale.value = material.scale;
  16231. }
  16232. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16233. uniforms.diffuse.value.copy( material.color );
  16234. uniforms.opacity.value = material.opacity;
  16235. uniforms.size.value = material.size * pixelRatio;
  16236. uniforms.scale.value = height * 0.5;
  16237. if ( material.map ) {
  16238. uniforms.map.value = material.map;
  16239. refreshTransformUniform( material.map, uniforms.uvTransform );
  16240. }
  16241. if ( material.alphaMap ) {
  16242. uniforms.alphaMap.value = material.alphaMap;
  16243. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16244. }
  16245. if ( material.alphaTest > 0 ) {
  16246. uniforms.alphaTest.value = material.alphaTest;
  16247. }
  16248. }
  16249. function refreshUniformsSprites( uniforms, material ) {
  16250. uniforms.diffuse.value.copy( material.color );
  16251. uniforms.opacity.value = material.opacity;
  16252. uniforms.rotation.value = material.rotation;
  16253. if ( material.map ) {
  16254. uniforms.map.value = material.map;
  16255. refreshTransformUniform( material.map, uniforms.mapTransform );
  16256. }
  16257. if ( material.alphaMap ) {
  16258. uniforms.alphaMap.value = material.alphaMap;
  16259. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16260. }
  16261. if ( material.alphaTest > 0 ) {
  16262. uniforms.alphaTest.value = material.alphaTest;
  16263. }
  16264. }
  16265. function refreshUniformsPhong( uniforms, material ) {
  16266. uniforms.specular.value.copy( material.specular );
  16267. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16268. }
  16269. function refreshUniformsToon( uniforms, material ) {
  16270. if ( material.gradientMap ) {
  16271. uniforms.gradientMap.value = material.gradientMap;
  16272. }
  16273. }
  16274. function refreshUniformsStandard( uniforms, material ) {
  16275. uniforms.metalness.value = material.metalness;
  16276. if ( material.metalnessMap ) {
  16277. uniforms.metalnessMap.value = material.metalnessMap;
  16278. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16279. }
  16280. uniforms.roughness.value = material.roughness;
  16281. if ( material.roughnessMap ) {
  16282. uniforms.roughnessMap.value = material.roughnessMap;
  16283. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16284. }
  16285. const envMap = properties.get( material ).envMap;
  16286. if ( envMap ) {
  16287. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16288. uniforms.envMapIntensity.value = material.envMapIntensity;
  16289. }
  16290. }
  16291. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16292. uniforms.ior.value = material.ior; // also part of uniforms common
  16293. if ( material.sheen > 0 ) {
  16294. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16295. uniforms.sheenRoughness.value = material.sheenRoughness;
  16296. if ( material.sheenColorMap ) {
  16297. uniforms.sheenColorMap.value = material.sheenColorMap;
  16298. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16299. }
  16300. if ( material.sheenRoughnessMap ) {
  16301. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16302. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16303. }
  16304. }
  16305. if ( material.clearcoat > 0 ) {
  16306. uniforms.clearcoat.value = material.clearcoat;
  16307. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16308. if ( material.clearcoatMap ) {
  16309. uniforms.clearcoatMap.value = material.clearcoatMap;
  16310. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16311. }
  16312. if ( material.clearcoatRoughnessMap ) {
  16313. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16314. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16315. }
  16316. if ( material.clearcoatNormalMap ) {
  16317. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16318. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16319. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16320. if ( material.side === BackSide ) {
  16321. uniforms.clearcoatNormalScale.value.negate();
  16322. }
  16323. }
  16324. }
  16325. if ( material.iridescence > 0 ) {
  16326. uniforms.iridescence.value = material.iridescence;
  16327. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16328. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16329. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16330. if ( material.iridescenceMap ) {
  16331. uniforms.iridescenceMap.value = material.iridescenceMap;
  16332. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16333. }
  16334. if ( material.iridescenceThicknessMap ) {
  16335. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16336. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16337. }
  16338. }
  16339. if ( material.transmission > 0 ) {
  16340. uniforms.transmission.value = material.transmission;
  16341. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16342. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16343. if ( material.transmissionMap ) {
  16344. uniforms.transmissionMap.value = material.transmissionMap;
  16345. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16346. }
  16347. uniforms.thickness.value = material.thickness;
  16348. if ( material.thicknessMap ) {
  16349. uniforms.thicknessMap.value = material.thicknessMap;
  16350. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16351. }
  16352. uniforms.attenuationDistance.value = material.attenuationDistance;
  16353. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16354. }
  16355. if ( material.anisotropy > 0 ) {
  16356. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16357. if ( material.anisotropyMap ) {
  16358. uniforms.anisotropyMap.value = material.anisotropyMap;
  16359. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16360. }
  16361. }
  16362. uniforms.specularIntensity.value = material.specularIntensity;
  16363. uniforms.specularColor.value.copy( material.specularColor );
  16364. if ( material.specularColorMap ) {
  16365. uniforms.specularColorMap.value = material.specularColorMap;
  16366. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16367. }
  16368. if ( material.specularIntensityMap ) {
  16369. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16370. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16371. }
  16372. }
  16373. function refreshUniformsMatcap( uniforms, material ) {
  16374. if ( material.matcap ) {
  16375. uniforms.matcap.value = material.matcap;
  16376. }
  16377. }
  16378. function refreshUniformsDistance( uniforms, material ) {
  16379. const light = properties.get( material ).light;
  16380. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16381. uniforms.nearDistance.value = light.shadow.camera.near;
  16382. uniforms.farDistance.value = light.shadow.camera.far;
  16383. }
  16384. return {
  16385. refreshFogUniforms: refreshFogUniforms,
  16386. refreshMaterialUniforms: refreshMaterialUniforms
  16387. };
  16388. }
  16389. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16390. let buffers = {};
  16391. let updateList = {};
  16392. let allocatedBindingPoints = [];
  16393. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  16394. function bind( uniformsGroup, program ) {
  16395. const webglProgram = program.program;
  16396. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16397. }
  16398. function update( uniformsGroup, program ) {
  16399. let buffer = buffers[ uniformsGroup.id ];
  16400. if ( buffer === undefined ) {
  16401. prepareUniformsGroup( uniformsGroup );
  16402. buffer = createBuffer( uniformsGroup );
  16403. buffers[ uniformsGroup.id ] = buffer;
  16404. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16405. }
  16406. // ensure to update the binding points/block indices mapping for this program
  16407. const webglProgram = program.program;
  16408. state.updateUBOMapping( uniformsGroup, webglProgram );
  16409. // update UBO once per frame
  16410. const frame = info.render.frame;
  16411. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16412. updateBufferData( uniformsGroup );
  16413. updateList[ uniformsGroup.id ] = frame;
  16414. }
  16415. }
  16416. function createBuffer( uniformsGroup ) {
  16417. // the setup of an UBO is independent of a particular shader program but global
  16418. const bindingPointIndex = allocateBindingPointIndex();
  16419. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16420. const buffer = gl.createBuffer();
  16421. const size = uniformsGroup.__size;
  16422. const usage = uniformsGroup.usage;
  16423. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16424. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16425. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16426. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16427. return buffer;
  16428. }
  16429. function allocateBindingPointIndex() {
  16430. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16431. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16432. allocatedBindingPoints.push( i );
  16433. return i;
  16434. }
  16435. }
  16436. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16437. return 0;
  16438. }
  16439. function updateBufferData( uniformsGroup ) {
  16440. const buffer = buffers[ uniformsGroup.id ];
  16441. const uniforms = uniformsGroup.uniforms;
  16442. const cache = uniformsGroup.__cache;
  16443. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16444. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16445. const uniform = uniforms[ i ];
  16446. // partly update the buffer if necessary
  16447. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16448. const offset = uniform.__offset;
  16449. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16450. let arrayOffset = 0;
  16451. for ( let i = 0; i < values.length; i ++ ) {
  16452. const value = values[ i ];
  16453. const info = getUniformSize( value );
  16454. if ( typeof value === 'number' ) {
  16455. uniform.__data[ 0 ] = value;
  16456. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16457. } else if ( value.isMatrix3 ) {
  16458. // manually converting 3x3 to 3x4
  16459. uniform.__data[ 0 ] = value.elements[ 0 ];
  16460. uniform.__data[ 1 ] = value.elements[ 1 ];
  16461. uniform.__data[ 2 ] = value.elements[ 2 ];
  16462. uniform.__data[ 3 ] = value.elements[ 0 ];
  16463. uniform.__data[ 4 ] = value.elements[ 3 ];
  16464. uniform.__data[ 5 ] = value.elements[ 4 ];
  16465. uniform.__data[ 6 ] = value.elements[ 5 ];
  16466. uniform.__data[ 7 ] = value.elements[ 0 ];
  16467. uniform.__data[ 8 ] = value.elements[ 6 ];
  16468. uniform.__data[ 9 ] = value.elements[ 7 ];
  16469. uniform.__data[ 10 ] = value.elements[ 8 ];
  16470. uniform.__data[ 11 ] = value.elements[ 0 ];
  16471. } else {
  16472. value.toArray( uniform.__data, arrayOffset );
  16473. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16474. }
  16475. }
  16476. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16477. }
  16478. }
  16479. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16480. }
  16481. function hasUniformChanged( uniform, index, cache ) {
  16482. const value = uniform.value;
  16483. if ( cache[ index ] === undefined ) {
  16484. // cache entry does not exist so far
  16485. if ( typeof value === 'number' ) {
  16486. cache[ index ] = value;
  16487. } else {
  16488. const values = Array.isArray( value ) ? value : [ value ];
  16489. const tempValues = [];
  16490. for ( let i = 0; i < values.length; i ++ ) {
  16491. tempValues.push( values[ i ].clone() );
  16492. }
  16493. cache[ index ] = tempValues;
  16494. }
  16495. return true;
  16496. } else {
  16497. // compare current value with cached entry
  16498. if ( typeof value === 'number' ) {
  16499. if ( cache[ index ] !== value ) {
  16500. cache[ index ] = value;
  16501. return true;
  16502. }
  16503. } else {
  16504. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16505. const values = Array.isArray( value ) ? value : [ value ];
  16506. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16507. const cachedObject = cachedObjects[ i ];
  16508. if ( cachedObject.equals( values[ i ] ) === false ) {
  16509. cachedObject.copy( values[ i ] );
  16510. return true;
  16511. }
  16512. }
  16513. }
  16514. }
  16515. return false;
  16516. }
  16517. function prepareUniformsGroup( uniformsGroup ) {
  16518. // determine total buffer size according to the STD140 layout
  16519. // Hint: STD140 is the only supported layout in WebGL 2
  16520. const uniforms = uniformsGroup.uniforms;
  16521. let offset = 0; // global buffer offset in bytes
  16522. const chunkSize = 16; // size of a chunk in bytes
  16523. let chunkOffset = 0; // offset within a single chunk in bytes
  16524. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16525. const uniform = uniforms[ i ];
  16526. const infos = {
  16527. boundary: 0, // bytes
  16528. storage: 0 // bytes
  16529. };
  16530. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16531. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16532. const value = values[ j ];
  16533. const info = getUniformSize( value );
  16534. infos.boundary += info.boundary;
  16535. infos.storage += info.storage;
  16536. }
  16537. // the following two properties will be used for partial buffer updates
  16538. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16539. uniform.__offset = offset;
  16540. //
  16541. if ( i > 0 ) {
  16542. chunkOffset = offset % chunkSize;
  16543. const remainingSizeInChunk = chunkSize - chunkOffset;
  16544. // check for chunk overflow
  16545. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16546. // add padding and adjust offset
  16547. offset += ( chunkSize - chunkOffset );
  16548. uniform.__offset = offset;
  16549. }
  16550. }
  16551. offset += infos.storage;
  16552. }
  16553. // ensure correct final padding
  16554. chunkOffset = offset % chunkSize;
  16555. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16556. //
  16557. uniformsGroup.__size = offset;
  16558. uniformsGroup.__cache = {};
  16559. return this;
  16560. }
  16561. function getUniformSize( value ) {
  16562. const info = {
  16563. boundary: 0, // bytes
  16564. storage: 0 // bytes
  16565. };
  16566. // determine sizes according to STD140
  16567. if ( typeof value === 'number' ) {
  16568. // float/int
  16569. info.boundary = 4;
  16570. info.storage = 4;
  16571. } else if ( value.isVector2 ) {
  16572. // vec2
  16573. info.boundary = 8;
  16574. info.storage = 8;
  16575. } else if ( value.isVector3 || value.isColor ) {
  16576. // vec3
  16577. info.boundary = 16;
  16578. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16579. } else if ( value.isVector4 ) {
  16580. // vec4
  16581. info.boundary = 16;
  16582. info.storage = 16;
  16583. } else if ( value.isMatrix3 ) {
  16584. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16585. info.boundary = 48;
  16586. info.storage = 48;
  16587. } else if ( value.isMatrix4 ) {
  16588. // mat4
  16589. info.boundary = 64;
  16590. info.storage = 64;
  16591. } else if ( value.isTexture ) {
  16592. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16593. } else {
  16594. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16595. }
  16596. return info;
  16597. }
  16598. function onUniformsGroupsDispose( event ) {
  16599. const uniformsGroup = event.target;
  16600. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16601. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16602. allocatedBindingPoints.splice( index, 1 );
  16603. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16604. delete buffers[ uniformsGroup.id ];
  16605. delete updateList[ uniformsGroup.id ];
  16606. }
  16607. function dispose() {
  16608. for ( const id in buffers ) {
  16609. gl.deleteBuffer( buffers[ id ] );
  16610. }
  16611. allocatedBindingPoints = [];
  16612. buffers = {};
  16613. updateList = {};
  16614. }
  16615. return {
  16616. bind: bind,
  16617. update: update,
  16618. dispose: dispose
  16619. };
  16620. }
  16621. function createCanvasElement() {
  16622. const canvas = createElementNS( 'canvas' );
  16623. canvas.style.display = 'block';
  16624. return canvas;
  16625. }
  16626. class WebGLRenderer {
  16627. constructor( parameters = {} ) {
  16628. const {
  16629. canvas = createCanvasElement(),
  16630. context = null,
  16631. depth = true,
  16632. stencil = true,
  16633. alpha = false,
  16634. antialias = false,
  16635. premultipliedAlpha = true,
  16636. preserveDrawingBuffer = false,
  16637. powerPreference = 'default',
  16638. failIfMajorPerformanceCaveat = false,
  16639. } = parameters;
  16640. this.isWebGLRenderer = true;
  16641. let _alpha;
  16642. if ( context !== null ) {
  16643. _alpha = context.getContextAttributes().alpha;
  16644. } else {
  16645. _alpha = alpha;
  16646. }
  16647. const uintClearColor = new Uint32Array( 4 );
  16648. const intClearColor = new Int32Array( 4 );
  16649. let currentRenderList = null;
  16650. let currentRenderState = null;
  16651. // render() can be called from within a callback triggered by another render.
  16652. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16653. const renderListStack = [];
  16654. const renderStateStack = [];
  16655. // public properties
  16656. this.domElement = canvas;
  16657. // Debug configuration container
  16658. this.debug = {
  16659. /**
  16660. * Enables error checking and reporting when shader programs are being compiled
  16661. * @type {boolean}
  16662. */
  16663. checkShaderErrors: true,
  16664. /**
  16665. * Callback for custom error reporting.
  16666. * @type {?Function}
  16667. */
  16668. onShaderError: null
  16669. };
  16670. // clearing
  16671. this.autoClear = true;
  16672. this.autoClearColor = true;
  16673. this.autoClearDepth = true;
  16674. this.autoClearStencil = true;
  16675. // scene graph
  16676. this.sortObjects = true;
  16677. // user-defined clipping
  16678. this.clippingPlanes = [];
  16679. this.localClippingEnabled = false;
  16680. // physically based shading
  16681. this.outputColorSpace = SRGBColorSpace;
  16682. // physical lights
  16683. this.useLegacyLights = true;
  16684. // tone mapping
  16685. this.toneMapping = NoToneMapping;
  16686. this.toneMappingExposure = 1.0;
  16687. // internal properties
  16688. const _this = this;
  16689. let _isContextLost = false;
  16690. // internal state cache
  16691. let _currentActiveCubeFace = 0;
  16692. let _currentActiveMipmapLevel = 0;
  16693. let _currentRenderTarget = null;
  16694. let _currentMaterialId = - 1;
  16695. let _currentCamera = null;
  16696. const _currentViewport = new Vector4();
  16697. const _currentScissor = new Vector4();
  16698. let _currentScissorTest = null;
  16699. const _currentClearColor = new Color( 0x000000 );
  16700. let _currentClearAlpha = 0;
  16701. //
  16702. let _width = canvas.width;
  16703. let _height = canvas.height;
  16704. let _pixelRatio = 1;
  16705. let _opaqueSort = null;
  16706. let _transparentSort = null;
  16707. const _viewport = new Vector4( 0, 0, _width, _height );
  16708. const _scissor = new Vector4( 0, 0, _width, _height );
  16709. let _scissorTest = false;
  16710. // frustum
  16711. const _frustum = new Frustum();
  16712. // clipping
  16713. let _clippingEnabled = false;
  16714. let _localClippingEnabled = false;
  16715. // transmission
  16716. let _transmissionRenderTarget = null;
  16717. // camera matrices cache
  16718. const _projScreenMatrix = new Matrix4();
  16719. const _vector2 = new Vector2();
  16720. const _vector3 = new Vector3();
  16721. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16722. function getTargetPixelRatio() {
  16723. return _currentRenderTarget === null ? _pixelRatio : 1;
  16724. }
  16725. // initialize
  16726. let _gl = context;
  16727. function getContext( contextNames, contextAttributes ) {
  16728. for ( let i = 0; i < contextNames.length; i ++ ) {
  16729. const contextName = contextNames[ i ];
  16730. const context = canvas.getContext( contextName, contextAttributes );
  16731. if ( context !== null ) return context;
  16732. }
  16733. return null;
  16734. }
  16735. try {
  16736. const contextAttributes = {
  16737. alpha: true,
  16738. depth,
  16739. stencil,
  16740. antialias,
  16741. premultipliedAlpha,
  16742. preserveDrawingBuffer,
  16743. powerPreference,
  16744. failIfMajorPerformanceCaveat,
  16745. };
  16746. // OffscreenCanvas does not have setAttribute, see #22811
  16747. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16748. // event listeners must be registered before WebGL context is created, see #12753
  16749. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16750. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16751. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16752. if ( _gl === null ) {
  16753. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16754. if ( _this.isWebGL1Renderer === true ) {
  16755. contextNames.shift();
  16756. }
  16757. _gl = getContext( contextNames, contextAttributes );
  16758. if ( _gl === null ) {
  16759. if ( getContext( contextNames ) ) {
  16760. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16761. } else {
  16762. throw new Error( 'Error creating WebGL context.' );
  16763. }
  16764. }
  16765. }
  16766. if ( _gl instanceof WebGLRenderingContext ) { // @deprecated, r153
  16767. console.warn( 'THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163.' );
  16768. }
  16769. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16770. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16771. _gl.getShaderPrecisionFormat = function () {
  16772. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16773. };
  16774. }
  16775. } catch ( error ) {
  16776. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16777. throw error;
  16778. }
  16779. let extensions, capabilities, state, info;
  16780. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16781. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16782. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16783. let utils, bindingStates, uniformsGroups;
  16784. function initGLContext() {
  16785. extensions = new WebGLExtensions( _gl );
  16786. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16787. extensions.init( capabilities );
  16788. utils = new WebGLUtils( _gl, extensions, capabilities );
  16789. state = new WebGLState( _gl, extensions, capabilities );
  16790. info = new WebGLInfo( _gl );
  16791. properties = new WebGLProperties();
  16792. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16793. cubemaps = new WebGLCubeMaps( _this );
  16794. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16795. attributes = new WebGLAttributes( _gl, capabilities );
  16796. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16797. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16798. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16799. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16800. clipping = new WebGLClipping( properties );
  16801. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16802. materials = new WebGLMaterials( _this, properties );
  16803. renderLists = new WebGLRenderLists();
  16804. renderStates = new WebGLRenderStates( extensions, capabilities );
  16805. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16806. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16807. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16808. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16809. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16810. info.programs = programCache.programs;
  16811. _this.capabilities = capabilities;
  16812. _this.extensions = extensions;
  16813. _this.properties = properties;
  16814. _this.renderLists = renderLists;
  16815. _this.shadowMap = shadowMap;
  16816. _this.state = state;
  16817. _this.info = info;
  16818. }
  16819. initGLContext();
  16820. // xr
  16821. const xr = new WebXRManager( _this, _gl );
  16822. this.xr = xr;
  16823. // API
  16824. this.getContext = function () {
  16825. return _gl;
  16826. };
  16827. this.getContextAttributes = function () {
  16828. return _gl.getContextAttributes();
  16829. };
  16830. this.forceContextLoss = function () {
  16831. const extension = extensions.get( 'WEBGL_lose_context' );
  16832. if ( extension ) extension.loseContext();
  16833. };
  16834. this.forceContextRestore = function () {
  16835. const extension = extensions.get( 'WEBGL_lose_context' );
  16836. if ( extension ) extension.restoreContext();
  16837. };
  16838. this.getPixelRatio = function () {
  16839. return _pixelRatio;
  16840. };
  16841. this.setPixelRatio = function ( value ) {
  16842. if ( value === undefined ) return;
  16843. _pixelRatio = value;
  16844. this.setSize( _width, _height, false );
  16845. };
  16846. this.getSize = function ( target ) {
  16847. return target.set( _width, _height );
  16848. };
  16849. this.setSize = function ( width, height, updateStyle = true ) {
  16850. if ( xr.isPresenting ) {
  16851. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16852. return;
  16853. }
  16854. _width = width;
  16855. _height = height;
  16856. canvas.width = Math.floor( width * _pixelRatio );
  16857. canvas.height = Math.floor( height * _pixelRatio );
  16858. if ( updateStyle === true ) {
  16859. canvas.style.width = width + 'px';
  16860. canvas.style.height = height + 'px';
  16861. }
  16862. this.setViewport( 0, 0, width, height );
  16863. };
  16864. this.getDrawingBufferSize = function ( target ) {
  16865. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16866. };
  16867. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16868. _width = width;
  16869. _height = height;
  16870. _pixelRatio = pixelRatio;
  16871. canvas.width = Math.floor( width * pixelRatio );
  16872. canvas.height = Math.floor( height * pixelRatio );
  16873. this.setViewport( 0, 0, width, height );
  16874. };
  16875. this.getCurrentViewport = function ( target ) {
  16876. return target.copy( _currentViewport );
  16877. };
  16878. this.getViewport = function ( target ) {
  16879. return target.copy( _viewport );
  16880. };
  16881. this.setViewport = function ( x, y, width, height ) {
  16882. if ( x.isVector4 ) {
  16883. _viewport.set( x.x, x.y, x.z, x.w );
  16884. } else {
  16885. _viewport.set( x, y, width, height );
  16886. }
  16887. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16888. };
  16889. this.getScissor = function ( target ) {
  16890. return target.copy( _scissor );
  16891. };
  16892. this.setScissor = function ( x, y, width, height ) {
  16893. if ( x.isVector4 ) {
  16894. _scissor.set( x.x, x.y, x.z, x.w );
  16895. } else {
  16896. _scissor.set( x, y, width, height );
  16897. }
  16898. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16899. };
  16900. this.getScissorTest = function () {
  16901. return _scissorTest;
  16902. };
  16903. this.setScissorTest = function ( boolean ) {
  16904. state.setScissorTest( _scissorTest = boolean );
  16905. };
  16906. this.setOpaqueSort = function ( method ) {
  16907. _opaqueSort = method;
  16908. };
  16909. this.setTransparentSort = function ( method ) {
  16910. _transparentSort = method;
  16911. };
  16912. // Clearing
  16913. this.getClearColor = function ( target ) {
  16914. return target.copy( background.getClearColor() );
  16915. };
  16916. this.setClearColor = function () {
  16917. background.setClearColor.apply( background, arguments );
  16918. };
  16919. this.getClearAlpha = function () {
  16920. return background.getClearAlpha();
  16921. };
  16922. this.setClearAlpha = function () {
  16923. background.setClearAlpha.apply( background, arguments );
  16924. };
  16925. this.clear = function ( color = true, depth = true, stencil = true ) {
  16926. let bits = 0;
  16927. if ( color ) {
  16928. // check if we're trying to clear an integer target
  16929. let isIntegerFormat = false;
  16930. if ( _currentRenderTarget !== null ) {
  16931. const targetFormat = _currentRenderTarget.texture.format;
  16932. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  16933. targetFormat === RGIntegerFormat ||
  16934. targetFormat === RedIntegerFormat;
  16935. }
  16936. // use the appropriate clear functions to clear the target if it's a signed
  16937. // or unsigned integer target
  16938. if ( isIntegerFormat ) {
  16939. const targetType = _currentRenderTarget.texture.type;
  16940. const isUnsignedType = targetType === UnsignedByteType ||
  16941. targetType === UnsignedIntType ||
  16942. targetType === UnsignedShortType ||
  16943. targetType === UnsignedInt248Type ||
  16944. targetType === UnsignedShort4444Type ||
  16945. targetType === UnsignedShort5551Type;
  16946. const clearColor = background.getClearColor();
  16947. const a = background.getClearAlpha();
  16948. const r = clearColor.r;
  16949. const g = clearColor.g;
  16950. const b = clearColor.b;
  16951. const __webglFramebuffer = properties.get( _currentRenderTarget ).__webglFramebuffer;
  16952. if ( isUnsignedType ) {
  16953. uintClearColor[ 0 ] = r;
  16954. uintClearColor[ 1 ] = g;
  16955. uintClearColor[ 2 ] = b;
  16956. uintClearColor[ 3 ] = a;
  16957. _gl.clearBufferuiv( _gl.COLOR, __webglFramebuffer, uintClearColor );
  16958. } else {
  16959. intClearColor[ 0 ] = r;
  16960. intClearColor[ 1 ] = g;
  16961. intClearColor[ 2 ] = b;
  16962. intClearColor[ 3 ] = a;
  16963. _gl.clearBufferiv( _gl.COLOR, __webglFramebuffer, intClearColor );
  16964. }
  16965. } else {
  16966. bits |= _gl.COLOR_BUFFER_BIT;
  16967. }
  16968. }
  16969. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16970. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16971. _gl.clear( bits );
  16972. };
  16973. this.clearColor = function () {
  16974. this.clear( true, false, false );
  16975. };
  16976. this.clearDepth = function () {
  16977. this.clear( false, true, false );
  16978. };
  16979. this.clearStencil = function () {
  16980. this.clear( false, false, true );
  16981. };
  16982. //
  16983. this.dispose = function () {
  16984. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16985. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16986. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16987. renderLists.dispose();
  16988. renderStates.dispose();
  16989. properties.dispose();
  16990. cubemaps.dispose();
  16991. cubeuvmaps.dispose();
  16992. objects.dispose();
  16993. bindingStates.dispose();
  16994. uniformsGroups.dispose();
  16995. programCache.dispose();
  16996. xr.dispose();
  16997. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16998. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16999. if ( _transmissionRenderTarget ) {
  17000. _transmissionRenderTarget.dispose();
  17001. _transmissionRenderTarget = null;
  17002. }
  17003. animation.stop();
  17004. };
  17005. // Events
  17006. function onContextLost( event ) {
  17007. event.preventDefault();
  17008. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17009. _isContextLost = true;
  17010. }
  17011. function onContextRestore( /* event */ ) {
  17012. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17013. _isContextLost = false;
  17014. const infoAutoReset = info.autoReset;
  17015. const shadowMapEnabled = shadowMap.enabled;
  17016. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17017. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17018. const shadowMapType = shadowMap.type;
  17019. initGLContext();
  17020. info.autoReset = infoAutoReset;
  17021. shadowMap.enabled = shadowMapEnabled;
  17022. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17023. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17024. shadowMap.type = shadowMapType;
  17025. }
  17026. function onContextCreationError( event ) {
  17027. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17028. }
  17029. function onMaterialDispose( event ) {
  17030. const material = event.target;
  17031. material.removeEventListener( 'dispose', onMaterialDispose );
  17032. deallocateMaterial( material );
  17033. }
  17034. // Buffer deallocation
  17035. function deallocateMaterial( material ) {
  17036. releaseMaterialProgramReferences( material );
  17037. properties.remove( material );
  17038. }
  17039. function releaseMaterialProgramReferences( material ) {
  17040. const programs = properties.get( material ).programs;
  17041. if ( programs !== undefined ) {
  17042. programs.forEach( function ( program ) {
  17043. programCache.releaseProgram( program );
  17044. } );
  17045. if ( material.isShaderMaterial ) {
  17046. programCache.releaseShaderCache( material );
  17047. }
  17048. }
  17049. }
  17050. // Buffer rendering
  17051. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17052. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17053. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17054. const program = setProgram( camera, scene, geometry, material, object );
  17055. state.setMaterial( material, frontFaceCW );
  17056. //
  17057. let index = geometry.index;
  17058. let rangeFactor = 1;
  17059. if ( material.wireframe === true ) {
  17060. index = geometries.getWireframeAttribute( geometry );
  17061. rangeFactor = 2;
  17062. }
  17063. //
  17064. const drawRange = geometry.drawRange;
  17065. const position = geometry.attributes.position;
  17066. let drawStart = drawRange.start * rangeFactor;
  17067. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17068. if ( group !== null ) {
  17069. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17070. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17071. }
  17072. if ( index !== null ) {
  17073. drawStart = Math.max( drawStart, 0 );
  17074. drawEnd = Math.min( drawEnd, index.count );
  17075. } else if ( position !== undefined && position !== null ) {
  17076. drawStart = Math.max( drawStart, 0 );
  17077. drawEnd = Math.min( drawEnd, position.count );
  17078. }
  17079. const drawCount = drawEnd - drawStart;
  17080. if ( drawCount < 0 || drawCount === Infinity ) return;
  17081. //
  17082. bindingStates.setup( object, material, program, geometry, index );
  17083. let attribute;
  17084. let renderer = bufferRenderer;
  17085. if ( index !== null ) {
  17086. attribute = attributes.get( index );
  17087. renderer = indexedBufferRenderer;
  17088. renderer.setIndex( attribute );
  17089. }
  17090. //
  17091. if ( object.isMesh ) {
  17092. if ( material.wireframe === true ) {
  17093. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17094. renderer.setMode( _gl.LINES );
  17095. } else {
  17096. renderer.setMode( _gl.TRIANGLES );
  17097. }
  17098. } else if ( object.isLine ) {
  17099. let lineWidth = material.linewidth;
  17100. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17101. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17102. if ( object.isLineSegments ) {
  17103. renderer.setMode( _gl.LINES );
  17104. } else if ( object.isLineLoop ) {
  17105. renderer.setMode( _gl.LINE_LOOP );
  17106. } else {
  17107. renderer.setMode( _gl.LINE_STRIP );
  17108. }
  17109. } else if ( object.isPoints ) {
  17110. renderer.setMode( _gl.POINTS );
  17111. } else if ( object.isSprite ) {
  17112. renderer.setMode( _gl.TRIANGLES );
  17113. }
  17114. if ( object.isInstancedMesh ) {
  17115. renderer.renderInstances( drawStart, drawCount, object.count );
  17116. } else if ( geometry.isInstancedBufferGeometry ) {
  17117. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17118. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17119. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17120. } else {
  17121. renderer.render( drawStart, drawCount );
  17122. }
  17123. };
  17124. // Compile
  17125. this.compile = function ( scene, camera ) {
  17126. function prepare( material, scene, object ) {
  17127. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17128. material.side = BackSide;
  17129. material.needsUpdate = true;
  17130. getProgram( material, scene, object );
  17131. material.side = FrontSide;
  17132. material.needsUpdate = true;
  17133. getProgram( material, scene, object );
  17134. material.side = DoubleSide;
  17135. } else {
  17136. getProgram( material, scene, object );
  17137. }
  17138. }
  17139. currentRenderState = renderStates.get( scene );
  17140. currentRenderState.init();
  17141. renderStateStack.push( currentRenderState );
  17142. scene.traverseVisible( function ( object ) {
  17143. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17144. currentRenderState.pushLight( object );
  17145. if ( object.castShadow ) {
  17146. currentRenderState.pushShadow( object );
  17147. }
  17148. }
  17149. } );
  17150. currentRenderState.setupLights( _this.useLegacyLights );
  17151. scene.traverse( function ( object ) {
  17152. const material = object.material;
  17153. if ( material ) {
  17154. if ( Array.isArray( material ) ) {
  17155. for ( let i = 0; i < material.length; i ++ ) {
  17156. const material2 = material[ i ];
  17157. prepare( material2, scene, object );
  17158. }
  17159. } else {
  17160. prepare( material, scene, object );
  17161. }
  17162. }
  17163. } );
  17164. renderStateStack.pop();
  17165. currentRenderState = null;
  17166. };
  17167. // Animation Loop
  17168. let onAnimationFrameCallback = null;
  17169. function onAnimationFrame( time ) {
  17170. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17171. }
  17172. function onXRSessionStart() {
  17173. animation.stop();
  17174. }
  17175. function onXRSessionEnd() {
  17176. animation.start();
  17177. }
  17178. const animation = new WebGLAnimation();
  17179. animation.setAnimationLoop( onAnimationFrame );
  17180. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17181. this.setAnimationLoop = function ( callback ) {
  17182. onAnimationFrameCallback = callback;
  17183. xr.setAnimationLoop( callback );
  17184. ( callback === null ) ? animation.stop() : animation.start();
  17185. };
  17186. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17187. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17188. // Rendering
  17189. this.render = function ( scene, camera ) {
  17190. if ( camera !== undefined && camera.isCamera !== true ) {
  17191. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17192. return;
  17193. }
  17194. if ( _isContextLost === true ) return;
  17195. // update scene graph
  17196. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17197. // update camera matrices and frustum
  17198. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17199. if ( xr.enabled === true && xr.isPresenting === true ) {
  17200. camera = xr.updateCameraXR( camera ); // use XR camera for rendering
  17201. }
  17202. //
  17203. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17204. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17205. currentRenderState.init();
  17206. renderStateStack.push( currentRenderState );
  17207. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17208. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17209. _localClippingEnabled = this.localClippingEnabled;
  17210. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17211. currentRenderList = renderLists.get( scene, renderListStack.length );
  17212. currentRenderList.init();
  17213. renderListStack.push( currentRenderList );
  17214. projectObject( scene, camera, 0, _this.sortObjects );
  17215. currentRenderList.finish();
  17216. if ( _this.sortObjects === true ) {
  17217. currentRenderList.sort( _opaqueSort, _transparentSort );
  17218. }
  17219. //
  17220. if ( _clippingEnabled === true ) clipping.beginShadows();
  17221. const shadowsArray = currentRenderState.state.shadowsArray;
  17222. shadowMap.render( shadowsArray, scene, camera );
  17223. if ( _clippingEnabled === true ) clipping.endShadows();
  17224. //
  17225. if ( this.info.autoReset === true ) this.info.reset();
  17226. this.info.render.frame ++;
  17227. //
  17228. background.render( currentRenderList, scene );
  17229. // render scene
  17230. currentRenderState.setupLights( _this.useLegacyLights );
  17231. if ( camera.isArrayCamera ) {
  17232. const cameras = camera.cameras;
  17233. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17234. const camera2 = cameras[ i ];
  17235. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17236. }
  17237. } else {
  17238. renderScene( currentRenderList, scene, camera );
  17239. }
  17240. //
  17241. if ( _currentRenderTarget !== null ) {
  17242. // resolve multisample renderbuffers to a single-sample texture if necessary
  17243. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17244. // Generate mipmap if we're using any kind of mipmap filtering
  17245. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17246. }
  17247. //
  17248. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17249. // _gl.finish();
  17250. bindingStates.resetDefaultState();
  17251. _currentMaterialId = - 1;
  17252. _currentCamera = null;
  17253. renderStateStack.pop();
  17254. if ( renderStateStack.length > 0 ) {
  17255. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17256. } else {
  17257. currentRenderState = null;
  17258. }
  17259. renderListStack.pop();
  17260. if ( renderListStack.length > 0 ) {
  17261. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17262. } else {
  17263. currentRenderList = null;
  17264. }
  17265. };
  17266. function projectObject( object, camera, groupOrder, sortObjects ) {
  17267. if ( object.visible === false ) return;
  17268. const visible = object.layers.test( camera.layers );
  17269. if ( visible ) {
  17270. if ( object.isGroup ) {
  17271. groupOrder = object.renderOrder;
  17272. } else if ( object.isLOD ) {
  17273. if ( object.autoUpdate === true ) object.update( camera );
  17274. } else if ( object.isLight ) {
  17275. currentRenderState.pushLight( object );
  17276. if ( object.castShadow ) {
  17277. currentRenderState.pushShadow( object );
  17278. }
  17279. } else if ( object.isSprite ) {
  17280. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17281. if ( sortObjects ) {
  17282. _vector3.setFromMatrixPosition( object.matrixWorld )
  17283. .applyMatrix4( _projScreenMatrix );
  17284. }
  17285. const geometry = objects.update( object );
  17286. const material = object.material;
  17287. if ( material.visible ) {
  17288. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17289. }
  17290. }
  17291. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17292. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17293. if ( object.isSkinnedMesh ) {
  17294. // update skeleton only once in a frame
  17295. if ( object.skeleton.frame !== info.render.frame ) {
  17296. object.skeleton.update();
  17297. object.skeleton.frame = info.render.frame;
  17298. }
  17299. }
  17300. const geometry = objects.update( object );
  17301. const material = object.material;
  17302. if ( sortObjects ) {
  17303. if ( object.boundingSphere !== undefined ) {
  17304. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17305. _vector3.copy( object.boundingSphere.center );
  17306. } else {
  17307. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17308. _vector3.copy( geometry.boundingSphere.center );
  17309. }
  17310. _vector3
  17311. .applyMatrix4( object.matrixWorld )
  17312. .applyMatrix4( _projScreenMatrix );
  17313. }
  17314. if ( Array.isArray( material ) ) {
  17315. const groups = geometry.groups;
  17316. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17317. const group = groups[ i ];
  17318. const groupMaterial = material[ group.materialIndex ];
  17319. if ( groupMaterial && groupMaterial.visible ) {
  17320. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17321. }
  17322. }
  17323. } else if ( material.visible ) {
  17324. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17325. }
  17326. }
  17327. }
  17328. }
  17329. const children = object.children;
  17330. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17331. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17332. }
  17333. }
  17334. function renderScene( currentRenderList, scene, camera, viewport ) {
  17335. const opaqueObjects = currentRenderList.opaque;
  17336. const transmissiveObjects = currentRenderList.transmissive;
  17337. const transparentObjects = currentRenderList.transparent;
  17338. currentRenderState.setupLightsView( camera );
  17339. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17340. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17341. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17342. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17343. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17344. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17345. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17346. state.buffers.depth.setTest( true );
  17347. state.buffers.depth.setMask( true );
  17348. state.buffers.color.setMask( true );
  17349. state.setPolygonOffset( false );
  17350. }
  17351. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17352. const isWebGL2 = capabilities.isWebGL2;
  17353. if ( _transmissionRenderTarget === null ) {
  17354. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  17355. generateMipmaps: true,
  17356. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17357. minFilter: LinearMipmapLinearFilter,
  17358. samples: ( isWebGL2 && antialias === true ) ? 4 : 0
  17359. } );
  17360. // debug
  17361. /*
  17362. const geometry = new PlaneGeometry();
  17363. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17364. const mesh = new Mesh( geometry, material );
  17365. scene.add( mesh );
  17366. */
  17367. }
  17368. _this.getDrawingBufferSize( _vector2 );
  17369. if ( isWebGL2 ) {
  17370. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  17371. } else {
  17372. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  17373. }
  17374. //
  17375. const currentRenderTarget = _this.getRenderTarget();
  17376. _this.setRenderTarget( _transmissionRenderTarget );
  17377. _this.getClearColor( _currentClearColor );
  17378. _currentClearAlpha = _this.getClearAlpha();
  17379. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17380. _this.clear();
  17381. // Turn off the features which can affect the frag color for opaque objects pass.
  17382. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17383. const currentToneMapping = _this.toneMapping;
  17384. _this.toneMapping = NoToneMapping;
  17385. renderObjects( opaqueObjects, scene, camera );
  17386. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17387. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17388. let renderTargetNeedsUpdate = false;
  17389. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17390. const renderItem = transmissiveObjects[ i ];
  17391. const object = renderItem.object;
  17392. const geometry = renderItem.geometry;
  17393. const material = renderItem.material;
  17394. const group = renderItem.group;
  17395. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17396. const currentSide = material.side;
  17397. material.side = BackSide;
  17398. material.needsUpdate = true;
  17399. renderObject( object, scene, camera, geometry, material, group );
  17400. material.side = currentSide;
  17401. material.needsUpdate = true;
  17402. renderTargetNeedsUpdate = true;
  17403. }
  17404. }
  17405. if ( renderTargetNeedsUpdate === true ) {
  17406. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17407. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17408. }
  17409. _this.setRenderTarget( currentRenderTarget );
  17410. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17411. _this.toneMapping = currentToneMapping;
  17412. }
  17413. function renderObjects( renderList, scene, camera ) {
  17414. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17415. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17416. const renderItem = renderList[ i ];
  17417. const object = renderItem.object;
  17418. const geometry = renderItem.geometry;
  17419. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17420. const group = renderItem.group;
  17421. if ( object.layers.test( camera.layers ) ) {
  17422. renderObject( object, scene, camera, geometry, material, group );
  17423. }
  17424. }
  17425. }
  17426. function renderObject( object, scene, camera, geometry, material, group ) {
  17427. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17428. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17429. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17430. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17431. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17432. material.side = BackSide;
  17433. material.needsUpdate = true;
  17434. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17435. material.side = FrontSide;
  17436. material.needsUpdate = true;
  17437. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17438. material.side = DoubleSide;
  17439. } else {
  17440. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17441. }
  17442. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17443. }
  17444. function getProgram( material, scene, object ) {
  17445. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17446. const materialProperties = properties.get( material );
  17447. const lights = currentRenderState.state.lights;
  17448. const shadowsArray = currentRenderState.state.shadowsArray;
  17449. const lightsStateVersion = lights.state.version;
  17450. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17451. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17452. let programs = materialProperties.programs;
  17453. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17454. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17455. materialProperties.fog = scene.fog;
  17456. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17457. if ( programs === undefined ) {
  17458. // new material
  17459. material.addEventListener( 'dispose', onMaterialDispose );
  17460. programs = new Map();
  17461. materialProperties.programs = programs;
  17462. }
  17463. let program = programs.get( programCacheKey );
  17464. if ( program !== undefined ) {
  17465. // early out if program and light state is identical
  17466. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17467. updateCommonMaterialProperties( material, parameters );
  17468. return program;
  17469. }
  17470. } else {
  17471. parameters.uniforms = programCache.getUniforms( material );
  17472. material.onBuild( object, parameters, _this );
  17473. material.onBeforeCompile( parameters, _this );
  17474. program = programCache.acquireProgram( parameters, programCacheKey );
  17475. programs.set( programCacheKey, program );
  17476. materialProperties.uniforms = parameters.uniforms;
  17477. }
  17478. const uniforms = materialProperties.uniforms;
  17479. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17480. uniforms.clippingPlanes = clipping.uniform;
  17481. }
  17482. updateCommonMaterialProperties( material, parameters );
  17483. // store the light setup it was created for
  17484. materialProperties.needsLights = materialNeedsLights( material );
  17485. materialProperties.lightsStateVersion = lightsStateVersion;
  17486. if ( materialProperties.needsLights ) {
  17487. // wire up the material to this renderer's lighting state
  17488. uniforms.ambientLightColor.value = lights.state.ambient;
  17489. uniforms.lightProbe.value = lights.state.probe;
  17490. uniforms.directionalLights.value = lights.state.directional;
  17491. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17492. uniforms.spotLights.value = lights.state.spot;
  17493. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17494. uniforms.rectAreaLights.value = lights.state.rectArea;
  17495. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17496. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17497. uniforms.pointLights.value = lights.state.point;
  17498. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17499. uniforms.hemisphereLights.value = lights.state.hemi;
  17500. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17501. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17502. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17503. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17504. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17505. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17506. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17507. // TODO (abelnation): add area lights shadow info to uniforms
  17508. }
  17509. const progUniforms = program.getUniforms();
  17510. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17511. materialProperties.currentProgram = program;
  17512. materialProperties.uniformsList = uniformsList;
  17513. return program;
  17514. }
  17515. function updateCommonMaterialProperties( material, parameters ) {
  17516. const materialProperties = properties.get( material );
  17517. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17518. materialProperties.instancing = parameters.instancing;
  17519. materialProperties.skinning = parameters.skinning;
  17520. materialProperties.morphTargets = parameters.morphTargets;
  17521. materialProperties.morphNormals = parameters.morphNormals;
  17522. materialProperties.morphColors = parameters.morphColors;
  17523. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17524. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17525. materialProperties.numIntersection = parameters.numClipIntersection;
  17526. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17527. materialProperties.vertexTangents = parameters.vertexTangents;
  17528. materialProperties.toneMapping = parameters.toneMapping;
  17529. }
  17530. function setProgram( camera, scene, geometry, material, object ) {
  17531. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17532. textures.resetTextureUnits();
  17533. const fog = scene.fog;
  17534. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17535. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17536. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17537. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17538. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  17539. const morphTargets = !! geometry.morphAttributes.position;
  17540. const morphNormals = !! geometry.morphAttributes.normal;
  17541. const morphColors = !! geometry.morphAttributes.color;
  17542. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17543. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17544. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17545. const materialProperties = properties.get( material );
  17546. const lights = currentRenderState.state.lights;
  17547. if ( _clippingEnabled === true ) {
  17548. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17549. const useCache =
  17550. camera === _currentCamera &&
  17551. material.id === _currentMaterialId;
  17552. // we might want to call this function with some ClippingGroup
  17553. // object instead of the material, once it becomes feasible
  17554. // (#8465, #8379)
  17555. clipping.setState( material, camera, useCache );
  17556. }
  17557. }
  17558. //
  17559. let needsProgramChange = false;
  17560. if ( material.version === materialProperties.__version ) {
  17561. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17562. needsProgramChange = true;
  17563. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17564. needsProgramChange = true;
  17565. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17566. needsProgramChange = true;
  17567. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17568. needsProgramChange = true;
  17569. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17570. needsProgramChange = true;
  17571. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17572. needsProgramChange = true;
  17573. } else if ( materialProperties.envMap !== envMap ) {
  17574. needsProgramChange = true;
  17575. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17576. needsProgramChange = true;
  17577. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17578. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17579. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17580. needsProgramChange = true;
  17581. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17582. needsProgramChange = true;
  17583. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17584. needsProgramChange = true;
  17585. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17586. needsProgramChange = true;
  17587. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17588. needsProgramChange = true;
  17589. } else if ( materialProperties.morphColors !== morphColors ) {
  17590. needsProgramChange = true;
  17591. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17592. needsProgramChange = true;
  17593. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17594. needsProgramChange = true;
  17595. }
  17596. } else {
  17597. needsProgramChange = true;
  17598. materialProperties.__version = material.version;
  17599. }
  17600. //
  17601. let program = materialProperties.currentProgram;
  17602. if ( needsProgramChange === true ) {
  17603. program = getProgram( material, scene, object );
  17604. }
  17605. let refreshProgram = false;
  17606. let refreshMaterial = false;
  17607. let refreshLights = false;
  17608. const p_uniforms = program.getUniforms(),
  17609. m_uniforms = materialProperties.uniforms;
  17610. if ( state.useProgram( program.program ) ) {
  17611. refreshProgram = true;
  17612. refreshMaterial = true;
  17613. refreshLights = true;
  17614. }
  17615. if ( material.id !== _currentMaterialId ) {
  17616. _currentMaterialId = material.id;
  17617. refreshMaterial = true;
  17618. }
  17619. if ( refreshProgram || _currentCamera !== camera ) {
  17620. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17621. if ( capabilities.logarithmicDepthBuffer ) {
  17622. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17623. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17624. }
  17625. if ( _currentCamera !== camera ) {
  17626. _currentCamera = camera;
  17627. // lighting uniforms depend on the camera so enforce an update
  17628. // now, in case this material supports lights - or later, when
  17629. // the next material that does gets activated:
  17630. refreshMaterial = true; // set to true on material change
  17631. refreshLights = true; // remains set until update done
  17632. }
  17633. // load material specific uniforms
  17634. // (shader material also gets them for the sake of genericity)
  17635. if ( material.isShaderMaterial ||
  17636. material.isMeshPhongMaterial ||
  17637. material.isMeshToonMaterial ||
  17638. material.isMeshStandardMaterial ||
  17639. material.envMap ) {
  17640. const uCamPos = p_uniforms.map.cameraPosition;
  17641. if ( uCamPos !== undefined ) {
  17642. uCamPos.setValue( _gl,
  17643. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17644. }
  17645. }
  17646. if ( material.isMeshPhongMaterial ||
  17647. material.isMeshToonMaterial ||
  17648. material.isMeshLambertMaterial ||
  17649. material.isMeshBasicMaterial ||
  17650. material.isMeshStandardMaterial ||
  17651. material.isShaderMaterial ) {
  17652. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17653. }
  17654. if ( material.isMeshPhongMaterial ||
  17655. material.isMeshToonMaterial ||
  17656. material.isMeshLambertMaterial ||
  17657. material.isMeshBasicMaterial ||
  17658. material.isMeshStandardMaterial ||
  17659. material.isShaderMaterial ||
  17660. material.isShadowMaterial ||
  17661. object.isSkinnedMesh ) {
  17662. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17663. }
  17664. }
  17665. // skinning and morph target uniforms must be set even if material didn't change
  17666. // auto-setting of texture unit for bone and morph texture must go before other textures
  17667. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17668. if ( object.isSkinnedMesh ) {
  17669. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17670. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17671. const skeleton = object.skeleton;
  17672. if ( skeleton ) {
  17673. if ( capabilities.floatVertexTextures ) {
  17674. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17675. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17676. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17677. } else {
  17678. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17679. }
  17680. }
  17681. }
  17682. const morphAttributes = geometry.morphAttributes;
  17683. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17684. morphtargets.update( object, geometry, program );
  17685. }
  17686. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17687. materialProperties.receiveShadow = object.receiveShadow;
  17688. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17689. }
  17690. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17691. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17692. m_uniforms.envMap.value = envMap;
  17693. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17694. }
  17695. if ( refreshMaterial ) {
  17696. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17697. if ( materialProperties.needsLights ) {
  17698. // the current material requires lighting info
  17699. // note: all lighting uniforms are always set correctly
  17700. // they simply reference the renderer's state for their
  17701. // values
  17702. //
  17703. // use the current material's .needsUpdate flags to set
  17704. // the GL state when required
  17705. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17706. }
  17707. // refresh uniforms common to several materials
  17708. if ( fog && material.fog === true ) {
  17709. materials.refreshFogUniforms( m_uniforms, fog );
  17710. }
  17711. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17712. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17713. }
  17714. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17715. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17716. material.uniformsNeedUpdate = false;
  17717. }
  17718. if ( material.isSpriteMaterial ) {
  17719. p_uniforms.setValue( _gl, 'center', object.center );
  17720. }
  17721. // common matrices
  17722. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17723. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17724. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17725. // UBOs
  17726. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17727. const groups = material.uniformsGroups;
  17728. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17729. if ( capabilities.isWebGL2 ) {
  17730. const group = groups[ i ];
  17731. uniformsGroups.update( group, program );
  17732. uniformsGroups.bind( group, program );
  17733. } else {
  17734. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17735. }
  17736. }
  17737. }
  17738. return program;
  17739. }
  17740. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17741. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17742. uniforms.ambientLightColor.needsUpdate = value;
  17743. uniforms.lightProbe.needsUpdate = value;
  17744. uniforms.directionalLights.needsUpdate = value;
  17745. uniforms.directionalLightShadows.needsUpdate = value;
  17746. uniforms.pointLights.needsUpdate = value;
  17747. uniforms.pointLightShadows.needsUpdate = value;
  17748. uniforms.spotLights.needsUpdate = value;
  17749. uniforms.spotLightShadows.needsUpdate = value;
  17750. uniforms.rectAreaLights.needsUpdate = value;
  17751. uniforms.hemisphereLights.needsUpdate = value;
  17752. }
  17753. function materialNeedsLights( material ) {
  17754. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17755. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17756. ( material.isShaderMaterial && material.lights === true );
  17757. }
  17758. this.getActiveCubeFace = function () {
  17759. return _currentActiveCubeFace;
  17760. };
  17761. this.getActiveMipmapLevel = function () {
  17762. return _currentActiveMipmapLevel;
  17763. };
  17764. this.getRenderTarget = function () {
  17765. return _currentRenderTarget;
  17766. };
  17767. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17768. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17769. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17770. const renderTargetProperties = properties.get( renderTarget );
  17771. renderTargetProperties.__hasExternalTextures = true;
  17772. if ( renderTargetProperties.__hasExternalTextures ) {
  17773. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17774. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17775. // The multisample_render_to_texture extension doesn't work properly if there
  17776. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17777. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17778. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17779. renderTargetProperties.__useRenderToTexture = false;
  17780. }
  17781. }
  17782. }
  17783. };
  17784. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17785. const renderTargetProperties = properties.get( renderTarget );
  17786. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17787. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17788. };
  17789. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17790. _currentRenderTarget = renderTarget;
  17791. _currentActiveCubeFace = activeCubeFace;
  17792. _currentActiveMipmapLevel = activeMipmapLevel;
  17793. let useDefaultFramebuffer = true;
  17794. let framebuffer = null;
  17795. let isCube = false;
  17796. let isRenderTarget3D = false;
  17797. if ( renderTarget ) {
  17798. const renderTargetProperties = properties.get( renderTarget );
  17799. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17800. // We need to make sure to rebind the framebuffer.
  17801. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17802. useDefaultFramebuffer = false;
  17803. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17804. textures.setupRenderTarget( renderTarget );
  17805. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17806. // Color and depth texture must be rebound in order for the swapchain to update.
  17807. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17808. }
  17809. const texture = renderTarget.texture;
  17810. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17811. isRenderTarget3D = true;
  17812. }
  17813. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17814. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17815. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17816. isCube = true;
  17817. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17818. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17819. } else {
  17820. framebuffer = __webglFramebuffer;
  17821. }
  17822. _currentViewport.copy( renderTarget.viewport );
  17823. _currentScissor.copy( renderTarget.scissor );
  17824. _currentScissorTest = renderTarget.scissorTest;
  17825. } else {
  17826. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17827. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17828. _currentScissorTest = _scissorTest;
  17829. }
  17830. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17831. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17832. state.drawBuffers( renderTarget, framebuffer );
  17833. }
  17834. state.viewport( _currentViewport );
  17835. state.scissor( _currentScissor );
  17836. state.setScissorTest( _currentScissorTest );
  17837. if ( isCube ) {
  17838. const textureProperties = properties.get( renderTarget.texture );
  17839. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17840. } else if ( isRenderTarget3D ) {
  17841. const textureProperties = properties.get( renderTarget.texture );
  17842. const layer = activeCubeFace || 0;
  17843. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17844. }
  17845. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17846. };
  17847. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17848. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17849. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17850. return;
  17851. }
  17852. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17853. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17854. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17855. }
  17856. if ( framebuffer ) {
  17857. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17858. try {
  17859. const texture = renderTarget.texture;
  17860. const textureFormat = texture.format;
  17861. const textureType = texture.type;
  17862. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17863. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17864. return;
  17865. }
  17866. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17867. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17868. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17869. ! halfFloatSupportedByExt ) {
  17870. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17871. return;
  17872. }
  17873. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17874. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17875. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17876. }
  17877. } finally {
  17878. // restore framebuffer of current render target if necessary
  17879. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17880. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17881. }
  17882. }
  17883. };
  17884. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17885. const levelScale = Math.pow( 2, - level );
  17886. const width = Math.floor( texture.image.width * levelScale );
  17887. const height = Math.floor( texture.image.height * levelScale );
  17888. textures.setTexture2D( texture, 0 );
  17889. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  17890. state.unbindTexture();
  17891. };
  17892. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17893. const width = srcTexture.image.width;
  17894. const height = srcTexture.image.height;
  17895. const glFormat = utils.convert( dstTexture.format );
  17896. const glType = utils.convert( dstTexture.type );
  17897. textures.setTexture2D( dstTexture, 0 );
  17898. // As another texture upload may have changed pixelStorei
  17899. // parameters, make sure they are correct for the dstTexture
  17900. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17901. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17902. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17903. if ( srcTexture.isDataTexture ) {
  17904. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17905. } else {
  17906. if ( srcTexture.isCompressedTexture ) {
  17907. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17908. } else {
  17909. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17910. }
  17911. }
  17912. // Generate mipmaps only when copying level 0
  17913. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  17914. state.unbindTexture();
  17915. };
  17916. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17917. if ( _this.isWebGL1Renderer ) {
  17918. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17919. return;
  17920. }
  17921. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17922. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17923. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17924. const glFormat = utils.convert( dstTexture.format );
  17925. const glType = utils.convert( dstTexture.type );
  17926. let glTarget;
  17927. if ( dstTexture.isData3DTexture ) {
  17928. textures.setTexture3D( dstTexture, 0 );
  17929. glTarget = _gl.TEXTURE_3D;
  17930. } else if ( dstTexture.isDataArrayTexture ) {
  17931. textures.setTexture2DArray( dstTexture, 0 );
  17932. glTarget = _gl.TEXTURE_2D_ARRAY;
  17933. } else {
  17934. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17935. return;
  17936. }
  17937. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17938. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17939. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17940. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  17941. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  17942. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  17943. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  17944. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  17945. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17946. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  17947. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  17948. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  17949. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  17950. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  17951. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17952. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17953. } else {
  17954. if ( srcTexture.isCompressedArrayTexture ) {
  17955. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17956. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17957. } else {
  17958. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17959. }
  17960. }
  17961. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  17962. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  17963. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  17964. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  17965. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  17966. // Generate mipmaps only when copying level 0
  17967. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17968. state.unbindTexture();
  17969. };
  17970. this.initTexture = function ( texture ) {
  17971. if ( texture.isCubeTexture ) {
  17972. textures.setTextureCube( texture, 0 );
  17973. } else if ( texture.isData3DTexture ) {
  17974. textures.setTexture3D( texture, 0 );
  17975. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17976. textures.setTexture2DArray( texture, 0 );
  17977. } else {
  17978. textures.setTexture2D( texture, 0 );
  17979. }
  17980. state.unbindTexture();
  17981. };
  17982. this.resetState = function () {
  17983. _currentActiveCubeFace = 0;
  17984. _currentActiveMipmapLevel = 0;
  17985. _currentRenderTarget = null;
  17986. state.reset();
  17987. bindingStates.reset();
  17988. };
  17989. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17990. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17991. }
  17992. }
  17993. get coordinateSystem() {
  17994. return WebGLCoordinateSystem;
  17995. }
  17996. get physicallyCorrectLights() { // @deprecated, r150
  17997. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17998. return ! this.useLegacyLights;
  17999. }
  18000. set physicallyCorrectLights( value ) { // @deprecated, r150
  18001. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  18002. this.useLegacyLights = ! value;
  18003. }
  18004. get outputEncoding() { // @deprecated, r152
  18005. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18006. return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  18007. }
  18008. set outputEncoding( encoding ) { // @deprecated, r152
  18009. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18010. this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  18011. }
  18012. }
  18013. class WebGL1Renderer extends WebGLRenderer {}
  18014. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  18015. class FogExp2 {
  18016. constructor( color, density = 0.00025 ) {
  18017. this.isFogExp2 = true;
  18018. this.name = '';
  18019. this.color = new Color( color );
  18020. this.density = density;
  18021. }
  18022. clone() {
  18023. return new FogExp2( this.color, this.density );
  18024. }
  18025. toJSON( /* meta */ ) {
  18026. return {
  18027. type: 'FogExp2',
  18028. color: this.color.getHex(),
  18029. density: this.density
  18030. };
  18031. }
  18032. }
  18033. class Fog {
  18034. constructor( color, near = 1, far = 1000 ) {
  18035. this.isFog = true;
  18036. this.name = '';
  18037. this.color = new Color( color );
  18038. this.near = near;
  18039. this.far = far;
  18040. }
  18041. clone() {
  18042. return new Fog( this.color, this.near, this.far );
  18043. }
  18044. toJSON( /* meta */ ) {
  18045. return {
  18046. type: 'Fog',
  18047. color: this.color.getHex(),
  18048. near: this.near,
  18049. far: this.far
  18050. };
  18051. }
  18052. }
  18053. class Scene extends Object3D {
  18054. constructor() {
  18055. super();
  18056. this.isScene = true;
  18057. this.type = 'Scene';
  18058. this.background = null;
  18059. this.environment = null;
  18060. this.fog = null;
  18061. this.backgroundBlurriness = 0;
  18062. this.backgroundIntensity = 1;
  18063. this.overrideMaterial = null;
  18064. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18065. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18066. }
  18067. }
  18068. copy( source, recursive ) {
  18069. super.copy( source, recursive );
  18070. if ( source.background !== null ) this.background = source.background.clone();
  18071. if ( source.environment !== null ) this.environment = source.environment.clone();
  18072. if ( source.fog !== null ) this.fog = source.fog.clone();
  18073. this.backgroundBlurriness = source.backgroundBlurriness;
  18074. this.backgroundIntensity = source.backgroundIntensity;
  18075. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18076. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18077. return this;
  18078. }
  18079. toJSON( meta ) {
  18080. const data = super.toJSON( meta );
  18081. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18082. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18083. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18084. return data;
  18085. }
  18086. get autoUpdate() { // @deprecated, r144
  18087. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  18088. return this.matrixWorldAutoUpdate;
  18089. }
  18090. set autoUpdate( value ) { // @deprecated, r144
  18091. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  18092. this.matrixWorldAutoUpdate = value;
  18093. }
  18094. }
  18095. class InterleavedBuffer {
  18096. constructor( array, stride ) {
  18097. this.isInterleavedBuffer = true;
  18098. this.array = array;
  18099. this.stride = stride;
  18100. this.count = array !== undefined ? array.length / stride : 0;
  18101. this.usage = StaticDrawUsage;
  18102. this.updateRange = { offset: 0, count: - 1 };
  18103. this.version = 0;
  18104. this.uuid = generateUUID();
  18105. }
  18106. onUploadCallback() {}
  18107. set needsUpdate( value ) {
  18108. if ( value === true ) this.version ++;
  18109. }
  18110. setUsage( value ) {
  18111. this.usage = value;
  18112. return this;
  18113. }
  18114. copy( source ) {
  18115. this.array = new source.array.constructor( source.array );
  18116. this.count = source.count;
  18117. this.stride = source.stride;
  18118. this.usage = source.usage;
  18119. return this;
  18120. }
  18121. copyAt( index1, attribute, index2 ) {
  18122. index1 *= this.stride;
  18123. index2 *= attribute.stride;
  18124. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18125. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18126. }
  18127. return this;
  18128. }
  18129. set( value, offset = 0 ) {
  18130. this.array.set( value, offset );
  18131. return this;
  18132. }
  18133. clone( data ) {
  18134. if ( data.arrayBuffers === undefined ) {
  18135. data.arrayBuffers = {};
  18136. }
  18137. if ( this.array.buffer._uuid === undefined ) {
  18138. this.array.buffer._uuid = generateUUID();
  18139. }
  18140. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18141. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18142. }
  18143. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18144. const ib = new this.constructor( array, this.stride );
  18145. ib.setUsage( this.usage );
  18146. return ib;
  18147. }
  18148. onUpload( callback ) {
  18149. this.onUploadCallback = callback;
  18150. return this;
  18151. }
  18152. toJSON( data ) {
  18153. if ( data.arrayBuffers === undefined ) {
  18154. data.arrayBuffers = {};
  18155. }
  18156. // generate UUID for array buffer if necessary
  18157. if ( this.array.buffer._uuid === undefined ) {
  18158. this.array.buffer._uuid = generateUUID();
  18159. }
  18160. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18161. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18162. }
  18163. //
  18164. return {
  18165. uuid: this.uuid,
  18166. buffer: this.array.buffer._uuid,
  18167. type: this.array.constructor.name,
  18168. stride: this.stride
  18169. };
  18170. }
  18171. }
  18172. const _vector$5 = /*@__PURE__*/ new Vector3();
  18173. class InterleavedBufferAttribute {
  18174. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18175. this.isInterleavedBufferAttribute = true;
  18176. this.name = '';
  18177. this.data = interleavedBuffer;
  18178. this.itemSize = itemSize;
  18179. this.offset = offset;
  18180. this.normalized = normalized;
  18181. }
  18182. get count() {
  18183. return this.data.count;
  18184. }
  18185. get array() {
  18186. return this.data.array;
  18187. }
  18188. set needsUpdate( value ) {
  18189. this.data.needsUpdate = value;
  18190. }
  18191. applyMatrix4( m ) {
  18192. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18193. _vector$5.fromBufferAttribute( this, i );
  18194. _vector$5.applyMatrix4( m );
  18195. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18196. }
  18197. return this;
  18198. }
  18199. applyNormalMatrix( m ) {
  18200. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18201. _vector$5.fromBufferAttribute( this, i );
  18202. _vector$5.applyNormalMatrix( m );
  18203. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18204. }
  18205. return this;
  18206. }
  18207. transformDirection( m ) {
  18208. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18209. _vector$5.fromBufferAttribute( this, i );
  18210. _vector$5.transformDirection( m );
  18211. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18212. }
  18213. return this;
  18214. }
  18215. setX( index, x ) {
  18216. if ( this.normalized ) x = normalize( x, this.array );
  18217. this.data.array[ index * this.data.stride + this.offset ] = x;
  18218. return this;
  18219. }
  18220. setY( index, y ) {
  18221. if ( this.normalized ) y = normalize( y, this.array );
  18222. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18223. return this;
  18224. }
  18225. setZ( index, z ) {
  18226. if ( this.normalized ) z = normalize( z, this.array );
  18227. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18228. return this;
  18229. }
  18230. setW( index, w ) {
  18231. if ( this.normalized ) w = normalize( w, this.array );
  18232. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18233. return this;
  18234. }
  18235. getX( index ) {
  18236. let x = this.data.array[ index * this.data.stride + this.offset ];
  18237. if ( this.normalized ) x = denormalize( x, this.array );
  18238. return x;
  18239. }
  18240. getY( index ) {
  18241. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18242. if ( this.normalized ) y = denormalize( y, this.array );
  18243. return y;
  18244. }
  18245. getZ( index ) {
  18246. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18247. if ( this.normalized ) z = denormalize( z, this.array );
  18248. return z;
  18249. }
  18250. getW( index ) {
  18251. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18252. if ( this.normalized ) w = denormalize( w, this.array );
  18253. return w;
  18254. }
  18255. setXY( index, x, y ) {
  18256. index = index * this.data.stride + this.offset;
  18257. if ( this.normalized ) {
  18258. x = normalize( x, this.array );
  18259. y = normalize( y, this.array );
  18260. }
  18261. this.data.array[ index + 0 ] = x;
  18262. this.data.array[ index + 1 ] = y;
  18263. return this;
  18264. }
  18265. setXYZ( index, x, y, z ) {
  18266. index = index * this.data.stride + this.offset;
  18267. if ( this.normalized ) {
  18268. x = normalize( x, this.array );
  18269. y = normalize( y, this.array );
  18270. z = normalize( z, this.array );
  18271. }
  18272. this.data.array[ index + 0 ] = x;
  18273. this.data.array[ index + 1 ] = y;
  18274. this.data.array[ index + 2 ] = z;
  18275. return this;
  18276. }
  18277. setXYZW( index, x, y, z, w ) {
  18278. index = index * this.data.stride + this.offset;
  18279. if ( this.normalized ) {
  18280. x = normalize( x, this.array );
  18281. y = normalize( y, this.array );
  18282. z = normalize( z, this.array );
  18283. w = normalize( w, this.array );
  18284. }
  18285. this.data.array[ index + 0 ] = x;
  18286. this.data.array[ index + 1 ] = y;
  18287. this.data.array[ index + 2 ] = z;
  18288. this.data.array[ index + 3 ] = w;
  18289. return this;
  18290. }
  18291. clone( data ) {
  18292. if ( data === undefined ) {
  18293. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18294. const array = [];
  18295. for ( let i = 0; i < this.count; i ++ ) {
  18296. const index = i * this.data.stride + this.offset;
  18297. for ( let j = 0; j < this.itemSize; j ++ ) {
  18298. array.push( this.data.array[ index + j ] );
  18299. }
  18300. }
  18301. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18302. } else {
  18303. if ( data.interleavedBuffers === undefined ) {
  18304. data.interleavedBuffers = {};
  18305. }
  18306. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18307. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18308. }
  18309. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18310. }
  18311. }
  18312. toJSON( data ) {
  18313. if ( data === undefined ) {
  18314. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18315. const array = [];
  18316. for ( let i = 0; i < this.count; i ++ ) {
  18317. const index = i * this.data.stride + this.offset;
  18318. for ( let j = 0; j < this.itemSize; j ++ ) {
  18319. array.push( this.data.array[ index + j ] );
  18320. }
  18321. }
  18322. // de-interleave data and save it as an ordinary buffer attribute for now
  18323. return {
  18324. itemSize: this.itemSize,
  18325. type: this.array.constructor.name,
  18326. array: array,
  18327. normalized: this.normalized
  18328. };
  18329. } else {
  18330. // save as true interleaved attribute
  18331. if ( data.interleavedBuffers === undefined ) {
  18332. data.interleavedBuffers = {};
  18333. }
  18334. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18335. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18336. }
  18337. return {
  18338. isInterleavedBufferAttribute: true,
  18339. itemSize: this.itemSize,
  18340. data: this.data.uuid,
  18341. offset: this.offset,
  18342. normalized: this.normalized
  18343. };
  18344. }
  18345. }
  18346. }
  18347. class SpriteMaterial extends Material {
  18348. constructor( parameters ) {
  18349. super();
  18350. this.isSpriteMaterial = true;
  18351. this.type = 'SpriteMaterial';
  18352. this.color = new Color( 0xffffff );
  18353. this.map = null;
  18354. this.alphaMap = null;
  18355. this.rotation = 0;
  18356. this.sizeAttenuation = true;
  18357. this.transparent = true;
  18358. this.fog = true;
  18359. this.setValues( parameters );
  18360. }
  18361. copy( source ) {
  18362. super.copy( source );
  18363. this.color.copy( source.color );
  18364. this.map = source.map;
  18365. this.alphaMap = source.alphaMap;
  18366. this.rotation = source.rotation;
  18367. this.sizeAttenuation = source.sizeAttenuation;
  18368. this.fog = source.fog;
  18369. return this;
  18370. }
  18371. }
  18372. let _geometry;
  18373. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18374. const _worldScale = /*@__PURE__*/ new Vector3();
  18375. const _mvPosition = /*@__PURE__*/ new Vector3();
  18376. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18377. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18378. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18379. const _vA = /*@__PURE__*/ new Vector3();
  18380. const _vB = /*@__PURE__*/ new Vector3();
  18381. const _vC = /*@__PURE__*/ new Vector3();
  18382. const _uvA = /*@__PURE__*/ new Vector2();
  18383. const _uvB = /*@__PURE__*/ new Vector2();
  18384. const _uvC = /*@__PURE__*/ new Vector2();
  18385. class Sprite extends Object3D {
  18386. constructor( material ) {
  18387. super();
  18388. this.isSprite = true;
  18389. this.type = 'Sprite';
  18390. if ( _geometry === undefined ) {
  18391. _geometry = new BufferGeometry();
  18392. const float32Array = new Float32Array( [
  18393. - 0.5, - 0.5, 0, 0, 0,
  18394. 0.5, - 0.5, 0, 1, 0,
  18395. 0.5, 0.5, 0, 1, 1,
  18396. - 0.5, 0.5, 0, 0, 1
  18397. ] );
  18398. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18399. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18400. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18401. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18402. }
  18403. this.geometry = _geometry;
  18404. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18405. this.center = new Vector2( 0.5, 0.5 );
  18406. }
  18407. raycast( raycaster, intersects ) {
  18408. if ( raycaster.camera === null ) {
  18409. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18410. }
  18411. _worldScale.setFromMatrixScale( this.matrixWorld );
  18412. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18413. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18414. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18415. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18416. _worldScale.multiplyScalar( - _mvPosition.z );
  18417. }
  18418. const rotation = this.material.rotation;
  18419. let sin, cos;
  18420. if ( rotation !== 0 ) {
  18421. cos = Math.cos( rotation );
  18422. sin = Math.sin( rotation );
  18423. }
  18424. const center = this.center;
  18425. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18426. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18427. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18428. _uvA.set( 0, 0 );
  18429. _uvB.set( 1, 0 );
  18430. _uvC.set( 1, 1 );
  18431. // check first triangle
  18432. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18433. if ( intersect === null ) {
  18434. // check second triangle
  18435. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18436. _uvB.set( 0, 1 );
  18437. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18438. if ( intersect === null ) {
  18439. return;
  18440. }
  18441. }
  18442. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18443. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18444. intersects.push( {
  18445. distance: distance,
  18446. point: _intersectPoint.clone(),
  18447. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18448. face: null,
  18449. object: this
  18450. } );
  18451. }
  18452. copy( source, recursive ) {
  18453. super.copy( source, recursive );
  18454. if ( source.center !== undefined ) this.center.copy( source.center );
  18455. this.material = source.material;
  18456. return this;
  18457. }
  18458. }
  18459. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18460. // compute position in camera space
  18461. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18462. // to check if rotation is not zero
  18463. if ( sin !== undefined ) {
  18464. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18465. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18466. } else {
  18467. _rotatedPosition.copy( _alignedPosition );
  18468. }
  18469. vertexPosition.copy( mvPosition );
  18470. vertexPosition.x += _rotatedPosition.x;
  18471. vertexPosition.y += _rotatedPosition.y;
  18472. // transform to world space
  18473. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18474. }
  18475. const _v1$2 = /*@__PURE__*/ new Vector3();
  18476. const _v2$1 = /*@__PURE__*/ new Vector3();
  18477. class LOD extends Object3D {
  18478. constructor() {
  18479. super();
  18480. this._currentLevel = 0;
  18481. this.type = 'LOD';
  18482. Object.defineProperties( this, {
  18483. levels: {
  18484. enumerable: true,
  18485. value: []
  18486. },
  18487. isLOD: {
  18488. value: true,
  18489. }
  18490. } );
  18491. this.autoUpdate = true;
  18492. }
  18493. copy( source ) {
  18494. super.copy( source, false );
  18495. const levels = source.levels;
  18496. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18497. const level = levels[ i ];
  18498. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18499. }
  18500. this.autoUpdate = source.autoUpdate;
  18501. return this;
  18502. }
  18503. addLevel( object, distance = 0, hysteresis = 0 ) {
  18504. distance = Math.abs( distance );
  18505. const levels = this.levels;
  18506. let l;
  18507. for ( l = 0; l < levels.length; l ++ ) {
  18508. if ( distance < levels[ l ].distance ) {
  18509. break;
  18510. }
  18511. }
  18512. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18513. this.add( object );
  18514. return this;
  18515. }
  18516. getCurrentLevel() {
  18517. return this._currentLevel;
  18518. }
  18519. getObjectForDistance( distance ) {
  18520. const levels = this.levels;
  18521. if ( levels.length > 0 ) {
  18522. let i, l;
  18523. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18524. let levelDistance = levels[ i ].distance;
  18525. if ( levels[ i ].object.visible ) {
  18526. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18527. }
  18528. if ( distance < levelDistance ) {
  18529. break;
  18530. }
  18531. }
  18532. return levels[ i - 1 ].object;
  18533. }
  18534. return null;
  18535. }
  18536. raycast( raycaster, intersects ) {
  18537. const levels = this.levels;
  18538. if ( levels.length > 0 ) {
  18539. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18540. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18541. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18542. }
  18543. }
  18544. update( camera ) {
  18545. const levels = this.levels;
  18546. if ( levels.length > 1 ) {
  18547. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18548. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18549. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18550. levels[ 0 ].object.visible = true;
  18551. let i, l;
  18552. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18553. let levelDistance = levels[ i ].distance;
  18554. if ( levels[ i ].object.visible ) {
  18555. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18556. }
  18557. if ( distance >= levelDistance ) {
  18558. levels[ i - 1 ].object.visible = false;
  18559. levels[ i ].object.visible = true;
  18560. } else {
  18561. break;
  18562. }
  18563. }
  18564. this._currentLevel = i - 1;
  18565. for ( ; i < l; i ++ ) {
  18566. levels[ i ].object.visible = false;
  18567. }
  18568. }
  18569. }
  18570. toJSON( meta ) {
  18571. const data = super.toJSON( meta );
  18572. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18573. data.object.levels = [];
  18574. const levels = this.levels;
  18575. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18576. const level = levels[ i ];
  18577. data.object.levels.push( {
  18578. object: level.object.uuid,
  18579. distance: level.distance,
  18580. hysteresis: level.hysteresis
  18581. } );
  18582. }
  18583. return data;
  18584. }
  18585. }
  18586. const _basePosition = /*@__PURE__*/ new Vector3();
  18587. const _skinIndex = /*@__PURE__*/ new Vector4();
  18588. const _skinWeight = /*@__PURE__*/ new Vector4();
  18589. const _vector3 = /*@__PURE__*/ new Vector3();
  18590. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18591. const _vertex = /*@__PURE__*/ new Vector3();
  18592. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18593. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18594. const _ray$2 = /*@__PURE__*/ new Ray();
  18595. class SkinnedMesh extends Mesh {
  18596. constructor( geometry, material ) {
  18597. super( geometry, material );
  18598. this.isSkinnedMesh = true;
  18599. this.type = 'SkinnedMesh';
  18600. this.bindMode = 'attached';
  18601. this.bindMatrix = new Matrix4();
  18602. this.bindMatrixInverse = new Matrix4();
  18603. this.boundingBox = null;
  18604. this.boundingSphere = null;
  18605. }
  18606. computeBoundingBox() {
  18607. const geometry = this.geometry;
  18608. if ( this.boundingBox === null ) {
  18609. this.boundingBox = new Box3();
  18610. }
  18611. this.boundingBox.makeEmpty();
  18612. const positionAttribute = geometry.getAttribute( 'position' );
  18613. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18614. _vertex.fromBufferAttribute( positionAttribute, i );
  18615. this.applyBoneTransform( i, _vertex );
  18616. this.boundingBox.expandByPoint( _vertex );
  18617. }
  18618. }
  18619. computeBoundingSphere() {
  18620. const geometry = this.geometry;
  18621. if ( this.boundingSphere === null ) {
  18622. this.boundingSphere = new Sphere();
  18623. }
  18624. this.boundingSphere.makeEmpty();
  18625. const positionAttribute = geometry.getAttribute( 'position' );
  18626. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18627. _vertex.fromBufferAttribute( positionAttribute, i );
  18628. this.applyBoneTransform( i, _vertex );
  18629. this.boundingSphere.expandByPoint( _vertex );
  18630. }
  18631. }
  18632. copy( source, recursive ) {
  18633. super.copy( source, recursive );
  18634. this.bindMode = source.bindMode;
  18635. this.bindMatrix.copy( source.bindMatrix );
  18636. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18637. this.skeleton = source.skeleton;
  18638. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18639. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18640. return this;
  18641. }
  18642. raycast( raycaster, intersects ) {
  18643. const material = this.material;
  18644. const matrixWorld = this.matrixWorld;
  18645. if ( material === undefined ) return;
  18646. // test with bounding sphere in world space
  18647. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18648. _sphere$3.copy( this.boundingSphere );
  18649. _sphere$3.applyMatrix4( matrixWorld );
  18650. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  18651. // convert ray to local space of skinned mesh
  18652. _inverseMatrix$2.copy( matrixWorld ).invert();
  18653. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18654. // test with bounding box in local space
  18655. if ( this.boundingBox !== null ) {
  18656. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18657. }
  18658. // test for intersections with geometry
  18659. this._computeIntersections( raycaster, intersects, _ray$2 );
  18660. }
  18661. getVertexPosition( index, target ) {
  18662. super.getVertexPosition( index, target );
  18663. this.applyBoneTransform( index, target );
  18664. return target;
  18665. }
  18666. bind( skeleton, bindMatrix ) {
  18667. this.skeleton = skeleton;
  18668. if ( bindMatrix === undefined ) {
  18669. this.updateMatrixWorld( true );
  18670. this.skeleton.calculateInverses();
  18671. bindMatrix = this.matrixWorld;
  18672. }
  18673. this.bindMatrix.copy( bindMatrix );
  18674. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18675. }
  18676. pose() {
  18677. this.skeleton.pose();
  18678. }
  18679. normalizeSkinWeights() {
  18680. const vector = new Vector4();
  18681. const skinWeight = this.geometry.attributes.skinWeight;
  18682. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18683. vector.fromBufferAttribute( skinWeight, i );
  18684. const scale = 1.0 / vector.manhattanLength();
  18685. if ( scale !== Infinity ) {
  18686. vector.multiplyScalar( scale );
  18687. } else {
  18688. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18689. }
  18690. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18691. }
  18692. }
  18693. updateMatrixWorld( force ) {
  18694. super.updateMatrixWorld( force );
  18695. if ( this.bindMode === 'attached' ) {
  18696. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18697. } else if ( this.bindMode === 'detached' ) {
  18698. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18699. } else {
  18700. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18701. }
  18702. }
  18703. applyBoneTransform( index, vector ) {
  18704. const skeleton = this.skeleton;
  18705. const geometry = this.geometry;
  18706. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18707. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18708. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18709. vector.set( 0, 0, 0 );
  18710. for ( let i = 0; i < 4; i ++ ) {
  18711. const weight = _skinWeight.getComponent( i );
  18712. if ( weight !== 0 ) {
  18713. const boneIndex = _skinIndex.getComponent( i );
  18714. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18715. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18716. }
  18717. }
  18718. return vector.applyMatrix4( this.bindMatrixInverse );
  18719. }
  18720. boneTransform( index, vector ) { // @deprecated, r151
  18721. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  18722. return this.applyBoneTransform( index, vector );
  18723. }
  18724. }
  18725. class Bone extends Object3D {
  18726. constructor() {
  18727. super();
  18728. this.isBone = true;
  18729. this.type = 'Bone';
  18730. }
  18731. }
  18732. class DataTexture extends Texture {
  18733. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18734. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18735. this.isDataTexture = true;
  18736. this.image = { data: data, width: width, height: height };
  18737. this.generateMipmaps = false;
  18738. this.flipY = false;
  18739. this.unpackAlignment = 1;
  18740. }
  18741. }
  18742. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18743. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18744. class Skeleton {
  18745. constructor( bones = [], boneInverses = [] ) {
  18746. this.uuid = generateUUID();
  18747. this.bones = bones.slice( 0 );
  18748. this.boneInverses = boneInverses;
  18749. this.boneMatrices = null;
  18750. this.boneTexture = null;
  18751. this.boneTextureSize = 0;
  18752. this.frame = - 1;
  18753. this.init();
  18754. }
  18755. init() {
  18756. const bones = this.bones;
  18757. const boneInverses = this.boneInverses;
  18758. this.boneMatrices = new Float32Array( bones.length * 16 );
  18759. // calculate inverse bone matrices if necessary
  18760. if ( boneInverses.length === 0 ) {
  18761. this.calculateInverses();
  18762. } else {
  18763. // handle special case
  18764. if ( bones.length !== boneInverses.length ) {
  18765. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18766. this.boneInverses = [];
  18767. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18768. this.boneInverses.push( new Matrix4() );
  18769. }
  18770. }
  18771. }
  18772. }
  18773. calculateInverses() {
  18774. this.boneInverses.length = 0;
  18775. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18776. const inverse = new Matrix4();
  18777. if ( this.bones[ i ] ) {
  18778. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18779. }
  18780. this.boneInverses.push( inverse );
  18781. }
  18782. }
  18783. pose() {
  18784. // recover the bind-time world matrices
  18785. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18786. const bone = this.bones[ i ];
  18787. if ( bone ) {
  18788. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18789. }
  18790. }
  18791. // compute the local matrices, positions, rotations and scales
  18792. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18793. const bone = this.bones[ i ];
  18794. if ( bone ) {
  18795. if ( bone.parent && bone.parent.isBone ) {
  18796. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18797. bone.matrix.multiply( bone.matrixWorld );
  18798. } else {
  18799. bone.matrix.copy( bone.matrixWorld );
  18800. }
  18801. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18802. }
  18803. }
  18804. }
  18805. update() {
  18806. const bones = this.bones;
  18807. const boneInverses = this.boneInverses;
  18808. const boneMatrices = this.boneMatrices;
  18809. const boneTexture = this.boneTexture;
  18810. // flatten bone matrices to array
  18811. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18812. // compute the offset between the current and the original transform
  18813. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18814. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18815. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18816. }
  18817. if ( boneTexture !== null ) {
  18818. boneTexture.needsUpdate = true;
  18819. }
  18820. }
  18821. clone() {
  18822. return new Skeleton( this.bones, this.boneInverses );
  18823. }
  18824. computeBoneTexture() {
  18825. // layout (1 matrix = 4 pixels)
  18826. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18827. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18828. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18829. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18830. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18831. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18832. size = ceilPowerOfTwo( size );
  18833. size = Math.max( size, 4 );
  18834. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18835. boneMatrices.set( this.boneMatrices ); // copy current values
  18836. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18837. boneTexture.needsUpdate = true;
  18838. this.boneMatrices = boneMatrices;
  18839. this.boneTexture = boneTexture;
  18840. this.boneTextureSize = size;
  18841. return this;
  18842. }
  18843. getBoneByName( name ) {
  18844. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18845. const bone = this.bones[ i ];
  18846. if ( bone.name === name ) {
  18847. return bone;
  18848. }
  18849. }
  18850. return undefined;
  18851. }
  18852. dispose( ) {
  18853. if ( this.boneTexture !== null ) {
  18854. this.boneTexture.dispose();
  18855. this.boneTexture = null;
  18856. }
  18857. }
  18858. fromJSON( json, bones ) {
  18859. this.uuid = json.uuid;
  18860. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18861. const uuid = json.bones[ i ];
  18862. let bone = bones[ uuid ];
  18863. if ( bone === undefined ) {
  18864. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18865. bone = new Bone();
  18866. }
  18867. this.bones.push( bone );
  18868. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18869. }
  18870. this.init();
  18871. return this;
  18872. }
  18873. toJSON() {
  18874. const data = {
  18875. metadata: {
  18876. version: 4.6,
  18877. type: 'Skeleton',
  18878. generator: 'Skeleton.toJSON'
  18879. },
  18880. bones: [],
  18881. boneInverses: []
  18882. };
  18883. data.uuid = this.uuid;
  18884. const bones = this.bones;
  18885. const boneInverses = this.boneInverses;
  18886. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18887. const bone = bones[ i ];
  18888. data.bones.push( bone.uuid );
  18889. const boneInverse = boneInverses[ i ];
  18890. data.boneInverses.push( boneInverse.toArray() );
  18891. }
  18892. return data;
  18893. }
  18894. }
  18895. class InstancedBufferAttribute extends BufferAttribute {
  18896. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18897. super( array, itemSize, normalized );
  18898. this.isInstancedBufferAttribute = true;
  18899. this.meshPerAttribute = meshPerAttribute;
  18900. }
  18901. copy( source ) {
  18902. super.copy( source );
  18903. this.meshPerAttribute = source.meshPerAttribute;
  18904. return this;
  18905. }
  18906. toJSON() {
  18907. const data = super.toJSON();
  18908. data.meshPerAttribute = this.meshPerAttribute;
  18909. data.isInstancedBufferAttribute = true;
  18910. return data;
  18911. }
  18912. }
  18913. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18914. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18915. const _instanceIntersects = [];
  18916. const _box3 = /*@__PURE__*/ new Box3();
  18917. const _identity = /*@__PURE__*/ new Matrix4();
  18918. const _mesh = /*@__PURE__*/ new Mesh();
  18919. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18920. class InstancedMesh extends Mesh {
  18921. constructor( geometry, material, count ) {
  18922. super( geometry, material );
  18923. this.isInstancedMesh = true;
  18924. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18925. this.instanceColor = null;
  18926. this.count = count;
  18927. this.boundingBox = null;
  18928. this.boundingSphere = null;
  18929. for ( let i = 0; i < count; i ++ ) {
  18930. this.setMatrixAt( i, _identity );
  18931. }
  18932. }
  18933. computeBoundingBox() {
  18934. const geometry = this.geometry;
  18935. const count = this.count;
  18936. if ( this.boundingBox === null ) {
  18937. this.boundingBox = new Box3();
  18938. }
  18939. if ( geometry.boundingBox === null ) {
  18940. geometry.computeBoundingBox();
  18941. }
  18942. this.boundingBox.makeEmpty();
  18943. for ( let i = 0; i < count; i ++ ) {
  18944. this.getMatrixAt( i, _instanceLocalMatrix );
  18945. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18946. this.boundingBox.union( _box3 );
  18947. }
  18948. }
  18949. computeBoundingSphere() {
  18950. const geometry = this.geometry;
  18951. const count = this.count;
  18952. if ( this.boundingSphere === null ) {
  18953. this.boundingSphere = new Sphere();
  18954. }
  18955. if ( geometry.boundingSphere === null ) {
  18956. geometry.computeBoundingSphere();
  18957. }
  18958. this.boundingSphere.makeEmpty();
  18959. for ( let i = 0; i < count; i ++ ) {
  18960. this.getMatrixAt( i, _instanceLocalMatrix );
  18961. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18962. this.boundingSphere.union( _sphere$2 );
  18963. }
  18964. }
  18965. copy( source, recursive ) {
  18966. super.copy( source, recursive );
  18967. this.instanceMatrix.copy( source.instanceMatrix );
  18968. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18969. this.count = source.count;
  18970. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18971. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18972. return this;
  18973. }
  18974. getColorAt( index, color ) {
  18975. color.fromArray( this.instanceColor.array, index * 3 );
  18976. }
  18977. getMatrixAt( index, matrix ) {
  18978. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18979. }
  18980. raycast( raycaster, intersects ) {
  18981. const matrixWorld = this.matrixWorld;
  18982. const raycastTimes = this.count;
  18983. _mesh.geometry = this.geometry;
  18984. _mesh.material = this.material;
  18985. if ( _mesh.material === undefined ) return;
  18986. // test with bounding sphere first
  18987. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18988. _sphere$2.copy( this.boundingSphere );
  18989. _sphere$2.applyMatrix4( matrixWorld );
  18990. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  18991. // now test each instance
  18992. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18993. // calculate the world matrix for each instance
  18994. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18995. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18996. // the mesh represents this single instance
  18997. _mesh.matrixWorld = _instanceWorldMatrix;
  18998. _mesh.raycast( raycaster, _instanceIntersects );
  18999. // process the result of raycast
  19000. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19001. const intersect = _instanceIntersects[ i ];
  19002. intersect.instanceId = instanceId;
  19003. intersect.object = this;
  19004. intersects.push( intersect );
  19005. }
  19006. _instanceIntersects.length = 0;
  19007. }
  19008. }
  19009. setColorAt( index, color ) {
  19010. if ( this.instanceColor === null ) {
  19011. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19012. }
  19013. color.toArray( this.instanceColor.array, index * 3 );
  19014. }
  19015. setMatrixAt( index, matrix ) {
  19016. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19017. }
  19018. updateMorphTargets() {
  19019. }
  19020. dispose() {
  19021. this.dispatchEvent( { type: 'dispose' } );
  19022. }
  19023. }
  19024. class LineBasicMaterial extends Material {
  19025. constructor( parameters ) {
  19026. super();
  19027. this.isLineBasicMaterial = true;
  19028. this.type = 'LineBasicMaterial';
  19029. this.color = new Color( 0xffffff );
  19030. this.map = null;
  19031. this.linewidth = 1;
  19032. this.linecap = 'round';
  19033. this.linejoin = 'round';
  19034. this.fog = true;
  19035. this.setValues( parameters );
  19036. }
  19037. copy( source ) {
  19038. super.copy( source );
  19039. this.color.copy( source.color );
  19040. this.map = source.map;
  19041. this.linewidth = source.linewidth;
  19042. this.linecap = source.linecap;
  19043. this.linejoin = source.linejoin;
  19044. this.fog = source.fog;
  19045. return this;
  19046. }
  19047. }
  19048. const _start$1 = /*@__PURE__*/ new Vector3();
  19049. const _end$1 = /*@__PURE__*/ new Vector3();
  19050. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  19051. const _ray$1 = /*@__PURE__*/ new Ray();
  19052. const _sphere$1 = /*@__PURE__*/ new Sphere();
  19053. class Line extends Object3D {
  19054. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  19055. super();
  19056. this.isLine = true;
  19057. this.type = 'Line';
  19058. this.geometry = geometry;
  19059. this.material = material;
  19060. this.updateMorphTargets();
  19061. }
  19062. copy( source, recursive ) {
  19063. super.copy( source, recursive );
  19064. this.material = source.material;
  19065. this.geometry = source.geometry;
  19066. return this;
  19067. }
  19068. computeLineDistances() {
  19069. const geometry = this.geometry;
  19070. // we assume non-indexed geometry
  19071. if ( geometry.index === null ) {
  19072. const positionAttribute = geometry.attributes.position;
  19073. const lineDistances = [ 0 ];
  19074. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  19075. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  19076. _end$1.fromBufferAttribute( positionAttribute, i );
  19077. lineDistances[ i ] = lineDistances[ i - 1 ];
  19078. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  19079. }
  19080. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19081. } else {
  19082. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19083. }
  19084. return this;
  19085. }
  19086. raycast( raycaster, intersects ) {
  19087. const geometry = this.geometry;
  19088. const matrixWorld = this.matrixWorld;
  19089. const threshold = raycaster.params.Line.threshold;
  19090. const drawRange = geometry.drawRange;
  19091. // Checking boundingSphere distance to ray
  19092. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19093. _sphere$1.copy( geometry.boundingSphere );
  19094. _sphere$1.applyMatrix4( matrixWorld );
  19095. _sphere$1.radius += threshold;
  19096. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  19097. //
  19098. _inverseMatrix$1.copy( matrixWorld ).invert();
  19099. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  19100. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19101. const localThresholdSq = localThreshold * localThreshold;
  19102. const vStart = new Vector3();
  19103. const vEnd = new Vector3();
  19104. const interSegment = new Vector3();
  19105. const interRay = new Vector3();
  19106. const step = this.isLineSegments ? 2 : 1;
  19107. const index = geometry.index;
  19108. const attributes = geometry.attributes;
  19109. const positionAttribute = attributes.position;
  19110. if ( index !== null ) {
  19111. const start = Math.max( 0, drawRange.start );
  19112. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  19113. for ( let i = start, l = end - 1; i < l; i += step ) {
  19114. const a = index.getX( i );
  19115. const b = index.getX( i + 1 );
  19116. vStart.fromBufferAttribute( positionAttribute, a );
  19117. vEnd.fromBufferAttribute( positionAttribute, b );
  19118. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19119. if ( distSq > localThresholdSq ) continue;
  19120. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19121. const distance = raycaster.ray.origin.distanceTo( interRay );
  19122. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19123. intersects.push( {
  19124. distance: distance,
  19125. // What do we want? intersection point on the ray or on the segment??
  19126. // point: raycaster.ray.at( distance ),
  19127. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19128. index: i,
  19129. face: null,
  19130. faceIndex: null,
  19131. object: this
  19132. } );
  19133. }
  19134. } else {
  19135. const start = Math.max( 0, drawRange.start );
  19136. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  19137. for ( let i = start, l = end - 1; i < l; i += step ) {
  19138. vStart.fromBufferAttribute( positionAttribute, i );
  19139. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  19140. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19141. if ( distSq > localThresholdSq ) continue;
  19142. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19143. const distance = raycaster.ray.origin.distanceTo( interRay );
  19144. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19145. intersects.push( {
  19146. distance: distance,
  19147. // What do we want? intersection point on the ray or on the segment??
  19148. // point: raycaster.ray.at( distance ),
  19149. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19150. index: i,
  19151. face: null,
  19152. faceIndex: null,
  19153. object: this
  19154. } );
  19155. }
  19156. }
  19157. }
  19158. updateMorphTargets() {
  19159. const geometry = this.geometry;
  19160. const morphAttributes = geometry.morphAttributes;
  19161. const keys = Object.keys( morphAttributes );
  19162. if ( keys.length > 0 ) {
  19163. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  19164. if ( morphAttribute !== undefined ) {
  19165. this.morphTargetInfluences = [];
  19166. this.morphTargetDictionary = {};
  19167. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  19168. const name = morphAttribute[ m ].name || String( m );
  19169. this.morphTargetInfluences.push( 0 );
  19170. this.morphTargetDictionary[ name ] = m;
  19171. }
  19172. }
  19173. }
  19174. }
  19175. }
  19176. const _start = /*@__PURE__*/ new Vector3();
  19177. const _end = /*@__PURE__*/ new Vector3();
  19178. class LineSegments extends Line {
  19179. constructor( geometry, material ) {
  19180. super( geometry, material );
  19181. this.isLineSegments = true;
  19182. this.type = 'LineSegments';
  19183. }
  19184. computeLineDistances() {
  19185. const geometry = this.geometry;
  19186. // we assume non-indexed geometry
  19187. if ( geometry.index === null ) {
  19188. const positionAttribute = geometry.attributes.position;
  19189. const lineDistances = [];
  19190. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  19191. _start.fromBufferAttribute( positionAttribute, i );
  19192. _end.fromBufferAttribute( positionAttribute, i + 1 );
  19193. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19194. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  19195. }
  19196. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19197. } else {
  19198. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19199. }
  19200. return this;
  19201. }
  19202. }
  19203. class LineLoop extends Line {
  19204. constructor( geometry, material ) {
  19205. super( geometry, material );
  19206. this.isLineLoop = true;
  19207. this.type = 'LineLoop';
  19208. }
  19209. }
  19210. class PointsMaterial extends Material {
  19211. constructor( parameters ) {
  19212. super();
  19213. this.isPointsMaterial = true;
  19214. this.type = 'PointsMaterial';
  19215. this.color = new Color( 0xffffff );
  19216. this.map = null;
  19217. this.alphaMap = null;
  19218. this.size = 1;
  19219. this.sizeAttenuation = true;
  19220. this.fog = true;
  19221. this.setValues( parameters );
  19222. }
  19223. copy( source ) {
  19224. super.copy( source );
  19225. this.color.copy( source.color );
  19226. this.map = source.map;
  19227. this.alphaMap = source.alphaMap;
  19228. this.size = source.size;
  19229. this.sizeAttenuation = source.sizeAttenuation;
  19230. this.fog = source.fog;
  19231. return this;
  19232. }
  19233. }
  19234. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  19235. const _ray = /*@__PURE__*/ new Ray();
  19236. const _sphere = /*@__PURE__*/ new Sphere();
  19237. const _position$2 = /*@__PURE__*/ new Vector3();
  19238. class Points extends Object3D {
  19239. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  19240. super();
  19241. this.isPoints = true;
  19242. this.type = 'Points';
  19243. this.geometry = geometry;
  19244. this.material = material;
  19245. this.updateMorphTargets();
  19246. }
  19247. copy( source, recursive ) {
  19248. super.copy( source, recursive );
  19249. this.material = source.material;
  19250. this.geometry = source.geometry;
  19251. return this;
  19252. }
  19253. raycast( raycaster, intersects ) {
  19254. const geometry = this.geometry;
  19255. const matrixWorld = this.matrixWorld;
  19256. const threshold = raycaster.params.Points.threshold;
  19257. const drawRange = geometry.drawRange;
  19258. // Checking boundingSphere distance to ray
  19259. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19260. _sphere.copy( geometry.boundingSphere );
  19261. _sphere.applyMatrix4( matrixWorld );
  19262. _sphere.radius += threshold;
  19263. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  19264. //
  19265. _inverseMatrix.copy( matrixWorld ).invert();
  19266. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  19267. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19268. const localThresholdSq = localThreshold * localThreshold;
  19269. const index = geometry.index;
  19270. const attributes = geometry.attributes;
  19271. const positionAttribute = attributes.position;
  19272. if ( index !== null ) {
  19273. const start = Math.max( 0, drawRange.start );
  19274. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  19275. for ( let i = start, il = end; i < il; i ++ ) {
  19276. const a = index.getX( i );
  19277. _position$2.fromBufferAttribute( positionAttribute, a );
  19278. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19279. }
  19280. } else {
  19281. const start = Math.max( 0, drawRange.start );
  19282. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  19283. for ( let i = start, l = end; i < l; i ++ ) {
  19284. _position$2.fromBufferAttribute( positionAttribute, i );
  19285. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19286. }
  19287. }
  19288. }
  19289. updateMorphTargets() {
  19290. const geometry = this.geometry;
  19291. const morphAttributes = geometry.morphAttributes;
  19292. const keys = Object.keys( morphAttributes );
  19293. if ( keys.length > 0 ) {
  19294. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  19295. if ( morphAttribute !== undefined ) {
  19296. this.morphTargetInfluences = [];
  19297. this.morphTargetDictionary = {};
  19298. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  19299. const name = morphAttribute[ m ].name || String( m );
  19300. this.morphTargetInfluences.push( 0 );
  19301. this.morphTargetDictionary[ name ] = m;
  19302. }
  19303. }
  19304. }
  19305. }
  19306. }
  19307. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  19308. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  19309. if ( rayPointDistanceSq < localThresholdSq ) {
  19310. const intersectPoint = new Vector3();
  19311. _ray.closestPointToPoint( point, intersectPoint );
  19312. intersectPoint.applyMatrix4( matrixWorld );
  19313. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19314. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19315. intersects.push( {
  19316. distance: distance,
  19317. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19318. point: intersectPoint,
  19319. index: index,
  19320. face: null,
  19321. object: object
  19322. } );
  19323. }
  19324. }
  19325. class VideoTexture extends Texture {
  19326. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19327. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19328. this.isVideoTexture = true;
  19329. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  19330. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  19331. this.generateMipmaps = false;
  19332. const scope = this;
  19333. function updateVideo() {
  19334. scope.needsUpdate = true;
  19335. video.requestVideoFrameCallback( updateVideo );
  19336. }
  19337. if ( 'requestVideoFrameCallback' in video ) {
  19338. video.requestVideoFrameCallback( updateVideo );
  19339. }
  19340. }
  19341. clone() {
  19342. return new this.constructor( this.image ).copy( this );
  19343. }
  19344. update() {
  19345. const video = this.image;
  19346. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  19347. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  19348. this.needsUpdate = true;
  19349. }
  19350. }
  19351. }
  19352. class FramebufferTexture extends Texture {
  19353. constructor( width, height ) {
  19354. super( { width, height } );
  19355. this.isFramebufferTexture = true;
  19356. this.magFilter = NearestFilter;
  19357. this.minFilter = NearestFilter;
  19358. this.generateMipmaps = false;
  19359. this.needsUpdate = true;
  19360. }
  19361. }
  19362. class CompressedTexture extends Texture {
  19363. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  19364. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19365. this.isCompressedTexture = true;
  19366. this.image = { width: width, height: height };
  19367. this.mipmaps = mipmaps;
  19368. // no flipping for cube textures
  19369. // (also flipping doesn't work for compressed textures )
  19370. this.flipY = false;
  19371. // can't generate mipmaps for compressed textures
  19372. // mips must be embedded in DDS files
  19373. this.generateMipmaps = false;
  19374. }
  19375. }
  19376. class CompressedArrayTexture extends CompressedTexture {
  19377. constructor( mipmaps, width, height, depth, format, type ) {
  19378. super( mipmaps, width, height, format, type );
  19379. this.isCompressedArrayTexture = true;
  19380. this.image.depth = depth;
  19381. this.wrapR = ClampToEdgeWrapping;
  19382. }
  19383. }
  19384. class CanvasTexture extends Texture {
  19385. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19386. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19387. this.isCanvasTexture = true;
  19388. this.needsUpdate = true;
  19389. }
  19390. }
  19391. /**
  19392. * Extensible curve object.
  19393. *
  19394. * Some common of curve methods:
  19395. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19396. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19397. * .getPoints(), .getSpacedPoints()
  19398. * .getLength()
  19399. * .updateArcLengths()
  19400. *
  19401. * This following curves inherit from THREE.Curve:
  19402. *
  19403. * -- 2D curves --
  19404. * THREE.ArcCurve
  19405. * THREE.CubicBezierCurve
  19406. * THREE.EllipseCurve
  19407. * THREE.LineCurve
  19408. * THREE.QuadraticBezierCurve
  19409. * THREE.SplineCurve
  19410. *
  19411. * -- 3D curves --
  19412. * THREE.CatmullRomCurve3
  19413. * THREE.CubicBezierCurve3
  19414. * THREE.LineCurve3
  19415. * THREE.QuadraticBezierCurve3
  19416. *
  19417. * A series of curves can be represented as a THREE.CurvePath.
  19418. *
  19419. **/
  19420. class Curve {
  19421. constructor() {
  19422. this.type = 'Curve';
  19423. this.arcLengthDivisions = 200;
  19424. }
  19425. // Virtual base class method to overwrite and implement in subclasses
  19426. // - t [0 .. 1]
  19427. getPoint( /* t, optionalTarget */ ) {
  19428. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19429. return null;
  19430. }
  19431. // Get point at relative position in curve according to arc length
  19432. // - u [0 .. 1]
  19433. getPointAt( u, optionalTarget ) {
  19434. const t = this.getUtoTmapping( u );
  19435. return this.getPoint( t, optionalTarget );
  19436. }
  19437. // Get sequence of points using getPoint( t )
  19438. getPoints( divisions = 5 ) {
  19439. const points = [];
  19440. for ( let d = 0; d <= divisions; d ++ ) {
  19441. points.push( this.getPoint( d / divisions ) );
  19442. }
  19443. return points;
  19444. }
  19445. // Get sequence of points using getPointAt( u )
  19446. getSpacedPoints( divisions = 5 ) {
  19447. const points = [];
  19448. for ( let d = 0; d <= divisions; d ++ ) {
  19449. points.push( this.getPointAt( d / divisions ) );
  19450. }
  19451. return points;
  19452. }
  19453. // Get total curve arc length
  19454. getLength() {
  19455. const lengths = this.getLengths();
  19456. return lengths[ lengths.length - 1 ];
  19457. }
  19458. // Get list of cumulative segment lengths
  19459. getLengths( divisions = this.arcLengthDivisions ) {
  19460. if ( this.cacheArcLengths &&
  19461. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19462. ! this.needsUpdate ) {
  19463. return this.cacheArcLengths;
  19464. }
  19465. this.needsUpdate = false;
  19466. const cache = [];
  19467. let current, last = this.getPoint( 0 );
  19468. let sum = 0;
  19469. cache.push( 0 );
  19470. for ( let p = 1; p <= divisions; p ++ ) {
  19471. current = this.getPoint( p / divisions );
  19472. sum += current.distanceTo( last );
  19473. cache.push( sum );
  19474. last = current;
  19475. }
  19476. this.cacheArcLengths = cache;
  19477. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19478. }
  19479. updateArcLengths() {
  19480. this.needsUpdate = true;
  19481. this.getLengths();
  19482. }
  19483. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19484. getUtoTmapping( u, distance ) {
  19485. const arcLengths = this.getLengths();
  19486. let i = 0;
  19487. const il = arcLengths.length;
  19488. let targetArcLength; // The targeted u distance value to get
  19489. if ( distance ) {
  19490. targetArcLength = distance;
  19491. } else {
  19492. targetArcLength = u * arcLengths[ il - 1 ];
  19493. }
  19494. // binary search for the index with largest value smaller than target u distance
  19495. let low = 0, high = il - 1, comparison;
  19496. while ( low <= high ) {
  19497. 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
  19498. comparison = arcLengths[ i ] - targetArcLength;
  19499. if ( comparison < 0 ) {
  19500. low = i + 1;
  19501. } else if ( comparison > 0 ) {
  19502. high = i - 1;
  19503. } else {
  19504. high = i;
  19505. break;
  19506. // DONE
  19507. }
  19508. }
  19509. i = high;
  19510. if ( arcLengths[ i ] === targetArcLength ) {
  19511. return i / ( il - 1 );
  19512. }
  19513. // we could get finer grain at lengths, or use simple interpolation between two points
  19514. const lengthBefore = arcLengths[ i ];
  19515. const lengthAfter = arcLengths[ i + 1 ];
  19516. const segmentLength = lengthAfter - lengthBefore;
  19517. // determine where we are between the 'before' and 'after' points
  19518. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19519. // add that fractional amount to t
  19520. const t = ( i + segmentFraction ) / ( il - 1 );
  19521. return t;
  19522. }
  19523. // Returns a unit vector tangent at t
  19524. // In case any sub curve does not implement its tangent derivation,
  19525. // 2 points a small delta apart will be used to find its gradient
  19526. // which seems to give a reasonable approximation
  19527. getTangent( t, optionalTarget ) {
  19528. const delta = 0.0001;
  19529. let t1 = t - delta;
  19530. let t2 = t + delta;
  19531. // Capping in case of danger
  19532. if ( t1 < 0 ) t1 = 0;
  19533. if ( t2 > 1 ) t2 = 1;
  19534. const pt1 = this.getPoint( t1 );
  19535. const pt2 = this.getPoint( t2 );
  19536. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19537. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19538. return tangent;
  19539. }
  19540. getTangentAt( u, optionalTarget ) {
  19541. const t = this.getUtoTmapping( u );
  19542. return this.getTangent( t, optionalTarget );
  19543. }
  19544. computeFrenetFrames( segments, closed ) {
  19545. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19546. const normal = new Vector3();
  19547. const tangents = [];
  19548. const normals = [];
  19549. const binormals = [];
  19550. const vec = new Vector3();
  19551. const mat = new Matrix4();
  19552. // compute the tangent vectors for each segment on the curve
  19553. for ( let i = 0; i <= segments; i ++ ) {
  19554. const u = i / segments;
  19555. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19556. }
  19557. // select an initial normal vector perpendicular to the first tangent vector,
  19558. // and in the direction of the minimum tangent xyz component
  19559. normals[ 0 ] = new Vector3();
  19560. binormals[ 0 ] = new Vector3();
  19561. let min = Number.MAX_VALUE;
  19562. const tx = Math.abs( tangents[ 0 ].x );
  19563. const ty = Math.abs( tangents[ 0 ].y );
  19564. const tz = Math.abs( tangents[ 0 ].z );
  19565. if ( tx <= min ) {
  19566. min = tx;
  19567. normal.set( 1, 0, 0 );
  19568. }
  19569. if ( ty <= min ) {
  19570. min = ty;
  19571. normal.set( 0, 1, 0 );
  19572. }
  19573. if ( tz <= min ) {
  19574. normal.set( 0, 0, 1 );
  19575. }
  19576. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19577. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19578. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19579. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19580. for ( let i = 1; i <= segments; i ++ ) {
  19581. normals[ i ] = normals[ i - 1 ].clone();
  19582. binormals[ i ] = binormals[ i - 1 ].clone();
  19583. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19584. if ( vec.length() > Number.EPSILON ) {
  19585. vec.normalize();
  19586. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19587. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19588. }
  19589. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19590. }
  19591. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19592. if ( closed === true ) {
  19593. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19594. theta /= segments;
  19595. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19596. theta = - theta;
  19597. }
  19598. for ( let i = 1; i <= segments; i ++ ) {
  19599. // twist a little...
  19600. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19601. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19602. }
  19603. }
  19604. return {
  19605. tangents: tangents,
  19606. normals: normals,
  19607. binormals: binormals
  19608. };
  19609. }
  19610. clone() {
  19611. return new this.constructor().copy( this );
  19612. }
  19613. copy( source ) {
  19614. this.arcLengthDivisions = source.arcLengthDivisions;
  19615. return this;
  19616. }
  19617. toJSON() {
  19618. const data = {
  19619. metadata: {
  19620. version: 4.6,
  19621. type: 'Curve',
  19622. generator: 'Curve.toJSON'
  19623. }
  19624. };
  19625. data.arcLengthDivisions = this.arcLengthDivisions;
  19626. data.type = this.type;
  19627. return data;
  19628. }
  19629. fromJSON( json ) {
  19630. this.arcLengthDivisions = json.arcLengthDivisions;
  19631. return this;
  19632. }
  19633. }
  19634. class EllipseCurve extends Curve {
  19635. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19636. super();
  19637. this.isEllipseCurve = true;
  19638. this.type = 'EllipseCurve';
  19639. this.aX = aX;
  19640. this.aY = aY;
  19641. this.xRadius = xRadius;
  19642. this.yRadius = yRadius;
  19643. this.aStartAngle = aStartAngle;
  19644. this.aEndAngle = aEndAngle;
  19645. this.aClockwise = aClockwise;
  19646. this.aRotation = aRotation;
  19647. }
  19648. getPoint( t, optionalTarget ) {
  19649. const point = optionalTarget || new Vector2();
  19650. const twoPi = Math.PI * 2;
  19651. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19652. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19653. // ensures that deltaAngle is 0 .. 2 PI
  19654. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19655. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19656. if ( deltaAngle < Number.EPSILON ) {
  19657. if ( samePoints ) {
  19658. deltaAngle = 0;
  19659. } else {
  19660. deltaAngle = twoPi;
  19661. }
  19662. }
  19663. if ( this.aClockwise === true && ! samePoints ) {
  19664. if ( deltaAngle === twoPi ) {
  19665. deltaAngle = - twoPi;
  19666. } else {
  19667. deltaAngle = deltaAngle - twoPi;
  19668. }
  19669. }
  19670. const angle = this.aStartAngle + t * deltaAngle;
  19671. let x = this.aX + this.xRadius * Math.cos( angle );
  19672. let y = this.aY + this.yRadius * Math.sin( angle );
  19673. if ( this.aRotation !== 0 ) {
  19674. const cos = Math.cos( this.aRotation );
  19675. const sin = Math.sin( this.aRotation );
  19676. const tx = x - this.aX;
  19677. const ty = y - this.aY;
  19678. // Rotate the point about the center of the ellipse.
  19679. x = tx * cos - ty * sin + this.aX;
  19680. y = tx * sin + ty * cos + this.aY;
  19681. }
  19682. return point.set( x, y );
  19683. }
  19684. copy( source ) {
  19685. super.copy( source );
  19686. this.aX = source.aX;
  19687. this.aY = source.aY;
  19688. this.xRadius = source.xRadius;
  19689. this.yRadius = source.yRadius;
  19690. this.aStartAngle = source.aStartAngle;
  19691. this.aEndAngle = source.aEndAngle;
  19692. this.aClockwise = source.aClockwise;
  19693. this.aRotation = source.aRotation;
  19694. return this;
  19695. }
  19696. toJSON() {
  19697. const data = super.toJSON();
  19698. data.aX = this.aX;
  19699. data.aY = this.aY;
  19700. data.xRadius = this.xRadius;
  19701. data.yRadius = this.yRadius;
  19702. data.aStartAngle = this.aStartAngle;
  19703. data.aEndAngle = this.aEndAngle;
  19704. data.aClockwise = this.aClockwise;
  19705. data.aRotation = this.aRotation;
  19706. return data;
  19707. }
  19708. fromJSON( json ) {
  19709. super.fromJSON( json );
  19710. this.aX = json.aX;
  19711. this.aY = json.aY;
  19712. this.xRadius = json.xRadius;
  19713. this.yRadius = json.yRadius;
  19714. this.aStartAngle = json.aStartAngle;
  19715. this.aEndAngle = json.aEndAngle;
  19716. this.aClockwise = json.aClockwise;
  19717. this.aRotation = json.aRotation;
  19718. return this;
  19719. }
  19720. }
  19721. class ArcCurve extends EllipseCurve {
  19722. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19723. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19724. this.isArcCurve = true;
  19725. this.type = 'ArcCurve';
  19726. }
  19727. }
  19728. /**
  19729. * Centripetal CatmullRom Curve - which is useful for avoiding
  19730. * cusps and self-intersections in non-uniform catmull rom curves.
  19731. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19732. *
  19733. * curve.type accepts centripetal(default), chordal and catmullrom
  19734. * curve.tension is used for catmullrom which defaults to 0.5
  19735. */
  19736. /*
  19737. Based on an optimized c++ solution in
  19738. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19739. - http://ideone.com/NoEbVM
  19740. This CubicPoly class could be used for reusing some variables and calculations,
  19741. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19742. which can be placed in CurveUtils.
  19743. */
  19744. function CubicPoly() {
  19745. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19746. /*
  19747. * Compute coefficients for a cubic polynomial
  19748. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19749. * such that
  19750. * p(0) = x0, p(1) = x1
  19751. * and
  19752. * p'(0) = t0, p'(1) = t1.
  19753. */
  19754. function init( x0, x1, t0, t1 ) {
  19755. c0 = x0;
  19756. c1 = t0;
  19757. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19758. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19759. }
  19760. return {
  19761. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19762. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19763. },
  19764. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19765. // compute tangents when parameterized in [t1,t2]
  19766. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19767. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19768. // rescale tangents for parametrization in [0,1]
  19769. t1 *= dt1;
  19770. t2 *= dt1;
  19771. init( x1, x2, t1, t2 );
  19772. },
  19773. calc: function ( t ) {
  19774. const t2 = t * t;
  19775. const t3 = t2 * t;
  19776. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19777. }
  19778. };
  19779. }
  19780. //
  19781. const tmp = /*@__PURE__*/ new Vector3();
  19782. const px = /*@__PURE__*/ new CubicPoly();
  19783. const py = /*@__PURE__*/ new CubicPoly();
  19784. const pz = /*@__PURE__*/ new CubicPoly();
  19785. class CatmullRomCurve3 extends Curve {
  19786. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19787. super();
  19788. this.isCatmullRomCurve3 = true;
  19789. this.type = 'CatmullRomCurve3';
  19790. this.points = points;
  19791. this.closed = closed;
  19792. this.curveType = curveType;
  19793. this.tension = tension;
  19794. }
  19795. getPoint( t, optionalTarget = new Vector3() ) {
  19796. const point = optionalTarget;
  19797. const points = this.points;
  19798. const l = points.length;
  19799. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19800. let intPoint = Math.floor( p );
  19801. let weight = p - intPoint;
  19802. if ( this.closed ) {
  19803. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19804. } else if ( weight === 0 && intPoint === l - 1 ) {
  19805. intPoint = l - 2;
  19806. weight = 1;
  19807. }
  19808. let p0, p3; // 4 points (p1 & p2 defined below)
  19809. if ( this.closed || intPoint > 0 ) {
  19810. p0 = points[ ( intPoint - 1 ) % l ];
  19811. } else {
  19812. // extrapolate first point
  19813. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19814. p0 = tmp;
  19815. }
  19816. const p1 = points[ intPoint % l ];
  19817. const p2 = points[ ( intPoint + 1 ) % l ];
  19818. if ( this.closed || intPoint + 2 < l ) {
  19819. p3 = points[ ( intPoint + 2 ) % l ];
  19820. } else {
  19821. // extrapolate last point
  19822. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19823. p3 = tmp;
  19824. }
  19825. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19826. // init Centripetal / Chordal Catmull-Rom
  19827. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19828. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19829. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19830. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19831. // safety check for repeated points
  19832. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19833. if ( dt0 < 1e-4 ) dt0 = dt1;
  19834. if ( dt2 < 1e-4 ) dt2 = dt1;
  19835. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19836. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19837. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19838. } else if ( this.curveType === 'catmullrom' ) {
  19839. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19840. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19841. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19842. }
  19843. point.set(
  19844. px.calc( weight ),
  19845. py.calc( weight ),
  19846. pz.calc( weight )
  19847. );
  19848. return point;
  19849. }
  19850. copy( source ) {
  19851. super.copy( source );
  19852. this.points = [];
  19853. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19854. const point = source.points[ i ];
  19855. this.points.push( point.clone() );
  19856. }
  19857. this.closed = source.closed;
  19858. this.curveType = source.curveType;
  19859. this.tension = source.tension;
  19860. return this;
  19861. }
  19862. toJSON() {
  19863. const data = super.toJSON();
  19864. data.points = [];
  19865. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19866. const point = this.points[ i ];
  19867. data.points.push( point.toArray() );
  19868. }
  19869. data.closed = this.closed;
  19870. data.curveType = this.curveType;
  19871. data.tension = this.tension;
  19872. return data;
  19873. }
  19874. fromJSON( json ) {
  19875. super.fromJSON( json );
  19876. this.points = [];
  19877. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19878. const point = json.points[ i ];
  19879. this.points.push( new Vector3().fromArray( point ) );
  19880. }
  19881. this.closed = json.closed;
  19882. this.curveType = json.curveType;
  19883. this.tension = json.tension;
  19884. return this;
  19885. }
  19886. }
  19887. /**
  19888. * Bezier Curves formulas obtained from
  19889. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19890. */
  19891. function CatmullRom( t, p0, p1, p2, p3 ) {
  19892. const v0 = ( p2 - p0 ) * 0.5;
  19893. const v1 = ( p3 - p1 ) * 0.5;
  19894. const t2 = t * t;
  19895. const t3 = t * t2;
  19896. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19897. }
  19898. //
  19899. function QuadraticBezierP0( t, p ) {
  19900. const k = 1 - t;
  19901. return k * k * p;
  19902. }
  19903. function QuadraticBezierP1( t, p ) {
  19904. return 2 * ( 1 - t ) * t * p;
  19905. }
  19906. function QuadraticBezierP2( t, p ) {
  19907. return t * t * p;
  19908. }
  19909. function QuadraticBezier( t, p0, p1, p2 ) {
  19910. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19911. QuadraticBezierP2( t, p2 );
  19912. }
  19913. //
  19914. function CubicBezierP0( t, p ) {
  19915. const k = 1 - t;
  19916. return k * k * k * p;
  19917. }
  19918. function CubicBezierP1( t, p ) {
  19919. const k = 1 - t;
  19920. return 3 * k * k * t * p;
  19921. }
  19922. function CubicBezierP2( t, p ) {
  19923. return 3 * ( 1 - t ) * t * t * p;
  19924. }
  19925. function CubicBezierP3( t, p ) {
  19926. return t * t * t * p;
  19927. }
  19928. function CubicBezier( t, p0, p1, p2, p3 ) {
  19929. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19930. CubicBezierP3( t, p3 );
  19931. }
  19932. class CubicBezierCurve extends Curve {
  19933. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19934. super();
  19935. this.isCubicBezierCurve = true;
  19936. this.type = 'CubicBezierCurve';
  19937. this.v0 = v0;
  19938. this.v1 = v1;
  19939. this.v2 = v2;
  19940. this.v3 = v3;
  19941. }
  19942. getPoint( t, optionalTarget = new Vector2() ) {
  19943. const point = optionalTarget;
  19944. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19945. point.set(
  19946. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19947. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19948. );
  19949. return point;
  19950. }
  19951. copy( source ) {
  19952. super.copy( source );
  19953. this.v0.copy( source.v0 );
  19954. this.v1.copy( source.v1 );
  19955. this.v2.copy( source.v2 );
  19956. this.v3.copy( source.v3 );
  19957. return this;
  19958. }
  19959. toJSON() {
  19960. const data = super.toJSON();
  19961. data.v0 = this.v0.toArray();
  19962. data.v1 = this.v1.toArray();
  19963. data.v2 = this.v2.toArray();
  19964. data.v3 = this.v3.toArray();
  19965. return data;
  19966. }
  19967. fromJSON( json ) {
  19968. super.fromJSON( json );
  19969. this.v0.fromArray( json.v0 );
  19970. this.v1.fromArray( json.v1 );
  19971. this.v2.fromArray( json.v2 );
  19972. this.v3.fromArray( json.v3 );
  19973. return this;
  19974. }
  19975. }
  19976. class CubicBezierCurve3 extends Curve {
  19977. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19978. super();
  19979. this.isCubicBezierCurve3 = true;
  19980. this.type = 'CubicBezierCurve3';
  19981. this.v0 = v0;
  19982. this.v1 = v1;
  19983. this.v2 = v2;
  19984. this.v3 = v3;
  19985. }
  19986. getPoint( t, optionalTarget = new Vector3() ) {
  19987. const point = optionalTarget;
  19988. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19989. point.set(
  19990. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19991. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19992. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19993. );
  19994. return point;
  19995. }
  19996. copy( source ) {
  19997. super.copy( source );
  19998. this.v0.copy( source.v0 );
  19999. this.v1.copy( source.v1 );
  20000. this.v2.copy( source.v2 );
  20001. this.v3.copy( source.v3 );
  20002. return this;
  20003. }
  20004. toJSON() {
  20005. const data = super.toJSON();
  20006. data.v0 = this.v0.toArray();
  20007. data.v1 = this.v1.toArray();
  20008. data.v2 = this.v2.toArray();
  20009. data.v3 = this.v3.toArray();
  20010. return data;
  20011. }
  20012. fromJSON( json ) {
  20013. super.fromJSON( json );
  20014. this.v0.fromArray( json.v0 );
  20015. this.v1.fromArray( json.v1 );
  20016. this.v2.fromArray( json.v2 );
  20017. this.v3.fromArray( json.v3 );
  20018. return this;
  20019. }
  20020. }
  20021. class LineCurve extends Curve {
  20022. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  20023. super();
  20024. this.isLineCurve = true;
  20025. this.type = 'LineCurve';
  20026. this.v1 = v1;
  20027. this.v2 = v2;
  20028. }
  20029. getPoint( t, optionalTarget = new Vector2() ) {
  20030. const point = optionalTarget;
  20031. if ( t === 1 ) {
  20032. point.copy( this.v2 );
  20033. } else {
  20034. point.copy( this.v2 ).sub( this.v1 );
  20035. point.multiplyScalar( t ).add( this.v1 );
  20036. }
  20037. return point;
  20038. }
  20039. // Line curve is linear, so we can overwrite default getPointAt
  20040. getPointAt( u, optionalTarget ) {
  20041. return this.getPoint( u, optionalTarget );
  20042. }
  20043. getTangent( t, optionalTarget = new Vector2() ) {
  20044. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20045. }
  20046. getTangentAt( u, optionalTarget ) {
  20047. return this.getTangent( u, optionalTarget );
  20048. }
  20049. copy( source ) {
  20050. super.copy( source );
  20051. this.v1.copy( source.v1 );
  20052. this.v2.copy( source.v2 );
  20053. return this;
  20054. }
  20055. toJSON() {
  20056. const data = super.toJSON();
  20057. data.v1 = this.v1.toArray();
  20058. data.v2 = this.v2.toArray();
  20059. return data;
  20060. }
  20061. fromJSON( json ) {
  20062. super.fromJSON( json );
  20063. this.v1.fromArray( json.v1 );
  20064. this.v2.fromArray( json.v2 );
  20065. return this;
  20066. }
  20067. }
  20068. class LineCurve3 extends Curve {
  20069. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  20070. super();
  20071. this.isLineCurve3 = true;
  20072. this.type = 'LineCurve3';
  20073. this.v1 = v1;
  20074. this.v2 = v2;
  20075. }
  20076. getPoint( t, optionalTarget = new Vector3() ) {
  20077. const point = optionalTarget;
  20078. if ( t === 1 ) {
  20079. point.copy( this.v2 );
  20080. } else {
  20081. point.copy( this.v2 ).sub( this.v1 );
  20082. point.multiplyScalar( t ).add( this.v1 );
  20083. }
  20084. return point;
  20085. }
  20086. // Line curve is linear, so we can overwrite default getPointAt
  20087. getPointAt( u, optionalTarget ) {
  20088. return this.getPoint( u, optionalTarget );
  20089. }
  20090. getTangent( t, optionalTarget = new Vector3() ) {
  20091. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20092. }
  20093. getTangentAt( u, optionalTarget ) {
  20094. return this.getTangent( u, optionalTarget );
  20095. }
  20096. copy( source ) {
  20097. super.copy( source );
  20098. this.v1.copy( source.v1 );
  20099. this.v2.copy( source.v2 );
  20100. return this;
  20101. }
  20102. toJSON() {
  20103. const data = super.toJSON();
  20104. data.v1 = this.v1.toArray();
  20105. data.v2 = this.v2.toArray();
  20106. return data;
  20107. }
  20108. fromJSON( json ) {
  20109. super.fromJSON( json );
  20110. this.v1.fromArray( json.v1 );
  20111. this.v2.fromArray( json.v2 );
  20112. return this;
  20113. }
  20114. }
  20115. class QuadraticBezierCurve extends Curve {
  20116. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  20117. super();
  20118. this.isQuadraticBezierCurve = true;
  20119. this.type = 'QuadraticBezierCurve';
  20120. this.v0 = v0;
  20121. this.v1 = v1;
  20122. this.v2 = v2;
  20123. }
  20124. getPoint( t, optionalTarget = new Vector2() ) {
  20125. const point = optionalTarget;
  20126. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20127. point.set(
  20128. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20129. QuadraticBezier( t, v0.y, v1.y, v2.y )
  20130. );
  20131. return point;
  20132. }
  20133. copy( source ) {
  20134. super.copy( source );
  20135. this.v0.copy( source.v0 );
  20136. this.v1.copy( source.v1 );
  20137. this.v2.copy( source.v2 );
  20138. return this;
  20139. }
  20140. toJSON() {
  20141. const data = super.toJSON();
  20142. data.v0 = this.v0.toArray();
  20143. data.v1 = this.v1.toArray();
  20144. data.v2 = this.v2.toArray();
  20145. return data;
  20146. }
  20147. fromJSON( json ) {
  20148. super.fromJSON( json );
  20149. this.v0.fromArray( json.v0 );
  20150. this.v1.fromArray( json.v1 );
  20151. this.v2.fromArray( json.v2 );
  20152. return this;
  20153. }
  20154. }
  20155. class QuadraticBezierCurve3 extends Curve {
  20156. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  20157. super();
  20158. this.isQuadraticBezierCurve3 = true;
  20159. this.type = 'QuadraticBezierCurve3';
  20160. this.v0 = v0;
  20161. this.v1 = v1;
  20162. this.v2 = v2;
  20163. }
  20164. getPoint( t, optionalTarget = new Vector3() ) {
  20165. const point = optionalTarget;
  20166. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20167. point.set(
  20168. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20169. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  20170. QuadraticBezier( t, v0.z, v1.z, v2.z )
  20171. );
  20172. return point;
  20173. }
  20174. copy( source ) {
  20175. super.copy( source );
  20176. this.v0.copy( source.v0 );
  20177. this.v1.copy( source.v1 );
  20178. this.v2.copy( source.v2 );
  20179. return this;
  20180. }
  20181. toJSON() {
  20182. const data = super.toJSON();
  20183. data.v0 = this.v0.toArray();
  20184. data.v1 = this.v1.toArray();
  20185. data.v2 = this.v2.toArray();
  20186. return data;
  20187. }
  20188. fromJSON( json ) {
  20189. super.fromJSON( json );
  20190. this.v0.fromArray( json.v0 );
  20191. this.v1.fromArray( json.v1 );
  20192. this.v2.fromArray( json.v2 );
  20193. return this;
  20194. }
  20195. }
  20196. class SplineCurve extends Curve {
  20197. constructor( points = [] ) {
  20198. super();
  20199. this.isSplineCurve = true;
  20200. this.type = 'SplineCurve';
  20201. this.points = points;
  20202. }
  20203. getPoint( t, optionalTarget = new Vector2() ) {
  20204. const point = optionalTarget;
  20205. const points = this.points;
  20206. const p = ( points.length - 1 ) * t;
  20207. const intPoint = Math.floor( p );
  20208. const weight = p - intPoint;
  20209. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20210. const p1 = points[ intPoint ];
  20211. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20212. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20213. point.set(
  20214. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  20215. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  20216. );
  20217. return point;
  20218. }
  20219. copy( source ) {
  20220. super.copy( source );
  20221. this.points = [];
  20222. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  20223. const point = source.points[ i ];
  20224. this.points.push( point.clone() );
  20225. }
  20226. return this;
  20227. }
  20228. toJSON() {
  20229. const data = super.toJSON();
  20230. data.points = [];
  20231. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20232. const point = this.points[ i ];
  20233. data.points.push( point.toArray() );
  20234. }
  20235. return data;
  20236. }
  20237. fromJSON( json ) {
  20238. super.fromJSON( json );
  20239. this.points = [];
  20240. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20241. const point = json.points[ i ];
  20242. this.points.push( new Vector2().fromArray( point ) );
  20243. }
  20244. return this;
  20245. }
  20246. }
  20247. var Curves = /*#__PURE__*/Object.freeze({
  20248. __proto__: null,
  20249. ArcCurve: ArcCurve,
  20250. CatmullRomCurve3: CatmullRomCurve3,
  20251. CubicBezierCurve: CubicBezierCurve,
  20252. CubicBezierCurve3: CubicBezierCurve3,
  20253. EllipseCurve: EllipseCurve,
  20254. LineCurve: LineCurve,
  20255. LineCurve3: LineCurve3,
  20256. QuadraticBezierCurve: QuadraticBezierCurve,
  20257. QuadraticBezierCurve3: QuadraticBezierCurve3,
  20258. SplineCurve: SplineCurve
  20259. });
  20260. /**************************************************************
  20261. * Curved Path - a curve path is simply a array of connected
  20262. * curves, but retains the api of a curve
  20263. **************************************************************/
  20264. class CurvePath extends Curve {
  20265. constructor() {
  20266. super();
  20267. this.type = 'CurvePath';
  20268. this.curves = [];
  20269. this.autoClose = false; // Automatically closes the path
  20270. }
  20271. add( curve ) {
  20272. this.curves.push( curve );
  20273. }
  20274. closePath() {
  20275. // Add a line curve if start and end of lines are not connected
  20276. const startPoint = this.curves[ 0 ].getPoint( 0 );
  20277. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20278. if ( ! startPoint.equals( endPoint ) ) {
  20279. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20280. }
  20281. }
  20282. // To get accurate point with reference to
  20283. // entire path distance at time t,
  20284. // following has to be done:
  20285. // 1. Length of each sub path have to be known
  20286. // 2. Locate and identify type of curve
  20287. // 3. Get t for the curve
  20288. // 4. Return curve.getPointAt(t')
  20289. getPoint( t, optionalTarget ) {
  20290. const d = t * this.getLength();
  20291. const curveLengths = this.getCurveLengths();
  20292. let i = 0;
  20293. // To think about boundaries points.
  20294. while ( i < curveLengths.length ) {
  20295. if ( curveLengths[ i ] >= d ) {
  20296. const diff = curveLengths[ i ] - d;
  20297. const curve = this.curves[ i ];
  20298. const segmentLength = curve.getLength();
  20299. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20300. return curve.getPointAt( u, optionalTarget );
  20301. }
  20302. i ++;
  20303. }
  20304. return null;
  20305. // loop where sum != 0, sum > d , sum+1 <d
  20306. }
  20307. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20308. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20309. // getPoint() depends on getLength
  20310. getLength() {
  20311. const lens = this.getCurveLengths();
  20312. return lens[ lens.length - 1 ];
  20313. }
  20314. // cacheLengths must be recalculated.
  20315. updateArcLengths() {
  20316. this.needsUpdate = true;
  20317. this.cacheLengths = null;
  20318. this.getCurveLengths();
  20319. }
  20320. // Compute lengths and cache them
  20321. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20322. getCurveLengths() {
  20323. // We use cache values if curves and cache array are same length
  20324. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20325. return this.cacheLengths;
  20326. }
  20327. // Get length of sub-curve
  20328. // Push sums into cached array
  20329. const lengths = [];
  20330. let sums = 0;
  20331. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20332. sums += this.curves[ i ].getLength();
  20333. lengths.push( sums );
  20334. }
  20335. this.cacheLengths = lengths;
  20336. return lengths;
  20337. }
  20338. getSpacedPoints( divisions = 40 ) {
  20339. const points = [];
  20340. for ( let i = 0; i <= divisions; i ++ ) {
  20341. points.push( this.getPoint( i / divisions ) );
  20342. }
  20343. if ( this.autoClose ) {
  20344. points.push( points[ 0 ] );
  20345. }
  20346. return points;
  20347. }
  20348. getPoints( divisions = 12 ) {
  20349. const points = [];
  20350. let last;
  20351. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20352. const curve = curves[ i ];
  20353. const resolution = curve.isEllipseCurve ? divisions * 2
  20354. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  20355. : curve.isSplineCurve ? divisions * curve.points.length
  20356. : divisions;
  20357. const pts = curve.getPoints( resolution );
  20358. for ( let j = 0; j < pts.length; j ++ ) {
  20359. const point = pts[ j ];
  20360. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20361. points.push( point );
  20362. last = point;
  20363. }
  20364. }
  20365. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20366. points.push( points[ 0 ] );
  20367. }
  20368. return points;
  20369. }
  20370. copy( source ) {
  20371. super.copy( source );
  20372. this.curves = [];
  20373. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  20374. const curve = source.curves[ i ];
  20375. this.curves.push( curve.clone() );
  20376. }
  20377. this.autoClose = source.autoClose;
  20378. return this;
  20379. }
  20380. toJSON() {
  20381. const data = super.toJSON();
  20382. data.autoClose = this.autoClose;
  20383. data.curves = [];
  20384. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20385. const curve = this.curves[ i ];
  20386. data.curves.push( curve.toJSON() );
  20387. }
  20388. return data;
  20389. }
  20390. fromJSON( json ) {
  20391. super.fromJSON( json );
  20392. this.autoClose = json.autoClose;
  20393. this.curves = [];
  20394. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  20395. const curve = json.curves[ i ];
  20396. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  20397. }
  20398. return this;
  20399. }
  20400. }
  20401. class Path extends CurvePath {
  20402. constructor( points ) {
  20403. super();
  20404. this.type = 'Path';
  20405. this.currentPoint = new Vector2();
  20406. if ( points ) {
  20407. this.setFromPoints( points );
  20408. }
  20409. }
  20410. setFromPoints( points ) {
  20411. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  20412. for ( let i = 1, l = points.length; i < l; i ++ ) {
  20413. this.lineTo( points[ i ].x, points[ i ].y );
  20414. }
  20415. return this;
  20416. }
  20417. moveTo( x, y ) {
  20418. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20419. return this;
  20420. }
  20421. lineTo( x, y ) {
  20422. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20423. this.curves.push( curve );
  20424. this.currentPoint.set( x, y );
  20425. return this;
  20426. }
  20427. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  20428. const curve = new QuadraticBezierCurve(
  20429. this.currentPoint.clone(),
  20430. new Vector2( aCPx, aCPy ),
  20431. new Vector2( aX, aY )
  20432. );
  20433. this.curves.push( curve );
  20434. this.currentPoint.set( aX, aY );
  20435. return this;
  20436. }
  20437. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20438. const curve = new CubicBezierCurve(
  20439. this.currentPoint.clone(),
  20440. new Vector2( aCP1x, aCP1y ),
  20441. new Vector2( aCP2x, aCP2y ),
  20442. new Vector2( aX, aY )
  20443. );
  20444. this.curves.push( curve );
  20445. this.currentPoint.set( aX, aY );
  20446. return this;
  20447. }
  20448. splineThru( pts /*Array of Vector*/ ) {
  20449. const npts = [ this.currentPoint.clone() ].concat( pts );
  20450. const curve = new SplineCurve( npts );
  20451. this.curves.push( curve );
  20452. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20453. return this;
  20454. }
  20455. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20456. const x0 = this.currentPoint.x;
  20457. const y0 = this.currentPoint.y;
  20458. this.absarc( aX + x0, aY + y0, aRadius,
  20459. aStartAngle, aEndAngle, aClockwise );
  20460. return this;
  20461. }
  20462. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20463. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20464. return this;
  20465. }
  20466. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20467. const x0 = this.currentPoint.x;
  20468. const y0 = this.currentPoint.y;
  20469. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20470. return this;
  20471. }
  20472. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20473. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20474. if ( this.curves.length > 0 ) {
  20475. // if a previous curve is present, attempt to join
  20476. const firstPoint = curve.getPoint( 0 );
  20477. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20478. this.lineTo( firstPoint.x, firstPoint.y );
  20479. }
  20480. }
  20481. this.curves.push( curve );
  20482. const lastPoint = curve.getPoint( 1 );
  20483. this.currentPoint.copy( lastPoint );
  20484. return this;
  20485. }
  20486. copy( source ) {
  20487. super.copy( source );
  20488. this.currentPoint.copy( source.currentPoint );
  20489. return this;
  20490. }
  20491. toJSON() {
  20492. const data = super.toJSON();
  20493. data.currentPoint = this.currentPoint.toArray();
  20494. return data;
  20495. }
  20496. fromJSON( json ) {
  20497. super.fromJSON( json );
  20498. this.currentPoint.fromArray( json.currentPoint );
  20499. return this;
  20500. }
  20501. }
  20502. class LatheGeometry extends BufferGeometry {
  20503. 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 ) {
  20504. super();
  20505. this.type = 'LatheGeometry';
  20506. this.parameters = {
  20507. points: points,
  20508. segments: segments,
  20509. phiStart: phiStart,
  20510. phiLength: phiLength
  20511. };
  20512. segments = Math.floor( segments );
  20513. // clamp phiLength so it's in range of [ 0, 2PI ]
  20514. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20515. // buffers
  20516. const indices = [];
  20517. const vertices = [];
  20518. const uvs = [];
  20519. const initNormals = [];
  20520. const normals = [];
  20521. // helper variables
  20522. const inverseSegments = 1.0 / segments;
  20523. const vertex = new Vector3();
  20524. const uv = new Vector2();
  20525. const normal = new Vector3();
  20526. const curNormal = new Vector3();
  20527. const prevNormal = new Vector3();
  20528. let dx = 0;
  20529. let dy = 0;
  20530. // pre-compute normals for initial "meridian"
  20531. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20532. switch ( j ) {
  20533. case 0: // special handling for 1st vertex on path
  20534. dx = points[ j + 1 ].x - points[ j ].x;
  20535. dy = points[ j + 1 ].y - points[ j ].y;
  20536. normal.x = dy * 1.0;
  20537. normal.y = - dx;
  20538. normal.z = dy * 0.0;
  20539. prevNormal.copy( normal );
  20540. normal.normalize();
  20541. initNormals.push( normal.x, normal.y, normal.z );
  20542. break;
  20543. case ( points.length - 1 ): // special handling for last Vertex on path
  20544. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20545. break;
  20546. default: // default handling for all vertices in between
  20547. dx = points[ j + 1 ].x - points[ j ].x;
  20548. dy = points[ j + 1 ].y - points[ j ].y;
  20549. normal.x = dy * 1.0;
  20550. normal.y = - dx;
  20551. normal.z = dy * 0.0;
  20552. curNormal.copy( normal );
  20553. normal.x += prevNormal.x;
  20554. normal.y += prevNormal.y;
  20555. normal.z += prevNormal.z;
  20556. normal.normalize();
  20557. initNormals.push( normal.x, normal.y, normal.z );
  20558. prevNormal.copy( curNormal );
  20559. }
  20560. }
  20561. // generate vertices, uvs and normals
  20562. for ( let i = 0; i <= segments; i ++ ) {
  20563. const phi = phiStart + i * inverseSegments * phiLength;
  20564. const sin = Math.sin( phi );
  20565. const cos = Math.cos( phi );
  20566. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20567. // vertex
  20568. vertex.x = points[ j ].x * sin;
  20569. vertex.y = points[ j ].y;
  20570. vertex.z = points[ j ].x * cos;
  20571. vertices.push( vertex.x, vertex.y, vertex.z );
  20572. // uv
  20573. uv.x = i / segments;
  20574. uv.y = j / ( points.length - 1 );
  20575. uvs.push( uv.x, uv.y );
  20576. // normal
  20577. const x = initNormals[ 3 * j + 0 ] * sin;
  20578. const y = initNormals[ 3 * j + 1 ];
  20579. const z = initNormals[ 3 * j + 0 ] * cos;
  20580. normals.push( x, y, z );
  20581. }
  20582. }
  20583. // indices
  20584. for ( let i = 0; i < segments; i ++ ) {
  20585. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20586. const base = j + i * points.length;
  20587. const a = base;
  20588. const b = base + points.length;
  20589. const c = base + points.length + 1;
  20590. const d = base + 1;
  20591. // faces
  20592. indices.push( a, b, d );
  20593. indices.push( c, d, b );
  20594. }
  20595. }
  20596. // build geometry
  20597. this.setIndex( indices );
  20598. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20599. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20600. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20601. }
  20602. copy( source ) {
  20603. super.copy( source );
  20604. this.parameters = Object.assign( {}, source.parameters );
  20605. return this;
  20606. }
  20607. static fromJSON( data ) {
  20608. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20609. }
  20610. }
  20611. class CapsuleGeometry extends LatheGeometry {
  20612. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20613. const path = new Path();
  20614. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20615. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20616. super( path.getPoints( capSegments ), radialSegments );
  20617. this.type = 'CapsuleGeometry';
  20618. this.parameters = {
  20619. radius: radius,
  20620. height: length,
  20621. capSegments: capSegments,
  20622. radialSegments: radialSegments,
  20623. };
  20624. }
  20625. static fromJSON( data ) {
  20626. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20627. }
  20628. }
  20629. class CircleGeometry extends BufferGeometry {
  20630. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20631. super();
  20632. this.type = 'CircleGeometry';
  20633. this.parameters = {
  20634. radius: radius,
  20635. segments: segments,
  20636. thetaStart: thetaStart,
  20637. thetaLength: thetaLength
  20638. };
  20639. segments = Math.max( 3, segments );
  20640. // buffers
  20641. const indices = [];
  20642. const vertices = [];
  20643. const normals = [];
  20644. const uvs = [];
  20645. // helper variables
  20646. const vertex = new Vector3();
  20647. const uv = new Vector2();
  20648. // center point
  20649. vertices.push( 0, 0, 0 );
  20650. normals.push( 0, 0, 1 );
  20651. uvs.push( 0.5, 0.5 );
  20652. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20653. const segment = thetaStart + s / segments * thetaLength;
  20654. // vertex
  20655. vertex.x = radius * Math.cos( segment );
  20656. vertex.y = radius * Math.sin( segment );
  20657. vertices.push( vertex.x, vertex.y, vertex.z );
  20658. // normal
  20659. normals.push( 0, 0, 1 );
  20660. // uvs
  20661. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20662. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20663. uvs.push( uv.x, uv.y );
  20664. }
  20665. // indices
  20666. for ( let i = 1; i <= segments; i ++ ) {
  20667. indices.push( i, i + 1, 0 );
  20668. }
  20669. // build geometry
  20670. this.setIndex( indices );
  20671. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20672. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20673. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20674. }
  20675. copy( source ) {
  20676. super.copy( source );
  20677. this.parameters = Object.assign( {}, source.parameters );
  20678. return this;
  20679. }
  20680. static fromJSON( data ) {
  20681. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20682. }
  20683. }
  20684. class CylinderGeometry extends BufferGeometry {
  20685. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20686. super();
  20687. this.type = 'CylinderGeometry';
  20688. this.parameters = {
  20689. radiusTop: radiusTop,
  20690. radiusBottom: radiusBottom,
  20691. height: height,
  20692. radialSegments: radialSegments,
  20693. heightSegments: heightSegments,
  20694. openEnded: openEnded,
  20695. thetaStart: thetaStart,
  20696. thetaLength: thetaLength
  20697. };
  20698. const scope = this;
  20699. radialSegments = Math.floor( radialSegments );
  20700. heightSegments = Math.floor( heightSegments );
  20701. // buffers
  20702. const indices = [];
  20703. const vertices = [];
  20704. const normals = [];
  20705. const uvs = [];
  20706. // helper variables
  20707. let index = 0;
  20708. const indexArray = [];
  20709. const halfHeight = height / 2;
  20710. let groupStart = 0;
  20711. // generate geometry
  20712. generateTorso();
  20713. if ( openEnded === false ) {
  20714. if ( radiusTop > 0 ) generateCap( true );
  20715. if ( radiusBottom > 0 ) generateCap( false );
  20716. }
  20717. // build geometry
  20718. this.setIndex( indices );
  20719. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20720. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20721. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20722. function generateTorso() {
  20723. const normal = new Vector3();
  20724. const vertex = new Vector3();
  20725. let groupCount = 0;
  20726. // this will be used to calculate the normal
  20727. const slope = ( radiusBottom - radiusTop ) / height;
  20728. // generate vertices, normals and uvs
  20729. for ( let y = 0; y <= heightSegments; y ++ ) {
  20730. const indexRow = [];
  20731. const v = y / heightSegments;
  20732. // calculate the radius of the current row
  20733. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20734. for ( let x = 0; x <= radialSegments; x ++ ) {
  20735. const u = x / radialSegments;
  20736. const theta = u * thetaLength + thetaStart;
  20737. const sinTheta = Math.sin( theta );
  20738. const cosTheta = Math.cos( theta );
  20739. // vertex
  20740. vertex.x = radius * sinTheta;
  20741. vertex.y = - v * height + halfHeight;
  20742. vertex.z = radius * cosTheta;
  20743. vertices.push( vertex.x, vertex.y, vertex.z );
  20744. // normal
  20745. normal.set( sinTheta, slope, cosTheta ).normalize();
  20746. normals.push( normal.x, normal.y, normal.z );
  20747. // uv
  20748. uvs.push( u, 1 - v );
  20749. // save index of vertex in respective row
  20750. indexRow.push( index ++ );
  20751. }
  20752. // now save vertices of the row in our index array
  20753. indexArray.push( indexRow );
  20754. }
  20755. // generate indices
  20756. for ( let x = 0; x < radialSegments; x ++ ) {
  20757. for ( let y = 0; y < heightSegments; y ++ ) {
  20758. // we use the index array to access the correct indices
  20759. const a = indexArray[ y ][ x ];
  20760. const b = indexArray[ y + 1 ][ x ];
  20761. const c = indexArray[ y + 1 ][ x + 1 ];
  20762. const d = indexArray[ y ][ x + 1 ];
  20763. // faces
  20764. indices.push( a, b, d );
  20765. indices.push( b, c, d );
  20766. // update group counter
  20767. groupCount += 6;
  20768. }
  20769. }
  20770. // add a group to the geometry. this will ensure multi material support
  20771. scope.addGroup( groupStart, groupCount, 0 );
  20772. // calculate new start value for groups
  20773. groupStart += groupCount;
  20774. }
  20775. function generateCap( top ) {
  20776. // save the index of the first center vertex
  20777. const centerIndexStart = index;
  20778. const uv = new Vector2();
  20779. const vertex = new Vector3();
  20780. let groupCount = 0;
  20781. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20782. const sign = ( top === true ) ? 1 : - 1;
  20783. // first we generate the center vertex data of the cap.
  20784. // because the geometry needs one set of uvs per face,
  20785. // we must generate a center vertex per face/segment
  20786. for ( let x = 1; x <= radialSegments; x ++ ) {
  20787. // vertex
  20788. vertices.push( 0, halfHeight * sign, 0 );
  20789. // normal
  20790. normals.push( 0, sign, 0 );
  20791. // uv
  20792. uvs.push( 0.5, 0.5 );
  20793. // increase index
  20794. index ++;
  20795. }
  20796. // save the index of the last center vertex
  20797. const centerIndexEnd = index;
  20798. // now we generate the surrounding vertices, normals and uvs
  20799. for ( let x = 0; x <= radialSegments; x ++ ) {
  20800. const u = x / radialSegments;
  20801. const theta = u * thetaLength + thetaStart;
  20802. const cosTheta = Math.cos( theta );
  20803. const sinTheta = Math.sin( theta );
  20804. // vertex
  20805. vertex.x = radius * sinTheta;
  20806. vertex.y = halfHeight * sign;
  20807. vertex.z = radius * cosTheta;
  20808. vertices.push( vertex.x, vertex.y, vertex.z );
  20809. // normal
  20810. normals.push( 0, sign, 0 );
  20811. // uv
  20812. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20813. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20814. uvs.push( uv.x, uv.y );
  20815. // increase index
  20816. index ++;
  20817. }
  20818. // generate indices
  20819. for ( let x = 0; x < radialSegments; x ++ ) {
  20820. const c = centerIndexStart + x;
  20821. const i = centerIndexEnd + x;
  20822. if ( top === true ) {
  20823. // face top
  20824. indices.push( i, i + 1, c );
  20825. } else {
  20826. // face bottom
  20827. indices.push( i + 1, i, c );
  20828. }
  20829. groupCount += 3;
  20830. }
  20831. // add a group to the geometry. this will ensure multi material support
  20832. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20833. // calculate new start value for groups
  20834. groupStart += groupCount;
  20835. }
  20836. }
  20837. copy( source ) {
  20838. super.copy( source );
  20839. this.parameters = Object.assign( {}, source.parameters );
  20840. return this;
  20841. }
  20842. static fromJSON( data ) {
  20843. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20844. }
  20845. }
  20846. class ConeGeometry extends CylinderGeometry {
  20847. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20848. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20849. this.type = 'ConeGeometry';
  20850. this.parameters = {
  20851. radius: radius,
  20852. height: height,
  20853. radialSegments: radialSegments,
  20854. heightSegments: heightSegments,
  20855. openEnded: openEnded,
  20856. thetaStart: thetaStart,
  20857. thetaLength: thetaLength
  20858. };
  20859. }
  20860. static fromJSON( data ) {
  20861. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20862. }
  20863. }
  20864. class PolyhedronGeometry extends BufferGeometry {
  20865. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20866. super();
  20867. this.type = 'PolyhedronGeometry';
  20868. this.parameters = {
  20869. vertices: vertices,
  20870. indices: indices,
  20871. radius: radius,
  20872. detail: detail
  20873. };
  20874. // default buffer data
  20875. const vertexBuffer = [];
  20876. const uvBuffer = [];
  20877. // the subdivision creates the vertex buffer data
  20878. subdivide( detail );
  20879. // all vertices should lie on a conceptual sphere with a given radius
  20880. applyRadius( radius );
  20881. // finally, create the uv data
  20882. generateUVs();
  20883. // build non-indexed geometry
  20884. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20885. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20886. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20887. if ( detail === 0 ) {
  20888. this.computeVertexNormals(); // flat normals
  20889. } else {
  20890. this.normalizeNormals(); // smooth normals
  20891. }
  20892. // helper functions
  20893. function subdivide( detail ) {
  20894. const a = new Vector3();
  20895. const b = new Vector3();
  20896. const c = new Vector3();
  20897. // iterate over all faces and apply a subdivision with the given detail value
  20898. for ( let i = 0; i < indices.length; i += 3 ) {
  20899. // get the vertices of the face
  20900. getVertexByIndex( indices[ i + 0 ], a );
  20901. getVertexByIndex( indices[ i + 1 ], b );
  20902. getVertexByIndex( indices[ i + 2 ], c );
  20903. // perform subdivision
  20904. subdivideFace( a, b, c, detail );
  20905. }
  20906. }
  20907. function subdivideFace( a, b, c, detail ) {
  20908. const cols = detail + 1;
  20909. // we use this multidimensional array as a data structure for creating the subdivision
  20910. const v = [];
  20911. // construct all of the vertices for this subdivision
  20912. for ( let i = 0; i <= cols; i ++ ) {
  20913. v[ i ] = [];
  20914. const aj = a.clone().lerp( c, i / cols );
  20915. const bj = b.clone().lerp( c, i / cols );
  20916. const rows = cols - i;
  20917. for ( let j = 0; j <= rows; j ++ ) {
  20918. if ( j === 0 && i === cols ) {
  20919. v[ i ][ j ] = aj;
  20920. } else {
  20921. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20922. }
  20923. }
  20924. }
  20925. // construct all of the faces
  20926. for ( let i = 0; i < cols; i ++ ) {
  20927. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20928. const k = Math.floor( j / 2 );
  20929. if ( j % 2 === 0 ) {
  20930. pushVertex( v[ i ][ k + 1 ] );
  20931. pushVertex( v[ i + 1 ][ k ] );
  20932. pushVertex( v[ i ][ k ] );
  20933. } else {
  20934. pushVertex( v[ i ][ k + 1 ] );
  20935. pushVertex( v[ i + 1 ][ k + 1 ] );
  20936. pushVertex( v[ i + 1 ][ k ] );
  20937. }
  20938. }
  20939. }
  20940. }
  20941. function applyRadius( radius ) {
  20942. const vertex = new Vector3();
  20943. // iterate over the entire buffer and apply the radius to each vertex
  20944. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20945. vertex.x = vertexBuffer[ i + 0 ];
  20946. vertex.y = vertexBuffer[ i + 1 ];
  20947. vertex.z = vertexBuffer[ i + 2 ];
  20948. vertex.normalize().multiplyScalar( radius );
  20949. vertexBuffer[ i + 0 ] = vertex.x;
  20950. vertexBuffer[ i + 1 ] = vertex.y;
  20951. vertexBuffer[ i + 2 ] = vertex.z;
  20952. }
  20953. }
  20954. function generateUVs() {
  20955. const vertex = new Vector3();
  20956. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20957. vertex.x = vertexBuffer[ i + 0 ];
  20958. vertex.y = vertexBuffer[ i + 1 ];
  20959. vertex.z = vertexBuffer[ i + 2 ];
  20960. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20961. const v = inclination( vertex ) / Math.PI + 0.5;
  20962. uvBuffer.push( u, 1 - v );
  20963. }
  20964. correctUVs();
  20965. correctSeam();
  20966. }
  20967. function correctSeam() {
  20968. // handle case when face straddles the seam, see #3269
  20969. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20970. // uv data of a single face
  20971. const x0 = uvBuffer[ i + 0 ];
  20972. const x1 = uvBuffer[ i + 2 ];
  20973. const x2 = uvBuffer[ i + 4 ];
  20974. const max = Math.max( x0, x1, x2 );
  20975. const min = Math.min( x0, x1, x2 );
  20976. // 0.9 is somewhat arbitrary
  20977. if ( max > 0.9 && min < 0.1 ) {
  20978. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20979. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20980. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20981. }
  20982. }
  20983. }
  20984. function pushVertex( vertex ) {
  20985. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20986. }
  20987. function getVertexByIndex( index, vertex ) {
  20988. const stride = index * 3;
  20989. vertex.x = vertices[ stride + 0 ];
  20990. vertex.y = vertices[ stride + 1 ];
  20991. vertex.z = vertices[ stride + 2 ];
  20992. }
  20993. function correctUVs() {
  20994. const a = new Vector3();
  20995. const b = new Vector3();
  20996. const c = new Vector3();
  20997. const centroid = new Vector3();
  20998. const uvA = new Vector2();
  20999. const uvB = new Vector2();
  21000. const uvC = new Vector2();
  21001. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  21002. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  21003. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  21004. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  21005. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  21006. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  21007. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  21008. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  21009. const azi = azimuth( centroid );
  21010. correctUV( uvA, j + 0, a, azi );
  21011. correctUV( uvB, j + 2, b, azi );
  21012. correctUV( uvC, j + 4, c, azi );
  21013. }
  21014. }
  21015. function correctUV( uv, stride, vector, azimuth ) {
  21016. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21017. uvBuffer[ stride ] = uv.x - 1;
  21018. }
  21019. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21020. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21021. }
  21022. }
  21023. // Angle around the Y axis, counter-clockwise when looking from above.
  21024. function azimuth( vector ) {
  21025. return Math.atan2( vector.z, - vector.x );
  21026. }
  21027. // Angle above the XZ plane.
  21028. function inclination( vector ) {
  21029. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21030. }
  21031. }
  21032. copy( source ) {
  21033. super.copy( source );
  21034. this.parameters = Object.assign( {}, source.parameters );
  21035. return this;
  21036. }
  21037. static fromJSON( data ) {
  21038. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  21039. }
  21040. }
  21041. class DodecahedronGeometry extends PolyhedronGeometry {
  21042. constructor( radius = 1, detail = 0 ) {
  21043. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21044. const r = 1 / t;
  21045. const vertices = [
  21046. // (±1, ±1, ±1)
  21047. - 1, - 1, - 1, - 1, - 1, 1,
  21048. - 1, 1, - 1, - 1, 1, 1,
  21049. 1, - 1, - 1, 1, - 1, 1,
  21050. 1, 1, - 1, 1, 1, 1,
  21051. // (0, ±1/φ, ±φ)
  21052. 0, - r, - t, 0, - r, t,
  21053. 0, r, - t, 0, r, t,
  21054. // (±1/φ, ±φ, 0)
  21055. - r, - t, 0, - r, t, 0,
  21056. r, - t, 0, r, t, 0,
  21057. // (±φ, 0, ±1/φ)
  21058. - t, 0, - r, t, 0, - r,
  21059. - t, 0, r, t, 0, r
  21060. ];
  21061. const indices = [
  21062. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21063. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  21064. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  21065. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  21066. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  21067. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  21068. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  21069. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  21070. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  21071. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  21072. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  21073. 1, 12, 14, 1, 14, 5, 1, 5, 9
  21074. ];
  21075. super( vertices, indices, radius, detail );
  21076. this.type = 'DodecahedronGeometry';
  21077. this.parameters = {
  21078. radius: radius,
  21079. detail: detail
  21080. };
  21081. }
  21082. static fromJSON( data ) {
  21083. return new DodecahedronGeometry( data.radius, data.detail );
  21084. }
  21085. }
  21086. const _v0 = /*@__PURE__*/ new Vector3();
  21087. const _v1$1 = /*@__PURE__*/ new Vector3();
  21088. const _normal = /*@__PURE__*/ new Vector3();
  21089. const _triangle = /*@__PURE__*/ new Triangle();
  21090. class EdgesGeometry extends BufferGeometry {
  21091. constructor( geometry = null, thresholdAngle = 1 ) {
  21092. super();
  21093. this.type = 'EdgesGeometry';
  21094. this.parameters = {
  21095. geometry: geometry,
  21096. thresholdAngle: thresholdAngle
  21097. };
  21098. if ( geometry !== null ) {
  21099. const precisionPoints = 4;
  21100. const precision = Math.pow( 10, precisionPoints );
  21101. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  21102. const indexAttr = geometry.getIndex();
  21103. const positionAttr = geometry.getAttribute( 'position' );
  21104. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  21105. const indexArr = [ 0, 0, 0 ];
  21106. const vertKeys = [ 'a', 'b', 'c' ];
  21107. const hashes = new Array( 3 );
  21108. const edgeData = {};
  21109. const vertices = [];
  21110. for ( let i = 0; i < indexCount; i += 3 ) {
  21111. if ( indexAttr ) {
  21112. indexArr[ 0 ] = indexAttr.getX( i );
  21113. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  21114. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  21115. } else {
  21116. indexArr[ 0 ] = i;
  21117. indexArr[ 1 ] = i + 1;
  21118. indexArr[ 2 ] = i + 2;
  21119. }
  21120. const { a, b, c } = _triangle;
  21121. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  21122. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  21123. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  21124. _triangle.getNormal( _normal );
  21125. // create hashes for the edge from the vertices
  21126. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  21127. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  21128. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  21129. // skip degenerate triangles
  21130. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  21131. continue;
  21132. }
  21133. // iterate over every edge
  21134. for ( let j = 0; j < 3; j ++ ) {
  21135. // get the first and next vertex making up the edge
  21136. const jNext = ( j + 1 ) % 3;
  21137. const vecHash0 = hashes[ j ];
  21138. const vecHash1 = hashes[ jNext ];
  21139. const v0 = _triangle[ vertKeys[ j ] ];
  21140. const v1 = _triangle[ vertKeys[ jNext ] ];
  21141. const hash = `${ vecHash0 }_${ vecHash1 }`;
  21142. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  21143. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  21144. // if we found a sibling edge add it into the vertex array if
  21145. // it meets the angle threshold and delete the edge from the map.
  21146. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  21147. vertices.push( v0.x, v0.y, v0.z );
  21148. vertices.push( v1.x, v1.y, v1.z );
  21149. }
  21150. edgeData[ reverseHash ] = null;
  21151. } else if ( ! ( hash in edgeData ) ) {
  21152. // if we've already got an edge here then skip adding a new one
  21153. edgeData[ hash ] = {
  21154. index0: indexArr[ j ],
  21155. index1: indexArr[ jNext ],
  21156. normal: _normal.clone(),
  21157. };
  21158. }
  21159. }
  21160. }
  21161. // iterate over all remaining, unmatched edges and add them to the vertex array
  21162. for ( const key in edgeData ) {
  21163. if ( edgeData[ key ] ) {
  21164. const { index0, index1 } = edgeData[ key ];
  21165. _v0.fromBufferAttribute( positionAttr, index0 );
  21166. _v1$1.fromBufferAttribute( positionAttr, index1 );
  21167. vertices.push( _v0.x, _v0.y, _v0.z );
  21168. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  21169. }
  21170. }
  21171. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21172. }
  21173. }
  21174. copy( source ) {
  21175. super.copy( source );
  21176. this.parameters = Object.assign( {}, source.parameters );
  21177. return this;
  21178. }
  21179. }
  21180. class Shape extends Path {
  21181. constructor( points ) {
  21182. super( points );
  21183. this.uuid = generateUUID();
  21184. this.type = 'Shape';
  21185. this.holes = [];
  21186. }
  21187. getPointsHoles( divisions ) {
  21188. const holesPts = [];
  21189. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  21190. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21191. }
  21192. return holesPts;
  21193. }
  21194. // get points of shape and holes (keypoints based on segments parameter)
  21195. extractPoints( divisions ) {
  21196. return {
  21197. shape: this.getPoints( divisions ),
  21198. holes: this.getPointsHoles( divisions )
  21199. };
  21200. }
  21201. copy( source ) {
  21202. super.copy( source );
  21203. this.holes = [];
  21204. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  21205. const hole = source.holes[ i ];
  21206. this.holes.push( hole.clone() );
  21207. }
  21208. return this;
  21209. }
  21210. toJSON() {
  21211. const data = super.toJSON();
  21212. data.uuid = this.uuid;
  21213. data.holes = [];
  21214. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  21215. const hole = this.holes[ i ];
  21216. data.holes.push( hole.toJSON() );
  21217. }
  21218. return data;
  21219. }
  21220. fromJSON( json ) {
  21221. super.fromJSON( json );
  21222. this.uuid = json.uuid;
  21223. this.holes = [];
  21224. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  21225. const hole = json.holes[ i ];
  21226. this.holes.push( new Path().fromJSON( hole ) );
  21227. }
  21228. return this;
  21229. }
  21230. }
  21231. /**
  21232. * Port from https://github.com/mapbox/earcut (v2.2.4)
  21233. */
  21234. const Earcut = {
  21235. triangulate: function ( data, holeIndices, dim = 2 ) {
  21236. const hasHoles = holeIndices && holeIndices.length;
  21237. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  21238. let outerNode = linkedList( data, 0, outerLen, dim, true );
  21239. const triangles = [];
  21240. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  21241. let minX, minY, maxX, maxY, x, y, invSize;
  21242. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  21243. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  21244. if ( data.length > 80 * dim ) {
  21245. minX = maxX = data[ 0 ];
  21246. minY = maxY = data[ 1 ];
  21247. for ( let i = dim; i < outerLen; i += dim ) {
  21248. x = data[ i ];
  21249. y = data[ i + 1 ];
  21250. if ( x < minX ) minX = x;
  21251. if ( y < minY ) minY = y;
  21252. if ( x > maxX ) maxX = x;
  21253. if ( y > maxY ) maxY = y;
  21254. }
  21255. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  21256. invSize = Math.max( maxX - minX, maxY - minY );
  21257. invSize = invSize !== 0 ? 32767 / invSize : 0;
  21258. }
  21259. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  21260. return triangles;
  21261. }
  21262. };
  21263. // create a circular doubly linked list from polygon points in the specified winding order
  21264. function linkedList( data, start, end, dim, clockwise ) {
  21265. let i, last;
  21266. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  21267. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21268. } else {
  21269. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21270. }
  21271. if ( last && equals( last, last.next ) ) {
  21272. removeNode( last );
  21273. last = last.next;
  21274. }
  21275. return last;
  21276. }
  21277. // eliminate colinear or duplicate points
  21278. function filterPoints( start, end ) {
  21279. if ( ! start ) return start;
  21280. if ( ! end ) end = start;
  21281. let p = start,
  21282. again;
  21283. do {
  21284. again = false;
  21285. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  21286. removeNode( p );
  21287. p = end = p.prev;
  21288. if ( p === p.next ) break;
  21289. again = true;
  21290. } else {
  21291. p = p.next;
  21292. }
  21293. } while ( again || p !== end );
  21294. return end;
  21295. }
  21296. // main ear slicing loop which triangulates a polygon (given as a linked list)
  21297. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  21298. if ( ! ear ) return;
  21299. // interlink polygon nodes in z-order
  21300. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  21301. let stop = ear,
  21302. prev, next;
  21303. // iterate through ears, slicing them one by one
  21304. while ( ear.prev !== ear.next ) {
  21305. prev = ear.prev;
  21306. next = ear.next;
  21307. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  21308. // cut off the triangle
  21309. triangles.push( prev.i / dim | 0 );
  21310. triangles.push( ear.i / dim | 0 );
  21311. triangles.push( next.i / dim | 0 );
  21312. removeNode( ear );
  21313. // skipping the next vertex leads to less sliver triangles
  21314. ear = next.next;
  21315. stop = next.next;
  21316. continue;
  21317. }
  21318. ear = next;
  21319. // if we looped through the whole remaining polygon and can't find any more ears
  21320. if ( ear === stop ) {
  21321. // try filtering points and slicing again
  21322. if ( ! pass ) {
  21323. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  21324. // if this didn't work, try curing all small self-intersections locally
  21325. } else if ( pass === 1 ) {
  21326. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  21327. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  21328. // as a last resort, try splitting the remaining polygon into two
  21329. } else if ( pass === 2 ) {
  21330. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  21331. }
  21332. break;
  21333. }
  21334. }
  21335. }
  21336. // check whether a polygon node forms a valid ear with adjacent nodes
  21337. function isEar( ear ) {
  21338. const a = ear.prev,
  21339. b = ear,
  21340. c = ear.next;
  21341. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21342. // now make sure we don't have other points inside the potential ear
  21343. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21344. // triangle bbox; min & max are calculated like this for speed
  21345. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21346. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21347. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21348. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21349. let p = c.next;
  21350. while ( p !== a ) {
  21351. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  21352. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  21353. area( p.prev, p, p.next ) >= 0 ) return false;
  21354. p = p.next;
  21355. }
  21356. return true;
  21357. }
  21358. function isEarHashed( ear, minX, minY, invSize ) {
  21359. const a = ear.prev,
  21360. b = ear,
  21361. c = ear.next;
  21362. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21363. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21364. // triangle bbox; min & max are calculated like this for speed
  21365. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21366. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21367. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21368. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21369. // z-order range for the current triangle bbox;
  21370. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  21371. maxZ = zOrder( x1, y1, minX, minY, invSize );
  21372. let p = ear.prevZ,
  21373. n = ear.nextZ;
  21374. // look for points inside the triangle in both directions
  21375. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  21376. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21377. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21378. p = p.prevZ;
  21379. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21380. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21381. n = n.nextZ;
  21382. }
  21383. // look for remaining points in decreasing z-order
  21384. while ( p && p.z >= minZ ) {
  21385. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21386. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21387. p = p.prevZ;
  21388. }
  21389. // look for remaining points in increasing z-order
  21390. while ( n && n.z <= maxZ ) {
  21391. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21392. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21393. n = n.nextZ;
  21394. }
  21395. return true;
  21396. }
  21397. // go through all polygon nodes and cure small local self-intersections
  21398. function cureLocalIntersections( start, triangles, dim ) {
  21399. let p = start;
  21400. do {
  21401. const a = p.prev,
  21402. b = p.next.next;
  21403. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21404. triangles.push( a.i / dim | 0 );
  21405. triangles.push( p.i / dim | 0 );
  21406. triangles.push( b.i / dim | 0 );
  21407. // remove two nodes involved
  21408. removeNode( p );
  21409. removeNode( p.next );
  21410. p = start = b;
  21411. }
  21412. p = p.next;
  21413. } while ( p !== start );
  21414. return filterPoints( p );
  21415. }
  21416. // try splitting polygon into two and triangulate them independently
  21417. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21418. // look for a valid diagonal that divides the polygon into two
  21419. let a = start;
  21420. do {
  21421. let b = a.next.next;
  21422. while ( b !== a.prev ) {
  21423. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21424. // split the polygon in two by the diagonal
  21425. let c = splitPolygon( a, b );
  21426. // filter colinear points around the cuts
  21427. a = filterPoints( a, a.next );
  21428. c = filterPoints( c, c.next );
  21429. // run earcut on each half
  21430. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  21431. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  21432. return;
  21433. }
  21434. b = b.next;
  21435. }
  21436. a = a.next;
  21437. } while ( a !== start );
  21438. }
  21439. // link every hole into the outer loop, producing a single-ring polygon without holes
  21440. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21441. const queue = [];
  21442. let i, len, start, end, list;
  21443. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21444. start = holeIndices[ i ] * dim;
  21445. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21446. list = linkedList( data, start, end, dim, false );
  21447. if ( list === list.next ) list.steiner = true;
  21448. queue.push( getLeftmost( list ) );
  21449. }
  21450. queue.sort( compareX );
  21451. // process holes from left to right
  21452. for ( i = 0; i < queue.length; i ++ ) {
  21453. outerNode = eliminateHole( queue[ i ], outerNode );
  21454. }
  21455. return outerNode;
  21456. }
  21457. function compareX( a, b ) {
  21458. return a.x - b.x;
  21459. }
  21460. // find a bridge between vertices that connects hole with an outer ring and link it
  21461. function eliminateHole( hole, outerNode ) {
  21462. const bridge = findHoleBridge( hole, outerNode );
  21463. if ( ! bridge ) {
  21464. return outerNode;
  21465. }
  21466. const bridgeReverse = splitPolygon( bridge, hole );
  21467. // filter collinear points around the cuts
  21468. filterPoints( bridgeReverse, bridgeReverse.next );
  21469. return filterPoints( bridge, bridge.next );
  21470. }
  21471. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21472. function findHoleBridge( hole, outerNode ) {
  21473. let p = outerNode,
  21474. qx = - Infinity,
  21475. m;
  21476. const hx = hole.x, hy = hole.y;
  21477. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21478. // segment's endpoint with lesser x will be potential connection point
  21479. do {
  21480. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21481. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21482. if ( x <= hx && x > qx ) {
  21483. qx = x;
  21484. m = p.x < p.next.x ? p : p.next;
  21485. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21486. }
  21487. }
  21488. p = p.next;
  21489. } while ( p !== outerNode );
  21490. if ( ! m ) return null;
  21491. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21492. // if there are no points found, we have a valid connection;
  21493. // otherwise choose the point of the minimum angle with the ray as connection point
  21494. const stop = m,
  21495. mx = m.x,
  21496. my = m.y;
  21497. let tanMin = Infinity, tan;
  21498. p = m;
  21499. do {
  21500. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21501. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21502. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21503. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21504. m = p;
  21505. tanMin = tan;
  21506. }
  21507. }
  21508. p = p.next;
  21509. } while ( p !== stop );
  21510. return m;
  21511. }
  21512. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21513. function sectorContainsSector( m, p ) {
  21514. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21515. }
  21516. // interlink polygon nodes in z-order
  21517. function indexCurve( start, minX, minY, invSize ) {
  21518. let p = start;
  21519. do {
  21520. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21521. p.prevZ = p.prev;
  21522. p.nextZ = p.next;
  21523. p = p.next;
  21524. } while ( p !== start );
  21525. p.prevZ.nextZ = null;
  21526. p.prevZ = null;
  21527. sortLinked( p );
  21528. }
  21529. // Simon Tatham's linked list merge sort algorithm
  21530. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21531. function sortLinked( list ) {
  21532. let i, p, q, e, tail, numMerges, pSize, qSize,
  21533. inSize = 1;
  21534. do {
  21535. p = list;
  21536. list = null;
  21537. tail = null;
  21538. numMerges = 0;
  21539. while ( p ) {
  21540. numMerges ++;
  21541. q = p;
  21542. pSize = 0;
  21543. for ( i = 0; i < inSize; i ++ ) {
  21544. pSize ++;
  21545. q = q.nextZ;
  21546. if ( ! q ) break;
  21547. }
  21548. qSize = inSize;
  21549. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21550. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21551. e = p;
  21552. p = p.nextZ;
  21553. pSize --;
  21554. } else {
  21555. e = q;
  21556. q = q.nextZ;
  21557. qSize --;
  21558. }
  21559. if ( tail ) tail.nextZ = e;
  21560. else list = e;
  21561. e.prevZ = tail;
  21562. tail = e;
  21563. }
  21564. p = q;
  21565. }
  21566. tail.nextZ = null;
  21567. inSize *= 2;
  21568. } while ( numMerges > 1 );
  21569. return list;
  21570. }
  21571. // z-order of a point given coords and inverse of the longer side of data bbox
  21572. function zOrder( x, y, minX, minY, invSize ) {
  21573. // coords are transformed into non-negative 15-bit integer range
  21574. x = ( x - minX ) * invSize | 0;
  21575. y = ( y - minY ) * invSize | 0;
  21576. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21577. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21578. x = ( x | ( x << 2 ) ) & 0x33333333;
  21579. x = ( x | ( x << 1 ) ) & 0x55555555;
  21580. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21581. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21582. y = ( y | ( y << 2 ) ) & 0x33333333;
  21583. y = ( y | ( y << 1 ) ) & 0x55555555;
  21584. return x | ( y << 1 );
  21585. }
  21586. // find the leftmost node of a polygon ring
  21587. function getLeftmost( start ) {
  21588. let p = start,
  21589. leftmost = start;
  21590. do {
  21591. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21592. p = p.next;
  21593. } while ( p !== start );
  21594. return leftmost;
  21595. }
  21596. // check if a point lies within a convex triangle
  21597. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21598. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21599. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21600. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21601. }
  21602. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21603. function isValidDiagonal( a, b ) {
  21604. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21605. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21606. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21607. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21608. }
  21609. // signed area of a triangle
  21610. function area( p, q, r ) {
  21611. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21612. }
  21613. // check if two points are equal
  21614. function equals( p1, p2 ) {
  21615. return p1.x === p2.x && p1.y === p2.y;
  21616. }
  21617. // check if two segments intersect
  21618. function intersects( p1, q1, p2, q2 ) {
  21619. const o1 = sign( area( p1, q1, p2 ) );
  21620. const o2 = sign( area( p1, q1, q2 ) );
  21621. const o3 = sign( area( p2, q2, p1 ) );
  21622. const o4 = sign( area( p2, q2, q1 ) );
  21623. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21624. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21625. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21626. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21627. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21628. return false;
  21629. }
  21630. // for collinear points p, q, r, check if point q lies on segment pr
  21631. function onSegment( p, q, r ) {
  21632. 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 );
  21633. }
  21634. function sign( num ) {
  21635. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21636. }
  21637. // check if a polygon diagonal intersects any polygon segments
  21638. function intersectsPolygon( a, b ) {
  21639. let p = a;
  21640. do {
  21641. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21642. intersects( p, p.next, a, b ) ) return true;
  21643. p = p.next;
  21644. } while ( p !== a );
  21645. return false;
  21646. }
  21647. // check if a polygon diagonal is locally inside the polygon
  21648. function locallyInside( a, b ) {
  21649. return area( a.prev, a, a.next ) < 0 ?
  21650. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21651. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21652. }
  21653. // check if the middle point of a polygon diagonal is inside the polygon
  21654. function middleInside( a, b ) {
  21655. let p = a,
  21656. inside = false;
  21657. const px = ( a.x + b.x ) / 2,
  21658. py = ( a.y + b.y ) / 2;
  21659. do {
  21660. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21661. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21662. inside = ! inside;
  21663. p = p.next;
  21664. } while ( p !== a );
  21665. return inside;
  21666. }
  21667. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21668. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21669. function splitPolygon( a, b ) {
  21670. const a2 = new Node( a.i, a.x, a.y ),
  21671. b2 = new Node( b.i, b.x, b.y ),
  21672. an = a.next,
  21673. bp = b.prev;
  21674. a.next = b;
  21675. b.prev = a;
  21676. a2.next = an;
  21677. an.prev = a2;
  21678. b2.next = a2;
  21679. a2.prev = b2;
  21680. bp.next = b2;
  21681. b2.prev = bp;
  21682. return b2;
  21683. }
  21684. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21685. function insertNode( i, x, y, last ) {
  21686. const p = new Node( i, x, y );
  21687. if ( ! last ) {
  21688. p.prev = p;
  21689. p.next = p;
  21690. } else {
  21691. p.next = last.next;
  21692. p.prev = last;
  21693. last.next.prev = p;
  21694. last.next = p;
  21695. }
  21696. return p;
  21697. }
  21698. function removeNode( p ) {
  21699. p.next.prev = p.prev;
  21700. p.prev.next = p.next;
  21701. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21702. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21703. }
  21704. function Node( i, x, y ) {
  21705. // vertex index in coordinates array
  21706. this.i = i;
  21707. // vertex coordinates
  21708. this.x = x;
  21709. this.y = y;
  21710. // previous and next vertex nodes in a polygon ring
  21711. this.prev = null;
  21712. this.next = null;
  21713. // z-order curve value
  21714. this.z = 0;
  21715. // previous and next nodes in z-order
  21716. this.prevZ = null;
  21717. this.nextZ = null;
  21718. // indicates whether this is a steiner point
  21719. this.steiner = false;
  21720. }
  21721. function signedArea( data, start, end, dim ) {
  21722. let sum = 0;
  21723. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21724. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21725. j = i;
  21726. }
  21727. return sum;
  21728. }
  21729. class ShapeUtils {
  21730. // calculate area of the contour polygon
  21731. static area( contour ) {
  21732. const n = contour.length;
  21733. let a = 0.0;
  21734. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21735. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21736. }
  21737. return a * 0.5;
  21738. }
  21739. static isClockWise( pts ) {
  21740. return ShapeUtils.area( pts ) < 0;
  21741. }
  21742. static triangulateShape( contour, holes ) {
  21743. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21744. const holeIndices = []; // array of hole indices
  21745. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21746. removeDupEndPts( contour );
  21747. addContour( vertices, contour );
  21748. //
  21749. let holeIndex = contour.length;
  21750. holes.forEach( removeDupEndPts );
  21751. for ( let i = 0; i < holes.length; i ++ ) {
  21752. holeIndices.push( holeIndex );
  21753. holeIndex += holes[ i ].length;
  21754. addContour( vertices, holes[ i ] );
  21755. }
  21756. //
  21757. const triangles = Earcut.triangulate( vertices, holeIndices );
  21758. //
  21759. for ( let i = 0; i < triangles.length; i += 3 ) {
  21760. faces.push( triangles.slice( i, i + 3 ) );
  21761. }
  21762. return faces;
  21763. }
  21764. }
  21765. function removeDupEndPts( points ) {
  21766. const l = points.length;
  21767. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21768. points.pop();
  21769. }
  21770. }
  21771. function addContour( vertices, contour ) {
  21772. for ( let i = 0; i < contour.length; i ++ ) {
  21773. vertices.push( contour[ i ].x );
  21774. vertices.push( contour[ i ].y );
  21775. }
  21776. }
  21777. /**
  21778. * Creates extruded geometry from a path shape.
  21779. *
  21780. * parameters = {
  21781. *
  21782. * curveSegments: <int>, // number of points on the curves
  21783. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21784. * depth: <float>, // Depth to extrude the shape
  21785. *
  21786. * bevelEnabled: <bool>, // turn on bevel
  21787. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21788. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21789. * bevelOffset: <float>, // how far from shape outline does bevel start
  21790. * bevelSegments: <int>, // number of bevel layers
  21791. *
  21792. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21793. *
  21794. * UVGenerator: <Object> // object that provides UV generator functions
  21795. *
  21796. * }
  21797. */
  21798. class ExtrudeGeometry extends BufferGeometry {
  21799. 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 = {} ) {
  21800. super();
  21801. this.type = 'ExtrudeGeometry';
  21802. this.parameters = {
  21803. shapes: shapes,
  21804. options: options
  21805. };
  21806. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21807. const scope = this;
  21808. const verticesArray = [];
  21809. const uvArray = [];
  21810. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21811. const shape = shapes[ i ];
  21812. addShape( shape );
  21813. }
  21814. // build geometry
  21815. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21816. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21817. this.computeVertexNormals();
  21818. // functions
  21819. function addShape( shape ) {
  21820. const placeholder = [];
  21821. // options
  21822. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21823. const steps = options.steps !== undefined ? options.steps : 1;
  21824. const depth = options.depth !== undefined ? options.depth : 1;
  21825. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21826. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21827. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21828. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21829. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21830. const extrudePath = options.extrudePath;
  21831. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21832. //
  21833. let extrudePts, extrudeByPath = false;
  21834. let splineTube, binormal, normal, position2;
  21835. if ( extrudePath ) {
  21836. extrudePts = extrudePath.getSpacedPoints( steps );
  21837. extrudeByPath = true;
  21838. bevelEnabled = false; // bevels not supported for path extrusion
  21839. // SETUP TNB variables
  21840. // TODO1 - have a .isClosed in spline?
  21841. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21842. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21843. binormal = new Vector3();
  21844. normal = new Vector3();
  21845. position2 = new Vector3();
  21846. }
  21847. // Safeguards if bevels are not enabled
  21848. if ( ! bevelEnabled ) {
  21849. bevelSegments = 0;
  21850. bevelThickness = 0;
  21851. bevelSize = 0;
  21852. bevelOffset = 0;
  21853. }
  21854. // Variables initialization
  21855. const shapePoints = shape.extractPoints( curveSegments );
  21856. let vertices = shapePoints.shape;
  21857. const holes = shapePoints.holes;
  21858. const reverse = ! ShapeUtils.isClockWise( vertices );
  21859. if ( reverse ) {
  21860. vertices = vertices.reverse();
  21861. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21862. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21863. const ahole = holes[ h ];
  21864. if ( ShapeUtils.isClockWise( ahole ) ) {
  21865. holes[ h ] = ahole.reverse();
  21866. }
  21867. }
  21868. }
  21869. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21870. /* Vertices */
  21871. const contour = vertices; // vertices has all points but contour has only points of circumference
  21872. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21873. const ahole = holes[ h ];
  21874. vertices = vertices.concat( ahole );
  21875. }
  21876. function scalePt2( pt, vec, size ) {
  21877. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21878. return pt.clone().addScaledVector( vec, size );
  21879. }
  21880. const vlen = vertices.length, flen = faces.length;
  21881. // Find directions for point movement
  21882. function getBevelVec( inPt, inPrev, inNext ) {
  21883. // computes for inPt the corresponding point inPt' on a new contour
  21884. // shifted by 1 unit (length of normalized vector) to the left
  21885. // if we walk along contour clockwise, this new contour is outside the old one
  21886. //
  21887. // inPt' is the intersection of the two lines parallel to the two
  21888. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21889. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21890. // good reading for geometry algorithms (here: line-line intersection)
  21891. // http://geomalgorithms.com/a05-_intersect-1.html
  21892. const v_prev_x = inPt.x - inPrev.x,
  21893. v_prev_y = inPt.y - inPrev.y;
  21894. const v_next_x = inNext.x - inPt.x,
  21895. v_next_y = inNext.y - inPt.y;
  21896. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21897. // check for collinear edges
  21898. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21899. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21900. // not collinear
  21901. // length of vectors for normalizing
  21902. const v_prev_len = Math.sqrt( v_prev_lensq );
  21903. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21904. // shift adjacent points by unit vectors to the left
  21905. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21906. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21907. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21908. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21909. // scaling factor for v_prev to intersection point
  21910. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21911. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21912. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21913. // vector from inPt to intersection point
  21914. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21915. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21916. // Don't normalize!, otherwise sharp corners become ugly
  21917. // but prevent crazy spikes
  21918. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21919. if ( v_trans_lensq <= 2 ) {
  21920. return new Vector2( v_trans_x, v_trans_y );
  21921. } else {
  21922. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21923. }
  21924. } else {
  21925. // handle special case of collinear edges
  21926. let direction_eq = false; // assumes: opposite
  21927. if ( v_prev_x > Number.EPSILON ) {
  21928. if ( v_next_x > Number.EPSILON ) {
  21929. direction_eq = true;
  21930. }
  21931. } else {
  21932. if ( v_prev_x < - Number.EPSILON ) {
  21933. if ( v_next_x < - Number.EPSILON ) {
  21934. direction_eq = true;
  21935. }
  21936. } else {
  21937. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21938. direction_eq = true;
  21939. }
  21940. }
  21941. }
  21942. if ( direction_eq ) {
  21943. // console.log("Warning: lines are a straight sequence");
  21944. v_trans_x = - v_prev_y;
  21945. v_trans_y = v_prev_x;
  21946. shrink_by = Math.sqrt( v_prev_lensq );
  21947. } else {
  21948. // console.log("Warning: lines are a straight spike");
  21949. v_trans_x = v_prev_x;
  21950. v_trans_y = v_prev_y;
  21951. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21952. }
  21953. }
  21954. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21955. }
  21956. const contourMovements = [];
  21957. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21958. if ( j === il ) j = 0;
  21959. if ( k === il ) k = 0;
  21960. // (j)---(i)---(k)
  21961. // console.log('i,j,k', i, j , k)
  21962. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21963. }
  21964. const holesMovements = [];
  21965. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21966. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21967. const ahole = holes[ h ];
  21968. oneHoleMovements = [];
  21969. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21970. if ( j === il ) j = 0;
  21971. if ( k === il ) k = 0;
  21972. // (j)---(i)---(k)
  21973. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21974. }
  21975. holesMovements.push( oneHoleMovements );
  21976. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21977. }
  21978. // Loop bevelSegments, 1 for the front, 1 for the back
  21979. for ( let b = 0; b < bevelSegments; b ++ ) {
  21980. //for ( b = bevelSegments; b > 0; b -- ) {
  21981. const t = b / bevelSegments;
  21982. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21983. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21984. // contract shape
  21985. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21986. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21987. v( vert.x, vert.y, - z );
  21988. }
  21989. // expand holes
  21990. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21991. const ahole = holes[ h ];
  21992. oneHoleMovements = holesMovements[ h ];
  21993. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21994. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21995. v( vert.x, vert.y, - z );
  21996. }
  21997. }
  21998. }
  21999. const bs = bevelSize + bevelOffset;
  22000. // Back facing vertices
  22001. for ( let i = 0; i < vlen; i ++ ) {
  22002. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22003. if ( ! extrudeByPath ) {
  22004. v( vert.x, vert.y, 0 );
  22005. } else {
  22006. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22007. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22008. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22009. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22010. v( position2.x, position2.y, position2.z );
  22011. }
  22012. }
  22013. // Add stepped vertices...
  22014. // Including front facing vertices
  22015. for ( let s = 1; s <= steps; s ++ ) {
  22016. for ( let i = 0; i < vlen; i ++ ) {
  22017. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22018. if ( ! extrudeByPath ) {
  22019. v( vert.x, vert.y, depth / steps * s );
  22020. } else {
  22021. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22022. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22023. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22024. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22025. v( position2.x, position2.y, position2.z );
  22026. }
  22027. }
  22028. }
  22029. // Add bevel segments planes
  22030. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22031. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  22032. const t = b / bevelSegments;
  22033. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22034. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22035. // contract shape
  22036. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22037. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22038. v( vert.x, vert.y, depth + z );
  22039. }
  22040. // expand holes
  22041. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22042. const ahole = holes[ h ];
  22043. oneHoleMovements = holesMovements[ h ];
  22044. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22045. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22046. if ( ! extrudeByPath ) {
  22047. v( vert.x, vert.y, depth + z );
  22048. } else {
  22049. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22050. }
  22051. }
  22052. }
  22053. }
  22054. /* Faces */
  22055. // Top and bottom faces
  22056. buildLidFaces();
  22057. // Sides faces
  22058. buildSideFaces();
  22059. ///// Internal functions
  22060. function buildLidFaces() {
  22061. const start = verticesArray.length / 3;
  22062. if ( bevelEnabled ) {
  22063. let layer = 0; // steps + 1
  22064. let offset = vlen * layer;
  22065. // Bottom faces
  22066. for ( let i = 0; i < flen; i ++ ) {
  22067. const face = faces[ i ];
  22068. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22069. }
  22070. layer = steps + bevelSegments * 2;
  22071. offset = vlen * layer;
  22072. // Top faces
  22073. for ( let i = 0; i < flen; i ++ ) {
  22074. const face = faces[ i ];
  22075. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  22076. }
  22077. } else {
  22078. // Bottom faces
  22079. for ( let i = 0; i < flen; i ++ ) {
  22080. const face = faces[ i ];
  22081. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  22082. }
  22083. // Top faces
  22084. for ( let i = 0; i < flen; i ++ ) {
  22085. const face = faces[ i ];
  22086. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  22087. }
  22088. }
  22089. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  22090. }
  22091. // Create faces for the z-sides of the shape
  22092. function buildSideFaces() {
  22093. const start = verticesArray.length / 3;
  22094. let layeroffset = 0;
  22095. sidewalls( contour, layeroffset );
  22096. layeroffset += contour.length;
  22097. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22098. const ahole = holes[ h ];
  22099. sidewalls( ahole, layeroffset );
  22100. //, true
  22101. layeroffset += ahole.length;
  22102. }
  22103. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  22104. }
  22105. function sidewalls( contour, layeroffset ) {
  22106. let i = contour.length;
  22107. while ( -- i >= 0 ) {
  22108. const j = i;
  22109. let k = i - 1;
  22110. if ( k < 0 ) k = contour.length - 1;
  22111. //console.log('b', i,j, i-1, k,vertices.length);
  22112. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  22113. const slen1 = vlen * s;
  22114. const slen2 = vlen * ( s + 1 );
  22115. const a = layeroffset + j + slen1,
  22116. b = layeroffset + k + slen1,
  22117. c = layeroffset + k + slen2,
  22118. d = layeroffset + j + slen2;
  22119. f4( a, b, c, d );
  22120. }
  22121. }
  22122. }
  22123. function v( x, y, z ) {
  22124. placeholder.push( x );
  22125. placeholder.push( y );
  22126. placeholder.push( z );
  22127. }
  22128. function f3( a, b, c ) {
  22129. addVertex( a );
  22130. addVertex( b );
  22131. addVertex( c );
  22132. const nextIndex = verticesArray.length / 3;
  22133. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22134. addUV( uvs[ 0 ] );
  22135. addUV( uvs[ 1 ] );
  22136. addUV( uvs[ 2 ] );
  22137. }
  22138. function f4( a, b, c, d ) {
  22139. addVertex( a );
  22140. addVertex( b );
  22141. addVertex( d );
  22142. addVertex( b );
  22143. addVertex( c );
  22144. addVertex( d );
  22145. const nextIndex = verticesArray.length / 3;
  22146. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22147. addUV( uvs[ 0 ] );
  22148. addUV( uvs[ 1 ] );
  22149. addUV( uvs[ 3 ] );
  22150. addUV( uvs[ 1 ] );
  22151. addUV( uvs[ 2 ] );
  22152. addUV( uvs[ 3 ] );
  22153. }
  22154. function addVertex( index ) {
  22155. verticesArray.push( placeholder[ index * 3 + 0 ] );
  22156. verticesArray.push( placeholder[ index * 3 + 1 ] );
  22157. verticesArray.push( placeholder[ index * 3 + 2 ] );
  22158. }
  22159. function addUV( vector2 ) {
  22160. uvArray.push( vector2.x );
  22161. uvArray.push( vector2.y );
  22162. }
  22163. }
  22164. }
  22165. copy( source ) {
  22166. super.copy( source );
  22167. this.parameters = Object.assign( {}, source.parameters );
  22168. return this;
  22169. }
  22170. toJSON() {
  22171. const data = super.toJSON();
  22172. const shapes = this.parameters.shapes;
  22173. const options = this.parameters.options;
  22174. return toJSON$1( shapes, options, data );
  22175. }
  22176. static fromJSON( data, shapes ) {
  22177. const geometryShapes = [];
  22178. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22179. const shape = shapes[ data.shapes[ j ] ];
  22180. geometryShapes.push( shape );
  22181. }
  22182. const extrudePath = data.options.extrudePath;
  22183. if ( extrudePath !== undefined ) {
  22184. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  22185. }
  22186. return new ExtrudeGeometry( geometryShapes, data.options );
  22187. }
  22188. }
  22189. const WorldUVGenerator = {
  22190. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  22191. const a_x = vertices[ indexA * 3 ];
  22192. const a_y = vertices[ indexA * 3 + 1 ];
  22193. const b_x = vertices[ indexB * 3 ];
  22194. const b_y = vertices[ indexB * 3 + 1 ];
  22195. const c_x = vertices[ indexC * 3 ];
  22196. const c_y = vertices[ indexC * 3 + 1 ];
  22197. return [
  22198. new Vector2( a_x, a_y ),
  22199. new Vector2( b_x, b_y ),
  22200. new Vector2( c_x, c_y )
  22201. ];
  22202. },
  22203. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  22204. const a_x = vertices[ indexA * 3 ];
  22205. const a_y = vertices[ indexA * 3 + 1 ];
  22206. const a_z = vertices[ indexA * 3 + 2 ];
  22207. const b_x = vertices[ indexB * 3 ];
  22208. const b_y = vertices[ indexB * 3 + 1 ];
  22209. const b_z = vertices[ indexB * 3 + 2 ];
  22210. const c_x = vertices[ indexC * 3 ];
  22211. const c_y = vertices[ indexC * 3 + 1 ];
  22212. const c_z = vertices[ indexC * 3 + 2 ];
  22213. const d_x = vertices[ indexD * 3 ];
  22214. const d_y = vertices[ indexD * 3 + 1 ];
  22215. const d_z = vertices[ indexD * 3 + 2 ];
  22216. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  22217. return [
  22218. new Vector2( a_x, 1 - a_z ),
  22219. new Vector2( b_x, 1 - b_z ),
  22220. new Vector2( c_x, 1 - c_z ),
  22221. new Vector2( d_x, 1 - d_z )
  22222. ];
  22223. } else {
  22224. return [
  22225. new Vector2( a_y, 1 - a_z ),
  22226. new Vector2( b_y, 1 - b_z ),
  22227. new Vector2( c_y, 1 - c_z ),
  22228. new Vector2( d_y, 1 - d_z )
  22229. ];
  22230. }
  22231. }
  22232. };
  22233. function toJSON$1( shapes, options, data ) {
  22234. data.shapes = [];
  22235. if ( Array.isArray( shapes ) ) {
  22236. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22237. const shape = shapes[ i ];
  22238. data.shapes.push( shape.uuid );
  22239. }
  22240. } else {
  22241. data.shapes.push( shapes.uuid );
  22242. }
  22243. data.options = Object.assign( {}, options );
  22244. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  22245. return data;
  22246. }
  22247. class IcosahedronGeometry extends PolyhedronGeometry {
  22248. constructor( radius = 1, detail = 0 ) {
  22249. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22250. const vertices = [
  22251. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22252. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22253. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22254. ];
  22255. const indices = [
  22256. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22257. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22258. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22259. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22260. ];
  22261. super( vertices, indices, radius, detail );
  22262. this.type = 'IcosahedronGeometry';
  22263. this.parameters = {
  22264. radius: radius,
  22265. detail: detail
  22266. };
  22267. }
  22268. static fromJSON( data ) {
  22269. return new IcosahedronGeometry( data.radius, data.detail );
  22270. }
  22271. }
  22272. class OctahedronGeometry extends PolyhedronGeometry {
  22273. constructor( radius = 1, detail = 0 ) {
  22274. const vertices = [
  22275. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  22276. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22277. ];
  22278. const indices = [
  22279. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  22280. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  22281. 1, 3, 4, 1, 4, 2
  22282. ];
  22283. super( vertices, indices, radius, detail );
  22284. this.type = 'OctahedronGeometry';
  22285. this.parameters = {
  22286. radius: radius,
  22287. detail: detail
  22288. };
  22289. }
  22290. static fromJSON( data ) {
  22291. return new OctahedronGeometry( data.radius, data.detail );
  22292. }
  22293. }
  22294. class RingGeometry extends BufferGeometry {
  22295. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22296. super();
  22297. this.type = 'RingGeometry';
  22298. this.parameters = {
  22299. innerRadius: innerRadius,
  22300. outerRadius: outerRadius,
  22301. thetaSegments: thetaSegments,
  22302. phiSegments: phiSegments,
  22303. thetaStart: thetaStart,
  22304. thetaLength: thetaLength
  22305. };
  22306. thetaSegments = Math.max( 3, thetaSegments );
  22307. phiSegments = Math.max( 1, phiSegments );
  22308. // buffers
  22309. const indices = [];
  22310. const vertices = [];
  22311. const normals = [];
  22312. const uvs = [];
  22313. // some helper variables
  22314. let radius = innerRadius;
  22315. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22316. const vertex = new Vector3();
  22317. const uv = new Vector2();
  22318. // generate vertices, normals and uvs
  22319. for ( let j = 0; j <= phiSegments; j ++ ) {
  22320. for ( let i = 0; i <= thetaSegments; i ++ ) {
  22321. // values are generate from the inside of the ring to the outside
  22322. const segment = thetaStart + i / thetaSegments * thetaLength;
  22323. // vertex
  22324. vertex.x = radius * Math.cos( segment );
  22325. vertex.y = radius * Math.sin( segment );
  22326. vertices.push( vertex.x, vertex.y, vertex.z );
  22327. // normal
  22328. normals.push( 0, 0, 1 );
  22329. // uv
  22330. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22331. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22332. uvs.push( uv.x, uv.y );
  22333. }
  22334. // increase the radius for next row of vertices
  22335. radius += radiusStep;
  22336. }
  22337. // indices
  22338. for ( let j = 0; j < phiSegments; j ++ ) {
  22339. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  22340. for ( let i = 0; i < thetaSegments; i ++ ) {
  22341. const segment = i + thetaSegmentLevel;
  22342. const a = segment;
  22343. const b = segment + thetaSegments + 1;
  22344. const c = segment + thetaSegments + 2;
  22345. const d = segment + 1;
  22346. // faces
  22347. indices.push( a, b, d );
  22348. indices.push( b, c, d );
  22349. }
  22350. }
  22351. // build geometry
  22352. this.setIndex( indices );
  22353. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22354. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22355. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22356. }
  22357. copy( source ) {
  22358. super.copy( source );
  22359. this.parameters = Object.assign( {}, source.parameters );
  22360. return this;
  22361. }
  22362. static fromJSON( data ) {
  22363. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  22364. }
  22365. }
  22366. class ShapeGeometry extends BufferGeometry {
  22367. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  22368. super();
  22369. this.type = 'ShapeGeometry';
  22370. this.parameters = {
  22371. shapes: shapes,
  22372. curveSegments: curveSegments
  22373. };
  22374. // buffers
  22375. const indices = [];
  22376. const vertices = [];
  22377. const normals = [];
  22378. const uvs = [];
  22379. // helper variables
  22380. let groupStart = 0;
  22381. let groupCount = 0;
  22382. // allow single and array values for "shapes" parameter
  22383. if ( Array.isArray( shapes ) === false ) {
  22384. addShape( shapes );
  22385. } else {
  22386. for ( let i = 0; i < shapes.length; i ++ ) {
  22387. addShape( shapes[ i ] );
  22388. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  22389. groupStart += groupCount;
  22390. groupCount = 0;
  22391. }
  22392. }
  22393. // build geometry
  22394. this.setIndex( indices );
  22395. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22396. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22397. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22398. // helper functions
  22399. function addShape( shape ) {
  22400. const indexOffset = vertices.length / 3;
  22401. const points = shape.extractPoints( curveSegments );
  22402. let shapeVertices = points.shape;
  22403. const shapeHoles = points.holes;
  22404. // check direction of vertices
  22405. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  22406. shapeVertices = shapeVertices.reverse();
  22407. }
  22408. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22409. const shapeHole = shapeHoles[ i ];
  22410. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  22411. shapeHoles[ i ] = shapeHole.reverse();
  22412. }
  22413. }
  22414. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  22415. // join vertices of inner and outer paths to a single array
  22416. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22417. const shapeHole = shapeHoles[ i ];
  22418. shapeVertices = shapeVertices.concat( shapeHole );
  22419. }
  22420. // vertices, normals, uvs
  22421. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  22422. const vertex = shapeVertices[ i ];
  22423. vertices.push( vertex.x, vertex.y, 0 );
  22424. normals.push( 0, 0, 1 );
  22425. uvs.push( vertex.x, vertex.y ); // world uvs
  22426. }
  22427. // indices
  22428. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  22429. const face = faces[ i ];
  22430. const a = face[ 0 ] + indexOffset;
  22431. const b = face[ 1 ] + indexOffset;
  22432. const c = face[ 2 ] + indexOffset;
  22433. indices.push( a, b, c );
  22434. groupCount += 3;
  22435. }
  22436. }
  22437. }
  22438. copy( source ) {
  22439. super.copy( source );
  22440. this.parameters = Object.assign( {}, source.parameters );
  22441. return this;
  22442. }
  22443. toJSON() {
  22444. const data = super.toJSON();
  22445. const shapes = this.parameters.shapes;
  22446. return toJSON( shapes, data );
  22447. }
  22448. static fromJSON( data, shapes ) {
  22449. const geometryShapes = [];
  22450. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22451. const shape = shapes[ data.shapes[ j ] ];
  22452. geometryShapes.push( shape );
  22453. }
  22454. return new ShapeGeometry( geometryShapes, data.curveSegments );
  22455. }
  22456. }
  22457. function toJSON( shapes, data ) {
  22458. data.shapes = [];
  22459. if ( Array.isArray( shapes ) ) {
  22460. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22461. const shape = shapes[ i ];
  22462. data.shapes.push( shape.uuid );
  22463. }
  22464. } else {
  22465. data.shapes.push( shapes.uuid );
  22466. }
  22467. return data;
  22468. }
  22469. class SphereGeometry extends BufferGeometry {
  22470. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  22471. super();
  22472. this.type = 'SphereGeometry';
  22473. this.parameters = {
  22474. radius: radius,
  22475. widthSegments: widthSegments,
  22476. heightSegments: heightSegments,
  22477. phiStart: phiStart,
  22478. phiLength: phiLength,
  22479. thetaStart: thetaStart,
  22480. thetaLength: thetaLength
  22481. };
  22482. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  22483. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  22484. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22485. let index = 0;
  22486. const grid = [];
  22487. const vertex = new Vector3();
  22488. const normal = new Vector3();
  22489. // buffers
  22490. const indices = [];
  22491. const vertices = [];
  22492. const normals = [];
  22493. const uvs = [];
  22494. // generate vertices, normals and uvs
  22495. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22496. const verticesRow = [];
  22497. const v = iy / heightSegments;
  22498. // special case for the poles
  22499. let uOffset = 0;
  22500. if ( iy === 0 && thetaStart === 0 ) {
  22501. uOffset = 0.5 / widthSegments;
  22502. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22503. uOffset = - 0.5 / widthSegments;
  22504. }
  22505. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22506. const u = ix / widthSegments;
  22507. // vertex
  22508. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22509. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22510. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22511. vertices.push( vertex.x, vertex.y, vertex.z );
  22512. // normal
  22513. normal.copy( vertex ).normalize();
  22514. normals.push( normal.x, normal.y, normal.z );
  22515. // uv
  22516. uvs.push( u + uOffset, 1 - v );
  22517. verticesRow.push( index ++ );
  22518. }
  22519. grid.push( verticesRow );
  22520. }
  22521. // indices
  22522. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22523. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22524. const a = grid[ iy ][ ix + 1 ];
  22525. const b = grid[ iy ][ ix ];
  22526. const c = grid[ iy + 1 ][ ix ];
  22527. const d = grid[ iy + 1 ][ ix + 1 ];
  22528. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22529. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  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. }
  22538. copy( source ) {
  22539. super.copy( source );
  22540. this.parameters = Object.assign( {}, source.parameters );
  22541. return this;
  22542. }
  22543. static fromJSON( data ) {
  22544. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22545. }
  22546. }
  22547. class TetrahedronGeometry extends PolyhedronGeometry {
  22548. constructor( radius = 1, detail = 0 ) {
  22549. const vertices = [
  22550. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22551. ];
  22552. const indices = [
  22553. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22554. ];
  22555. super( vertices, indices, radius, detail );
  22556. this.type = 'TetrahedronGeometry';
  22557. this.parameters = {
  22558. radius: radius,
  22559. detail: detail
  22560. };
  22561. }
  22562. static fromJSON( data ) {
  22563. return new TetrahedronGeometry( data.radius, data.detail );
  22564. }
  22565. }
  22566. class TorusGeometry extends BufferGeometry {
  22567. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22568. super();
  22569. this.type = 'TorusGeometry';
  22570. this.parameters = {
  22571. radius: radius,
  22572. tube: tube,
  22573. radialSegments: radialSegments,
  22574. tubularSegments: tubularSegments,
  22575. arc: arc
  22576. };
  22577. radialSegments = Math.floor( radialSegments );
  22578. tubularSegments = Math.floor( tubularSegments );
  22579. // buffers
  22580. const indices = [];
  22581. const vertices = [];
  22582. const normals = [];
  22583. const uvs = [];
  22584. // helper variables
  22585. const center = new Vector3();
  22586. const vertex = new Vector3();
  22587. const normal = new Vector3();
  22588. // generate vertices, normals and uvs
  22589. for ( let j = 0; j <= radialSegments; j ++ ) {
  22590. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22591. const u = i / tubularSegments * arc;
  22592. const v = j / radialSegments * Math.PI * 2;
  22593. // vertex
  22594. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22595. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22596. vertex.z = tube * Math.sin( v );
  22597. vertices.push( vertex.x, vertex.y, vertex.z );
  22598. // normal
  22599. center.x = radius * Math.cos( u );
  22600. center.y = radius * Math.sin( u );
  22601. normal.subVectors( vertex, center ).normalize();
  22602. normals.push( normal.x, normal.y, normal.z );
  22603. // uv
  22604. uvs.push( i / tubularSegments );
  22605. uvs.push( j / radialSegments );
  22606. }
  22607. }
  22608. // generate indices
  22609. for ( let j = 1; j <= radialSegments; j ++ ) {
  22610. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22611. // indices
  22612. const a = ( tubularSegments + 1 ) * j + i - 1;
  22613. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22614. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22615. const d = ( tubularSegments + 1 ) * j + i;
  22616. // faces
  22617. indices.push( a, b, d );
  22618. indices.push( b, c, d );
  22619. }
  22620. }
  22621. // build geometry
  22622. this.setIndex( indices );
  22623. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22624. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22625. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22626. }
  22627. copy( source ) {
  22628. super.copy( source );
  22629. this.parameters = Object.assign( {}, source.parameters );
  22630. return this;
  22631. }
  22632. static fromJSON( data ) {
  22633. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22634. }
  22635. }
  22636. class TorusKnotGeometry extends BufferGeometry {
  22637. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22638. super();
  22639. this.type = 'TorusKnotGeometry';
  22640. this.parameters = {
  22641. radius: radius,
  22642. tube: tube,
  22643. tubularSegments: tubularSegments,
  22644. radialSegments: radialSegments,
  22645. p: p,
  22646. q: q
  22647. };
  22648. tubularSegments = Math.floor( tubularSegments );
  22649. radialSegments = Math.floor( radialSegments );
  22650. // buffers
  22651. const indices = [];
  22652. const vertices = [];
  22653. const normals = [];
  22654. const uvs = [];
  22655. // helper variables
  22656. const vertex = new Vector3();
  22657. const normal = new Vector3();
  22658. const P1 = new Vector3();
  22659. const P2 = new Vector3();
  22660. const B = new Vector3();
  22661. const T = new Vector3();
  22662. const N = new Vector3();
  22663. // generate vertices, normals and uvs
  22664. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22665. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22666. const u = i / tubularSegments * p * Math.PI * 2;
  22667. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22668. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22669. calculatePositionOnCurve( u, p, q, radius, P1 );
  22670. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22671. // calculate orthonormal basis
  22672. T.subVectors( P2, P1 );
  22673. N.addVectors( P2, P1 );
  22674. B.crossVectors( T, N );
  22675. N.crossVectors( B, T );
  22676. // normalize B, N. T can be ignored, we don't use it
  22677. B.normalize();
  22678. N.normalize();
  22679. for ( let j = 0; j <= radialSegments; ++ j ) {
  22680. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22681. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22682. const v = j / radialSegments * Math.PI * 2;
  22683. const cx = - tube * Math.cos( v );
  22684. const cy = tube * Math.sin( v );
  22685. // now calculate the final vertex position.
  22686. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22687. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22688. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22689. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22690. vertices.push( vertex.x, vertex.y, vertex.z );
  22691. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22692. normal.subVectors( vertex, P1 ).normalize();
  22693. normals.push( normal.x, normal.y, normal.z );
  22694. // uv
  22695. uvs.push( i / tubularSegments );
  22696. uvs.push( j / radialSegments );
  22697. }
  22698. }
  22699. // generate indices
  22700. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22701. for ( let i = 1; i <= radialSegments; i ++ ) {
  22702. // indices
  22703. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22704. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22705. const c = ( radialSegments + 1 ) * j + i;
  22706. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22707. // faces
  22708. indices.push( a, b, d );
  22709. indices.push( b, c, d );
  22710. }
  22711. }
  22712. // build geometry
  22713. this.setIndex( indices );
  22714. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22715. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22716. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22717. // this function calculates the current position on the torus curve
  22718. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22719. const cu = Math.cos( u );
  22720. const su = Math.sin( u );
  22721. const quOverP = q / p * u;
  22722. const cs = Math.cos( quOverP );
  22723. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22724. position.y = radius * ( 2 + cs ) * su * 0.5;
  22725. position.z = radius * Math.sin( quOverP ) * 0.5;
  22726. }
  22727. }
  22728. copy( source ) {
  22729. super.copy( source );
  22730. this.parameters = Object.assign( {}, source.parameters );
  22731. return this;
  22732. }
  22733. static fromJSON( data ) {
  22734. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22735. }
  22736. }
  22737. class TubeGeometry extends BufferGeometry {
  22738. 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 ) {
  22739. super();
  22740. this.type = 'TubeGeometry';
  22741. this.parameters = {
  22742. path: path,
  22743. tubularSegments: tubularSegments,
  22744. radius: radius,
  22745. radialSegments: radialSegments,
  22746. closed: closed
  22747. };
  22748. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22749. // expose internals
  22750. this.tangents = frames.tangents;
  22751. this.normals = frames.normals;
  22752. this.binormals = frames.binormals;
  22753. // helper variables
  22754. const vertex = new Vector3();
  22755. const normal = new Vector3();
  22756. const uv = new Vector2();
  22757. let P = new Vector3();
  22758. // buffer
  22759. const vertices = [];
  22760. const normals = [];
  22761. const uvs = [];
  22762. const indices = [];
  22763. // create buffer data
  22764. generateBufferData();
  22765. // build geometry
  22766. this.setIndex( indices );
  22767. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22768. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22769. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22770. // functions
  22771. function generateBufferData() {
  22772. for ( let i = 0; i < tubularSegments; i ++ ) {
  22773. generateSegment( i );
  22774. }
  22775. // if the geometry is not closed, generate the last row of vertices and normals
  22776. // at the regular position on the given path
  22777. //
  22778. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22779. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22780. // uvs are generated in a separate function.
  22781. // this makes it easy compute correct values for closed geometries
  22782. generateUVs();
  22783. // finally create faces
  22784. generateIndices();
  22785. }
  22786. function generateSegment( i ) {
  22787. // we use getPointAt to sample evenly distributed points from the given path
  22788. P = path.getPointAt( i / tubularSegments, P );
  22789. // retrieve corresponding normal and binormal
  22790. const N = frames.normals[ i ];
  22791. const B = frames.binormals[ i ];
  22792. // generate normals and vertices for the current segment
  22793. for ( let j = 0; j <= radialSegments; j ++ ) {
  22794. const v = j / radialSegments * Math.PI * 2;
  22795. const sin = Math.sin( v );
  22796. const cos = - Math.cos( v );
  22797. // normal
  22798. normal.x = ( cos * N.x + sin * B.x );
  22799. normal.y = ( cos * N.y + sin * B.y );
  22800. normal.z = ( cos * N.z + sin * B.z );
  22801. normal.normalize();
  22802. normals.push( normal.x, normal.y, normal.z );
  22803. // vertex
  22804. vertex.x = P.x + radius * normal.x;
  22805. vertex.y = P.y + radius * normal.y;
  22806. vertex.z = P.z + radius * normal.z;
  22807. vertices.push( vertex.x, vertex.y, vertex.z );
  22808. }
  22809. }
  22810. function generateIndices() {
  22811. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22812. for ( let i = 1; i <= radialSegments; i ++ ) {
  22813. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22814. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22815. const c = ( radialSegments + 1 ) * j + i;
  22816. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22817. // faces
  22818. indices.push( a, b, d );
  22819. indices.push( b, c, d );
  22820. }
  22821. }
  22822. }
  22823. function generateUVs() {
  22824. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22825. for ( let j = 0; j <= radialSegments; j ++ ) {
  22826. uv.x = i / tubularSegments;
  22827. uv.y = j / radialSegments;
  22828. uvs.push( uv.x, uv.y );
  22829. }
  22830. }
  22831. }
  22832. }
  22833. copy( source ) {
  22834. super.copy( source );
  22835. this.parameters = Object.assign( {}, source.parameters );
  22836. return this;
  22837. }
  22838. toJSON() {
  22839. const data = super.toJSON();
  22840. data.path = this.parameters.path.toJSON();
  22841. return data;
  22842. }
  22843. static fromJSON( data ) {
  22844. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22845. // User defined curves or instances of CurvePath will not be deserialized.
  22846. return new TubeGeometry(
  22847. new Curves[ data.path.type ]().fromJSON( data.path ),
  22848. data.tubularSegments,
  22849. data.radius,
  22850. data.radialSegments,
  22851. data.closed
  22852. );
  22853. }
  22854. }
  22855. class WireframeGeometry extends BufferGeometry {
  22856. constructor( geometry = null ) {
  22857. super();
  22858. this.type = 'WireframeGeometry';
  22859. this.parameters = {
  22860. geometry: geometry
  22861. };
  22862. if ( geometry !== null ) {
  22863. // buffer
  22864. const vertices = [];
  22865. const edges = new Set();
  22866. // helper variables
  22867. const start = new Vector3();
  22868. const end = new Vector3();
  22869. if ( geometry.index !== null ) {
  22870. // indexed BufferGeometry
  22871. const position = geometry.attributes.position;
  22872. const indices = geometry.index;
  22873. let groups = geometry.groups;
  22874. if ( groups.length === 0 ) {
  22875. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22876. }
  22877. // create a data structure that contains all edges without duplicates
  22878. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22879. const group = groups[ o ];
  22880. const groupStart = group.start;
  22881. const groupCount = group.count;
  22882. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22883. for ( let j = 0; j < 3; j ++ ) {
  22884. const index1 = indices.getX( i + j );
  22885. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22886. start.fromBufferAttribute( position, index1 );
  22887. end.fromBufferAttribute( position, index2 );
  22888. if ( isUniqueEdge( start, end, edges ) === true ) {
  22889. vertices.push( start.x, start.y, start.z );
  22890. vertices.push( end.x, end.y, end.z );
  22891. }
  22892. }
  22893. }
  22894. }
  22895. } else {
  22896. // non-indexed BufferGeometry
  22897. const position = geometry.attributes.position;
  22898. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22899. for ( let j = 0; j < 3; j ++ ) {
  22900. // three edges per triangle, an edge is represented as (index1, index2)
  22901. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22902. const index1 = 3 * i + j;
  22903. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22904. start.fromBufferAttribute( position, index1 );
  22905. end.fromBufferAttribute( position, index2 );
  22906. if ( isUniqueEdge( start, end, edges ) === true ) {
  22907. vertices.push( start.x, start.y, start.z );
  22908. vertices.push( end.x, end.y, end.z );
  22909. }
  22910. }
  22911. }
  22912. }
  22913. // build geometry
  22914. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22915. }
  22916. }
  22917. copy( source ) {
  22918. super.copy( source );
  22919. this.parameters = Object.assign( {}, source.parameters );
  22920. return this;
  22921. }
  22922. }
  22923. function isUniqueEdge( start, end, edges ) {
  22924. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22925. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22926. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22927. return false;
  22928. } else {
  22929. edges.add( hash1 );
  22930. edges.add( hash2 );
  22931. return true;
  22932. }
  22933. }
  22934. var Geometries = /*#__PURE__*/Object.freeze({
  22935. __proto__: null,
  22936. BoxGeometry: BoxGeometry,
  22937. CapsuleGeometry: CapsuleGeometry,
  22938. CircleGeometry: CircleGeometry,
  22939. ConeGeometry: ConeGeometry,
  22940. CylinderGeometry: CylinderGeometry,
  22941. DodecahedronGeometry: DodecahedronGeometry,
  22942. EdgesGeometry: EdgesGeometry,
  22943. ExtrudeGeometry: ExtrudeGeometry,
  22944. IcosahedronGeometry: IcosahedronGeometry,
  22945. LatheGeometry: LatheGeometry,
  22946. OctahedronGeometry: OctahedronGeometry,
  22947. PlaneGeometry: PlaneGeometry,
  22948. PolyhedronGeometry: PolyhedronGeometry,
  22949. RingGeometry: RingGeometry,
  22950. ShapeGeometry: ShapeGeometry,
  22951. SphereGeometry: SphereGeometry,
  22952. TetrahedronGeometry: TetrahedronGeometry,
  22953. TorusGeometry: TorusGeometry,
  22954. TorusKnotGeometry: TorusKnotGeometry,
  22955. TubeGeometry: TubeGeometry,
  22956. WireframeGeometry: WireframeGeometry
  22957. });
  22958. class ShadowMaterial extends Material {
  22959. constructor( parameters ) {
  22960. super();
  22961. this.isShadowMaterial = true;
  22962. this.type = 'ShadowMaterial';
  22963. this.color = new Color( 0x000000 );
  22964. this.transparent = true;
  22965. this.fog = true;
  22966. this.setValues( parameters );
  22967. }
  22968. copy( source ) {
  22969. super.copy( source );
  22970. this.color.copy( source.color );
  22971. this.fog = source.fog;
  22972. return this;
  22973. }
  22974. }
  22975. class RawShaderMaterial extends ShaderMaterial {
  22976. constructor( parameters ) {
  22977. super( parameters );
  22978. this.isRawShaderMaterial = true;
  22979. this.type = 'RawShaderMaterial';
  22980. }
  22981. }
  22982. class MeshStandardMaterial extends Material {
  22983. constructor( parameters ) {
  22984. super();
  22985. this.isMeshStandardMaterial = true;
  22986. this.defines = { 'STANDARD': '' };
  22987. this.type = 'MeshStandardMaterial';
  22988. this.color = new Color( 0xffffff ); // diffuse
  22989. this.roughness = 1.0;
  22990. this.metalness = 0.0;
  22991. this.map = null;
  22992. this.lightMap = null;
  22993. this.lightMapIntensity = 1.0;
  22994. this.aoMap = null;
  22995. this.aoMapIntensity = 1.0;
  22996. this.emissive = new Color( 0x000000 );
  22997. this.emissiveIntensity = 1.0;
  22998. this.emissiveMap = null;
  22999. this.bumpMap = null;
  23000. this.bumpScale = 1;
  23001. this.normalMap = null;
  23002. this.normalMapType = TangentSpaceNormalMap;
  23003. this.normalScale = new Vector2( 1, 1 );
  23004. this.displacementMap = null;
  23005. this.displacementScale = 1;
  23006. this.displacementBias = 0;
  23007. this.roughnessMap = null;
  23008. this.metalnessMap = null;
  23009. this.alphaMap = null;
  23010. this.envMap = null;
  23011. this.envMapIntensity = 1.0;
  23012. this.wireframe = false;
  23013. this.wireframeLinewidth = 1;
  23014. this.wireframeLinecap = 'round';
  23015. this.wireframeLinejoin = 'round';
  23016. this.flatShading = false;
  23017. this.fog = true;
  23018. this.setValues( parameters );
  23019. }
  23020. copy( source ) {
  23021. super.copy( source );
  23022. this.defines = { 'STANDARD': '' };
  23023. this.color.copy( source.color );
  23024. this.roughness = source.roughness;
  23025. this.metalness = source.metalness;
  23026. this.map = source.map;
  23027. this.lightMap = source.lightMap;
  23028. this.lightMapIntensity = source.lightMapIntensity;
  23029. this.aoMap = source.aoMap;
  23030. this.aoMapIntensity = source.aoMapIntensity;
  23031. this.emissive.copy( source.emissive );
  23032. this.emissiveMap = source.emissiveMap;
  23033. this.emissiveIntensity = source.emissiveIntensity;
  23034. this.bumpMap = source.bumpMap;
  23035. this.bumpScale = source.bumpScale;
  23036. this.normalMap = source.normalMap;
  23037. this.normalMapType = source.normalMapType;
  23038. this.normalScale.copy( source.normalScale );
  23039. this.displacementMap = source.displacementMap;
  23040. this.displacementScale = source.displacementScale;
  23041. this.displacementBias = source.displacementBias;
  23042. this.roughnessMap = source.roughnessMap;
  23043. this.metalnessMap = source.metalnessMap;
  23044. this.alphaMap = source.alphaMap;
  23045. this.envMap = source.envMap;
  23046. this.envMapIntensity = source.envMapIntensity;
  23047. this.wireframe = source.wireframe;
  23048. this.wireframeLinewidth = source.wireframeLinewidth;
  23049. this.wireframeLinecap = source.wireframeLinecap;
  23050. this.wireframeLinejoin = source.wireframeLinejoin;
  23051. this.flatShading = source.flatShading;
  23052. this.fog = source.fog;
  23053. return this;
  23054. }
  23055. }
  23056. class MeshPhysicalMaterial extends MeshStandardMaterial {
  23057. constructor( parameters ) {
  23058. super();
  23059. this.isMeshPhysicalMaterial = true;
  23060. this.defines = {
  23061. 'STANDARD': '',
  23062. 'PHYSICAL': ''
  23063. };
  23064. this.type = 'MeshPhysicalMaterial';
  23065. this.anisotropyRotation = 0;
  23066. this.anisotropyMap = null;
  23067. this.clearcoatMap = null;
  23068. this.clearcoatRoughness = 0.0;
  23069. this.clearcoatRoughnessMap = null;
  23070. this.clearcoatNormalScale = new Vector2( 1, 1 );
  23071. this.clearcoatNormalMap = null;
  23072. this.ior = 1.5;
  23073. Object.defineProperty( this, 'reflectivity', {
  23074. get: function () {
  23075. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  23076. },
  23077. set: function ( reflectivity ) {
  23078. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  23079. }
  23080. } );
  23081. this.iridescenceMap = null;
  23082. this.iridescenceIOR = 1.3;
  23083. this.iridescenceThicknessRange = [ 100, 400 ];
  23084. this.iridescenceThicknessMap = null;
  23085. this.sheenColor = new Color( 0x000000 );
  23086. this.sheenColorMap = null;
  23087. this.sheenRoughness = 1.0;
  23088. this.sheenRoughnessMap = null;
  23089. this.transmissionMap = null;
  23090. this.thickness = 0;
  23091. this.thicknessMap = null;
  23092. this.attenuationDistance = Infinity;
  23093. this.attenuationColor = new Color( 1, 1, 1 );
  23094. this.specularIntensity = 1.0;
  23095. this.specularIntensityMap = null;
  23096. this.specularColor = new Color( 1, 1, 1 );
  23097. this.specularColorMap = null;
  23098. this._anisotropy = 0;
  23099. this._clearcoat = 0;
  23100. this._iridescence = 0;
  23101. this._sheen = 0.0;
  23102. this._transmission = 0;
  23103. this.setValues( parameters );
  23104. }
  23105. get anisotropy() {
  23106. return this._anisotropy;
  23107. }
  23108. set anisotropy( value ) {
  23109. if ( this._anisotropy > 0 !== value > 0 ) {
  23110. this.version ++;
  23111. }
  23112. this._anisotropy = value;
  23113. }
  23114. get clearcoat() {
  23115. return this._clearcoat;
  23116. }
  23117. set clearcoat( value ) {
  23118. if ( this._clearcoat > 0 !== value > 0 ) {
  23119. this.version ++;
  23120. }
  23121. this._clearcoat = value;
  23122. }
  23123. get iridescence() {
  23124. return this._iridescence;
  23125. }
  23126. set iridescence( value ) {
  23127. if ( this._iridescence > 0 !== value > 0 ) {
  23128. this.version ++;
  23129. }
  23130. this._iridescence = value;
  23131. }
  23132. get sheen() {
  23133. return this._sheen;
  23134. }
  23135. set sheen( value ) {
  23136. if ( this._sheen > 0 !== value > 0 ) {
  23137. this.version ++;
  23138. }
  23139. this._sheen = value;
  23140. }
  23141. get transmission() {
  23142. return this._transmission;
  23143. }
  23144. set transmission( value ) {
  23145. if ( this._transmission > 0 !== value > 0 ) {
  23146. this.version ++;
  23147. }
  23148. this._transmission = value;
  23149. }
  23150. copy( source ) {
  23151. super.copy( source );
  23152. this.defines = {
  23153. 'STANDARD': '',
  23154. 'PHYSICAL': ''
  23155. };
  23156. this.anisotropy = source.anisotropy;
  23157. this.anisotropyRotation = source.anisotropyRotation;
  23158. this.anisotropyMap = source.anisotropyMap;
  23159. this.clearcoat = source.clearcoat;
  23160. this.clearcoatMap = source.clearcoatMap;
  23161. this.clearcoatRoughness = source.clearcoatRoughness;
  23162. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  23163. this.clearcoatNormalMap = source.clearcoatNormalMap;
  23164. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  23165. this.ior = source.ior;
  23166. this.iridescence = source.iridescence;
  23167. this.iridescenceMap = source.iridescenceMap;
  23168. this.iridescenceIOR = source.iridescenceIOR;
  23169. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  23170. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  23171. this.sheen = source.sheen;
  23172. this.sheenColor.copy( source.sheenColor );
  23173. this.sheenColorMap = source.sheenColorMap;
  23174. this.sheenRoughness = source.sheenRoughness;
  23175. this.sheenRoughnessMap = source.sheenRoughnessMap;
  23176. this.transmission = source.transmission;
  23177. this.transmissionMap = source.transmissionMap;
  23178. this.thickness = source.thickness;
  23179. this.thicknessMap = source.thicknessMap;
  23180. this.attenuationDistance = source.attenuationDistance;
  23181. this.attenuationColor.copy( source.attenuationColor );
  23182. this.specularIntensity = source.specularIntensity;
  23183. this.specularIntensityMap = source.specularIntensityMap;
  23184. this.specularColor.copy( source.specularColor );
  23185. this.specularColorMap = source.specularColorMap;
  23186. return this;
  23187. }
  23188. }
  23189. class MeshPhongMaterial extends Material {
  23190. constructor( parameters ) {
  23191. super();
  23192. this.isMeshPhongMaterial = true;
  23193. this.type = 'MeshPhongMaterial';
  23194. this.color = new Color( 0xffffff ); // diffuse
  23195. this.specular = new Color( 0x111111 );
  23196. this.shininess = 30;
  23197. this.map = null;
  23198. this.lightMap = null;
  23199. this.lightMapIntensity = 1.0;
  23200. this.aoMap = null;
  23201. this.aoMapIntensity = 1.0;
  23202. this.emissive = new Color( 0x000000 );
  23203. this.emissiveIntensity = 1.0;
  23204. this.emissiveMap = null;
  23205. this.bumpMap = null;
  23206. this.bumpScale = 1;
  23207. this.normalMap = null;
  23208. this.normalMapType = TangentSpaceNormalMap;
  23209. this.normalScale = new Vector2( 1, 1 );
  23210. this.displacementMap = null;
  23211. this.displacementScale = 1;
  23212. this.displacementBias = 0;
  23213. this.specularMap = null;
  23214. this.alphaMap = null;
  23215. this.envMap = null;
  23216. this.combine = MultiplyOperation;
  23217. this.reflectivity = 1;
  23218. this.refractionRatio = 0.98;
  23219. this.wireframe = false;
  23220. this.wireframeLinewidth = 1;
  23221. this.wireframeLinecap = 'round';
  23222. this.wireframeLinejoin = 'round';
  23223. this.flatShading = false;
  23224. this.fog = true;
  23225. this.setValues( parameters );
  23226. }
  23227. copy( source ) {
  23228. super.copy( source );
  23229. this.color.copy( source.color );
  23230. this.specular.copy( source.specular );
  23231. this.shininess = source.shininess;
  23232. this.map = source.map;
  23233. this.lightMap = source.lightMap;
  23234. this.lightMapIntensity = source.lightMapIntensity;
  23235. this.aoMap = source.aoMap;
  23236. this.aoMapIntensity = source.aoMapIntensity;
  23237. this.emissive.copy( source.emissive );
  23238. this.emissiveMap = source.emissiveMap;
  23239. this.emissiveIntensity = source.emissiveIntensity;
  23240. this.bumpMap = source.bumpMap;
  23241. this.bumpScale = source.bumpScale;
  23242. this.normalMap = source.normalMap;
  23243. this.normalMapType = source.normalMapType;
  23244. this.normalScale.copy( source.normalScale );
  23245. this.displacementMap = source.displacementMap;
  23246. this.displacementScale = source.displacementScale;
  23247. this.displacementBias = source.displacementBias;
  23248. this.specularMap = source.specularMap;
  23249. this.alphaMap = source.alphaMap;
  23250. this.envMap = source.envMap;
  23251. this.combine = source.combine;
  23252. this.reflectivity = source.reflectivity;
  23253. this.refractionRatio = source.refractionRatio;
  23254. this.wireframe = source.wireframe;
  23255. this.wireframeLinewidth = source.wireframeLinewidth;
  23256. this.wireframeLinecap = source.wireframeLinecap;
  23257. this.wireframeLinejoin = source.wireframeLinejoin;
  23258. this.flatShading = source.flatShading;
  23259. this.fog = source.fog;
  23260. return this;
  23261. }
  23262. }
  23263. class MeshToonMaterial extends Material {
  23264. constructor( parameters ) {
  23265. super();
  23266. this.isMeshToonMaterial = true;
  23267. this.defines = { 'TOON': '' };
  23268. this.type = 'MeshToonMaterial';
  23269. this.color = new Color( 0xffffff );
  23270. this.map = null;
  23271. this.gradientMap = null;
  23272. this.lightMap = null;
  23273. this.lightMapIntensity = 1.0;
  23274. this.aoMap = null;
  23275. this.aoMapIntensity = 1.0;
  23276. this.emissive = new Color( 0x000000 );
  23277. this.emissiveIntensity = 1.0;
  23278. this.emissiveMap = null;
  23279. this.bumpMap = null;
  23280. this.bumpScale = 1;
  23281. this.normalMap = null;
  23282. this.normalMapType = TangentSpaceNormalMap;
  23283. this.normalScale = new Vector2( 1, 1 );
  23284. this.displacementMap = null;
  23285. this.displacementScale = 1;
  23286. this.displacementBias = 0;
  23287. this.alphaMap = null;
  23288. this.wireframe = false;
  23289. this.wireframeLinewidth = 1;
  23290. this.wireframeLinecap = 'round';
  23291. this.wireframeLinejoin = 'round';
  23292. this.fog = true;
  23293. this.setValues( parameters );
  23294. }
  23295. copy( source ) {
  23296. super.copy( source );
  23297. this.color.copy( source.color );
  23298. this.map = source.map;
  23299. this.gradientMap = source.gradientMap;
  23300. this.lightMap = source.lightMap;
  23301. this.lightMapIntensity = source.lightMapIntensity;
  23302. this.aoMap = source.aoMap;
  23303. this.aoMapIntensity = source.aoMapIntensity;
  23304. this.emissive.copy( source.emissive );
  23305. this.emissiveMap = source.emissiveMap;
  23306. this.emissiveIntensity = source.emissiveIntensity;
  23307. this.bumpMap = source.bumpMap;
  23308. this.bumpScale = source.bumpScale;
  23309. this.normalMap = source.normalMap;
  23310. this.normalMapType = source.normalMapType;
  23311. this.normalScale.copy( source.normalScale );
  23312. this.displacementMap = source.displacementMap;
  23313. this.displacementScale = source.displacementScale;
  23314. this.displacementBias = source.displacementBias;
  23315. this.alphaMap = source.alphaMap;
  23316. this.wireframe = source.wireframe;
  23317. this.wireframeLinewidth = source.wireframeLinewidth;
  23318. this.wireframeLinecap = source.wireframeLinecap;
  23319. this.wireframeLinejoin = source.wireframeLinejoin;
  23320. this.fog = source.fog;
  23321. return this;
  23322. }
  23323. }
  23324. class MeshNormalMaterial extends Material {
  23325. constructor( parameters ) {
  23326. super();
  23327. this.isMeshNormalMaterial = true;
  23328. this.type = 'MeshNormalMaterial';
  23329. this.bumpMap = null;
  23330. this.bumpScale = 1;
  23331. this.normalMap = null;
  23332. this.normalMapType = TangentSpaceNormalMap;
  23333. this.normalScale = new Vector2( 1, 1 );
  23334. this.displacementMap = null;
  23335. this.displacementScale = 1;
  23336. this.displacementBias = 0;
  23337. this.wireframe = false;
  23338. this.wireframeLinewidth = 1;
  23339. this.flatShading = false;
  23340. this.setValues( parameters );
  23341. }
  23342. copy( source ) {
  23343. super.copy( source );
  23344. this.bumpMap = source.bumpMap;
  23345. this.bumpScale = source.bumpScale;
  23346. this.normalMap = source.normalMap;
  23347. this.normalMapType = source.normalMapType;
  23348. this.normalScale.copy( source.normalScale );
  23349. this.displacementMap = source.displacementMap;
  23350. this.displacementScale = source.displacementScale;
  23351. this.displacementBias = source.displacementBias;
  23352. this.wireframe = source.wireframe;
  23353. this.wireframeLinewidth = source.wireframeLinewidth;
  23354. this.flatShading = source.flatShading;
  23355. return this;
  23356. }
  23357. }
  23358. class MeshLambertMaterial extends Material {
  23359. constructor( parameters ) {
  23360. super();
  23361. this.isMeshLambertMaterial = true;
  23362. this.type = 'MeshLambertMaterial';
  23363. this.color = new Color( 0xffffff ); // diffuse
  23364. this.map = null;
  23365. this.lightMap = null;
  23366. this.lightMapIntensity = 1.0;
  23367. this.aoMap = null;
  23368. this.aoMapIntensity = 1.0;
  23369. this.emissive = new Color( 0x000000 );
  23370. this.emissiveIntensity = 1.0;
  23371. this.emissiveMap = null;
  23372. this.bumpMap = null;
  23373. this.bumpScale = 1;
  23374. this.normalMap = null;
  23375. this.normalMapType = TangentSpaceNormalMap;
  23376. this.normalScale = new Vector2( 1, 1 );
  23377. this.displacementMap = null;
  23378. this.displacementScale = 1;
  23379. this.displacementBias = 0;
  23380. this.specularMap = null;
  23381. this.alphaMap = null;
  23382. this.envMap = null;
  23383. this.combine = MultiplyOperation;
  23384. this.reflectivity = 1;
  23385. this.refractionRatio = 0.98;
  23386. this.wireframe = false;
  23387. this.wireframeLinewidth = 1;
  23388. this.wireframeLinecap = 'round';
  23389. this.wireframeLinejoin = 'round';
  23390. this.flatShading = false;
  23391. this.fog = true;
  23392. this.setValues( parameters );
  23393. }
  23394. copy( source ) {
  23395. super.copy( source );
  23396. this.color.copy( source.color );
  23397. this.map = source.map;
  23398. this.lightMap = source.lightMap;
  23399. this.lightMapIntensity = source.lightMapIntensity;
  23400. this.aoMap = source.aoMap;
  23401. this.aoMapIntensity = source.aoMapIntensity;
  23402. this.emissive.copy( source.emissive );
  23403. this.emissiveMap = source.emissiveMap;
  23404. this.emissiveIntensity = source.emissiveIntensity;
  23405. this.bumpMap = source.bumpMap;
  23406. this.bumpScale = source.bumpScale;
  23407. this.normalMap = source.normalMap;
  23408. this.normalMapType = source.normalMapType;
  23409. this.normalScale.copy( source.normalScale );
  23410. this.displacementMap = source.displacementMap;
  23411. this.displacementScale = source.displacementScale;
  23412. this.displacementBias = source.displacementBias;
  23413. this.specularMap = source.specularMap;
  23414. this.alphaMap = source.alphaMap;
  23415. this.envMap = source.envMap;
  23416. this.combine = source.combine;
  23417. this.reflectivity = source.reflectivity;
  23418. this.refractionRatio = source.refractionRatio;
  23419. this.wireframe = source.wireframe;
  23420. this.wireframeLinewidth = source.wireframeLinewidth;
  23421. this.wireframeLinecap = source.wireframeLinecap;
  23422. this.wireframeLinejoin = source.wireframeLinejoin;
  23423. this.flatShading = source.flatShading;
  23424. this.fog = source.fog;
  23425. return this;
  23426. }
  23427. }
  23428. class MeshMatcapMaterial extends Material {
  23429. constructor( parameters ) {
  23430. super();
  23431. this.isMeshMatcapMaterial = true;
  23432. this.defines = { 'MATCAP': '' };
  23433. this.type = 'MeshMatcapMaterial';
  23434. this.color = new Color( 0xffffff ); // diffuse
  23435. this.matcap = null;
  23436. this.map = null;
  23437. this.bumpMap = null;
  23438. this.bumpScale = 1;
  23439. this.normalMap = null;
  23440. this.normalMapType = TangentSpaceNormalMap;
  23441. this.normalScale = new Vector2( 1, 1 );
  23442. this.displacementMap = null;
  23443. this.displacementScale = 1;
  23444. this.displacementBias = 0;
  23445. this.alphaMap = null;
  23446. this.flatShading = false;
  23447. this.fog = true;
  23448. this.setValues( parameters );
  23449. }
  23450. copy( source ) {
  23451. super.copy( source );
  23452. this.defines = { 'MATCAP': '' };
  23453. this.color.copy( source.color );
  23454. this.matcap = source.matcap;
  23455. this.map = source.map;
  23456. this.bumpMap = source.bumpMap;
  23457. this.bumpScale = source.bumpScale;
  23458. this.normalMap = source.normalMap;
  23459. this.normalMapType = source.normalMapType;
  23460. this.normalScale.copy( source.normalScale );
  23461. this.displacementMap = source.displacementMap;
  23462. this.displacementScale = source.displacementScale;
  23463. this.displacementBias = source.displacementBias;
  23464. this.alphaMap = source.alphaMap;
  23465. this.flatShading = source.flatShading;
  23466. this.fog = source.fog;
  23467. return this;
  23468. }
  23469. }
  23470. class LineDashedMaterial extends LineBasicMaterial {
  23471. constructor( parameters ) {
  23472. super();
  23473. this.isLineDashedMaterial = true;
  23474. this.type = 'LineDashedMaterial';
  23475. this.scale = 1;
  23476. this.dashSize = 3;
  23477. this.gapSize = 1;
  23478. this.setValues( parameters );
  23479. }
  23480. copy( source ) {
  23481. super.copy( source );
  23482. this.scale = source.scale;
  23483. this.dashSize = source.dashSize;
  23484. this.gapSize = source.gapSize;
  23485. return this;
  23486. }
  23487. }
  23488. // same as Array.prototype.slice, but also works on typed arrays
  23489. function arraySlice( array, from, to ) {
  23490. if ( isTypedArray( array ) ) {
  23491. // in ios9 array.subarray(from, undefined) will return empty array
  23492. // but array.subarray(from) or array.subarray(from, len) is correct
  23493. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  23494. }
  23495. return array.slice( from, to );
  23496. }
  23497. // converts an array to a specific type
  23498. function convertArray( array, type, forceClone ) {
  23499. if ( ! array || // let 'undefined' and 'null' pass
  23500. ! forceClone && array.constructor === type ) return array;
  23501. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23502. return new type( array ); // create typed array
  23503. }
  23504. return Array.prototype.slice.call( array ); // create Array
  23505. }
  23506. function isTypedArray( object ) {
  23507. return ArrayBuffer.isView( object ) &&
  23508. ! ( object instanceof DataView );
  23509. }
  23510. // returns an array by which times and values can be sorted
  23511. function getKeyframeOrder( times ) {
  23512. function compareTime( i, j ) {
  23513. return times[ i ] - times[ j ];
  23514. }
  23515. const n = times.length;
  23516. const result = new Array( n );
  23517. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23518. result.sort( compareTime );
  23519. return result;
  23520. }
  23521. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23522. function sortedArray( values, stride, order ) {
  23523. const nValues = values.length;
  23524. const result = new values.constructor( nValues );
  23525. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23526. const srcOffset = order[ i ] * stride;
  23527. for ( let j = 0; j !== stride; ++ j ) {
  23528. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23529. }
  23530. }
  23531. return result;
  23532. }
  23533. // function for parsing AOS keyframe formats
  23534. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23535. let i = 1, key = jsonKeys[ 0 ];
  23536. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23537. key = jsonKeys[ i ++ ];
  23538. }
  23539. if ( key === undefined ) return; // no data
  23540. let value = key[ valuePropertyName ];
  23541. if ( value === undefined ) return; // no data
  23542. if ( Array.isArray( value ) ) {
  23543. do {
  23544. value = key[ valuePropertyName ];
  23545. if ( value !== undefined ) {
  23546. times.push( key.time );
  23547. values.push.apply( values, value ); // push all elements
  23548. }
  23549. key = jsonKeys[ i ++ ];
  23550. } while ( key !== undefined );
  23551. } else if ( value.toArray !== undefined ) {
  23552. // ...assume THREE.Math-ish
  23553. do {
  23554. value = key[ valuePropertyName ];
  23555. if ( value !== undefined ) {
  23556. times.push( key.time );
  23557. value.toArray( values, values.length );
  23558. }
  23559. key = jsonKeys[ i ++ ];
  23560. } while ( key !== undefined );
  23561. } else {
  23562. // otherwise push as-is
  23563. do {
  23564. value = key[ valuePropertyName ];
  23565. if ( value !== undefined ) {
  23566. times.push( key.time );
  23567. values.push( value );
  23568. }
  23569. key = jsonKeys[ i ++ ];
  23570. } while ( key !== undefined );
  23571. }
  23572. }
  23573. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23574. const clip = sourceClip.clone();
  23575. clip.name = name;
  23576. const tracks = [];
  23577. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23578. const track = clip.tracks[ i ];
  23579. const valueSize = track.getValueSize();
  23580. const times = [];
  23581. const values = [];
  23582. for ( let j = 0; j < track.times.length; ++ j ) {
  23583. const frame = track.times[ j ] * fps;
  23584. if ( frame < startFrame || frame >= endFrame ) continue;
  23585. times.push( track.times[ j ] );
  23586. for ( let k = 0; k < valueSize; ++ k ) {
  23587. values.push( track.values[ j * valueSize + k ] );
  23588. }
  23589. }
  23590. if ( times.length === 0 ) continue;
  23591. track.times = convertArray( times, track.times.constructor );
  23592. track.values = convertArray( values, track.values.constructor );
  23593. tracks.push( track );
  23594. }
  23595. clip.tracks = tracks;
  23596. // find minimum .times value across all tracks in the trimmed clip
  23597. let minStartTime = Infinity;
  23598. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23599. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23600. minStartTime = clip.tracks[ i ].times[ 0 ];
  23601. }
  23602. }
  23603. // shift all tracks such that clip begins at t=0
  23604. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23605. clip.tracks[ i ].shift( - 1 * minStartTime );
  23606. }
  23607. clip.resetDuration();
  23608. return clip;
  23609. }
  23610. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23611. if ( fps <= 0 ) fps = 30;
  23612. const numTracks = referenceClip.tracks.length;
  23613. const referenceTime = referenceFrame / fps;
  23614. // Make each track's values relative to the values at the reference frame
  23615. for ( let i = 0; i < numTracks; ++ i ) {
  23616. const referenceTrack = referenceClip.tracks[ i ];
  23617. const referenceTrackType = referenceTrack.ValueTypeName;
  23618. // Skip this track if it's non-numeric
  23619. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23620. // Find the track in the target clip whose name and type matches the reference track
  23621. const targetTrack = targetClip.tracks.find( function ( track ) {
  23622. return track.name === referenceTrack.name
  23623. && track.ValueTypeName === referenceTrackType;
  23624. } );
  23625. if ( targetTrack === undefined ) continue;
  23626. let referenceOffset = 0;
  23627. const referenceValueSize = referenceTrack.getValueSize();
  23628. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23629. referenceOffset = referenceValueSize / 3;
  23630. }
  23631. let targetOffset = 0;
  23632. const targetValueSize = targetTrack.getValueSize();
  23633. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23634. targetOffset = targetValueSize / 3;
  23635. }
  23636. const lastIndex = referenceTrack.times.length - 1;
  23637. let referenceValue;
  23638. // Find the value to subtract out of the track
  23639. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23640. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23641. const startIndex = referenceOffset;
  23642. const endIndex = referenceValueSize - referenceOffset;
  23643. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23644. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23645. // Reference frame is after the last keyframe, so just use the last keyframe
  23646. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23647. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23648. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23649. } else {
  23650. // Interpolate to the reference value
  23651. const interpolant = referenceTrack.createInterpolant();
  23652. const startIndex = referenceOffset;
  23653. const endIndex = referenceValueSize - referenceOffset;
  23654. interpolant.evaluate( referenceTime );
  23655. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23656. }
  23657. // Conjugate the quaternion
  23658. if ( referenceTrackType === 'quaternion' ) {
  23659. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23660. referenceQuat.toArray( referenceValue );
  23661. }
  23662. // Subtract the reference value from all of the track values
  23663. const numTimes = targetTrack.times.length;
  23664. for ( let j = 0; j < numTimes; ++ j ) {
  23665. const valueStart = j * targetValueSize + targetOffset;
  23666. if ( referenceTrackType === 'quaternion' ) {
  23667. // Multiply the conjugate for quaternion track types
  23668. Quaternion.multiplyQuaternionsFlat(
  23669. targetTrack.values,
  23670. valueStart,
  23671. referenceValue,
  23672. 0,
  23673. targetTrack.values,
  23674. valueStart
  23675. );
  23676. } else {
  23677. const valueEnd = targetValueSize - targetOffset * 2;
  23678. // Subtract each value for all other numeric track types
  23679. for ( let k = 0; k < valueEnd; ++ k ) {
  23680. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23681. }
  23682. }
  23683. }
  23684. }
  23685. targetClip.blendMode = AdditiveAnimationBlendMode;
  23686. return targetClip;
  23687. }
  23688. const AnimationUtils = {
  23689. arraySlice: arraySlice,
  23690. convertArray: convertArray,
  23691. isTypedArray: isTypedArray,
  23692. getKeyframeOrder: getKeyframeOrder,
  23693. sortedArray: sortedArray,
  23694. flattenJSON: flattenJSON,
  23695. subclip: subclip,
  23696. makeClipAdditive: makeClipAdditive
  23697. };
  23698. /**
  23699. * Abstract base class of interpolants over parametric samples.
  23700. *
  23701. * The parameter domain is one dimensional, typically the time or a path
  23702. * along a curve defined by the data.
  23703. *
  23704. * The sample values can have any dimensionality and derived classes may
  23705. * apply special interpretations to the data.
  23706. *
  23707. * This class provides the interval seek in a Template Method, deferring
  23708. * the actual interpolation to derived classes.
  23709. *
  23710. * Time complexity is O(1) for linear access crossing at most two points
  23711. * and O(log N) for random access, where N is the number of positions.
  23712. *
  23713. * References:
  23714. *
  23715. * http://www.oodesign.com/template-method-pattern.html
  23716. *
  23717. */
  23718. class Interpolant {
  23719. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23720. this.parameterPositions = parameterPositions;
  23721. this._cachedIndex = 0;
  23722. this.resultBuffer = resultBuffer !== undefined ?
  23723. resultBuffer : new sampleValues.constructor( sampleSize );
  23724. this.sampleValues = sampleValues;
  23725. this.valueSize = sampleSize;
  23726. this.settings = null;
  23727. this.DefaultSettings_ = {};
  23728. }
  23729. evaluate( t ) {
  23730. const pp = this.parameterPositions;
  23731. let i1 = this._cachedIndex,
  23732. t1 = pp[ i1 ],
  23733. t0 = pp[ i1 - 1 ];
  23734. validate_interval: {
  23735. seek: {
  23736. let right;
  23737. linear_scan: {
  23738. //- See http://jsperf.com/comparison-to-undefined/3
  23739. //- slower code:
  23740. //-
  23741. //- if ( t >= t1 || t1 === undefined ) {
  23742. forward_scan: if ( ! ( t < t1 ) ) {
  23743. for ( let giveUpAt = i1 + 2; ; ) {
  23744. if ( t1 === undefined ) {
  23745. if ( t < t0 ) break forward_scan;
  23746. // after end
  23747. i1 = pp.length;
  23748. this._cachedIndex = i1;
  23749. return this.copySampleValue_( i1 - 1 );
  23750. }
  23751. if ( i1 === giveUpAt ) break; // this loop
  23752. t0 = t1;
  23753. t1 = pp[ ++ i1 ];
  23754. if ( t < t1 ) {
  23755. // we have arrived at the sought interval
  23756. break seek;
  23757. }
  23758. }
  23759. // prepare binary search on the right side of the index
  23760. right = pp.length;
  23761. break linear_scan;
  23762. }
  23763. //- slower code:
  23764. //- if ( t < t0 || t0 === undefined ) {
  23765. if ( ! ( t >= t0 ) ) {
  23766. // looping?
  23767. const t1global = pp[ 1 ];
  23768. if ( t < t1global ) {
  23769. i1 = 2; // + 1, using the scan for the details
  23770. t0 = t1global;
  23771. }
  23772. // linear reverse scan
  23773. for ( let giveUpAt = i1 - 2; ; ) {
  23774. if ( t0 === undefined ) {
  23775. // before start
  23776. this._cachedIndex = 0;
  23777. return this.copySampleValue_( 0 );
  23778. }
  23779. if ( i1 === giveUpAt ) break; // this loop
  23780. t1 = t0;
  23781. t0 = pp[ -- i1 - 1 ];
  23782. if ( t >= t0 ) {
  23783. // we have arrived at the sought interval
  23784. break seek;
  23785. }
  23786. }
  23787. // prepare binary search on the left side of the index
  23788. right = i1;
  23789. i1 = 0;
  23790. break linear_scan;
  23791. }
  23792. // the interval is valid
  23793. break validate_interval;
  23794. } // linear scan
  23795. // binary search
  23796. while ( i1 < right ) {
  23797. const mid = ( i1 + right ) >>> 1;
  23798. if ( t < pp[ mid ] ) {
  23799. right = mid;
  23800. } else {
  23801. i1 = mid + 1;
  23802. }
  23803. }
  23804. t1 = pp[ i1 ];
  23805. t0 = pp[ i1 - 1 ];
  23806. // check boundary cases, again
  23807. if ( t0 === undefined ) {
  23808. this._cachedIndex = 0;
  23809. return this.copySampleValue_( 0 );
  23810. }
  23811. if ( t1 === undefined ) {
  23812. i1 = pp.length;
  23813. this._cachedIndex = i1;
  23814. return this.copySampleValue_( i1 - 1 );
  23815. }
  23816. } // seek
  23817. this._cachedIndex = i1;
  23818. this.intervalChanged_( i1, t0, t1 );
  23819. } // validate_interval
  23820. return this.interpolate_( i1, t0, t, t1 );
  23821. }
  23822. getSettings_() {
  23823. return this.settings || this.DefaultSettings_;
  23824. }
  23825. copySampleValue_( index ) {
  23826. // copies a sample value to the result buffer
  23827. const result = this.resultBuffer,
  23828. values = this.sampleValues,
  23829. stride = this.valueSize,
  23830. offset = index * stride;
  23831. for ( let i = 0; i !== stride; ++ i ) {
  23832. result[ i ] = values[ offset + i ];
  23833. }
  23834. return result;
  23835. }
  23836. // Template methods for derived classes:
  23837. interpolate_( /* i1, t0, t, t1 */ ) {
  23838. throw new Error( 'call to abstract method' );
  23839. // implementations shall return this.resultBuffer
  23840. }
  23841. intervalChanged_( /* i1, t0, t1 */ ) {
  23842. // empty
  23843. }
  23844. }
  23845. /**
  23846. * Fast and simple cubic spline interpolant.
  23847. *
  23848. * It was derived from a Hermitian construction setting the first derivative
  23849. * at each sample position to the linear slope between neighboring positions
  23850. * over their parameter interval.
  23851. */
  23852. class CubicInterpolant extends Interpolant {
  23853. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23854. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23855. this._weightPrev = - 0;
  23856. this._offsetPrev = - 0;
  23857. this._weightNext = - 0;
  23858. this._offsetNext = - 0;
  23859. this.DefaultSettings_ = {
  23860. endingStart: ZeroCurvatureEnding,
  23861. endingEnd: ZeroCurvatureEnding
  23862. };
  23863. }
  23864. intervalChanged_( i1, t0, t1 ) {
  23865. const pp = this.parameterPositions;
  23866. let iPrev = i1 - 2,
  23867. iNext = i1 + 1,
  23868. tPrev = pp[ iPrev ],
  23869. tNext = pp[ iNext ];
  23870. if ( tPrev === undefined ) {
  23871. switch ( this.getSettings_().endingStart ) {
  23872. case ZeroSlopeEnding:
  23873. // f'(t0) = 0
  23874. iPrev = i1;
  23875. tPrev = 2 * t0 - t1;
  23876. break;
  23877. case WrapAroundEnding:
  23878. // use the other end of the curve
  23879. iPrev = pp.length - 2;
  23880. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23881. break;
  23882. default: // ZeroCurvatureEnding
  23883. // f''(t0) = 0 a.k.a. Natural Spline
  23884. iPrev = i1;
  23885. tPrev = t1;
  23886. }
  23887. }
  23888. if ( tNext === undefined ) {
  23889. switch ( this.getSettings_().endingEnd ) {
  23890. case ZeroSlopeEnding:
  23891. // f'(tN) = 0
  23892. iNext = i1;
  23893. tNext = 2 * t1 - t0;
  23894. break;
  23895. case WrapAroundEnding:
  23896. // use the other end of the curve
  23897. iNext = 1;
  23898. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23899. break;
  23900. default: // ZeroCurvatureEnding
  23901. // f''(tN) = 0, a.k.a. Natural Spline
  23902. iNext = i1 - 1;
  23903. tNext = t0;
  23904. }
  23905. }
  23906. const halfDt = ( t1 - t0 ) * 0.5,
  23907. stride = this.valueSize;
  23908. this._weightPrev = halfDt / ( t0 - tPrev );
  23909. this._weightNext = halfDt / ( tNext - t1 );
  23910. this._offsetPrev = iPrev * stride;
  23911. this._offsetNext = iNext * stride;
  23912. }
  23913. interpolate_( i1, t0, t, t1 ) {
  23914. const result = this.resultBuffer,
  23915. values = this.sampleValues,
  23916. stride = this.valueSize,
  23917. o1 = i1 * stride, o0 = o1 - stride,
  23918. oP = this._offsetPrev, oN = this._offsetNext,
  23919. wP = this._weightPrev, wN = this._weightNext,
  23920. p = ( t - t0 ) / ( t1 - t0 ),
  23921. pp = p * p,
  23922. ppp = pp * p;
  23923. // evaluate polynomials
  23924. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23925. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23926. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23927. const sN = wN * ppp - wN * pp;
  23928. // combine data linearly
  23929. for ( let i = 0; i !== stride; ++ i ) {
  23930. result[ i ] =
  23931. sP * values[ oP + i ] +
  23932. s0 * values[ o0 + i ] +
  23933. s1 * values[ o1 + i ] +
  23934. sN * values[ oN + i ];
  23935. }
  23936. return result;
  23937. }
  23938. }
  23939. class LinearInterpolant extends Interpolant {
  23940. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23941. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23942. }
  23943. interpolate_( i1, t0, t, t1 ) {
  23944. const result = this.resultBuffer,
  23945. values = this.sampleValues,
  23946. stride = this.valueSize,
  23947. offset1 = i1 * stride,
  23948. offset0 = offset1 - stride,
  23949. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23950. weight0 = 1 - weight1;
  23951. for ( let i = 0; i !== stride; ++ i ) {
  23952. result[ i ] =
  23953. values[ offset0 + i ] * weight0 +
  23954. values[ offset1 + i ] * weight1;
  23955. }
  23956. return result;
  23957. }
  23958. }
  23959. /**
  23960. *
  23961. * Interpolant that evaluates to the sample value at the position preceding
  23962. * the parameter.
  23963. */
  23964. class DiscreteInterpolant extends Interpolant {
  23965. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23966. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23967. }
  23968. interpolate_( i1 /*, t0, t, t1 */ ) {
  23969. return this.copySampleValue_( i1 - 1 );
  23970. }
  23971. }
  23972. class KeyframeTrack {
  23973. constructor( name, times, values, interpolation ) {
  23974. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23975. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23976. this.name = name;
  23977. this.times = convertArray( times, this.TimeBufferType );
  23978. this.values = convertArray( values, this.ValueBufferType );
  23979. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23980. }
  23981. // Serialization (in static context, because of constructor invocation
  23982. // and automatic invocation of .toJSON):
  23983. static toJSON( track ) {
  23984. const trackType = track.constructor;
  23985. let json;
  23986. // derived classes can define a static toJSON method
  23987. if ( trackType.toJSON !== this.toJSON ) {
  23988. json = trackType.toJSON( track );
  23989. } else {
  23990. // by default, we assume the data can be serialized as-is
  23991. json = {
  23992. 'name': track.name,
  23993. 'times': convertArray( track.times, Array ),
  23994. 'values': convertArray( track.values, Array )
  23995. };
  23996. const interpolation = track.getInterpolation();
  23997. if ( interpolation !== track.DefaultInterpolation ) {
  23998. json.interpolation = interpolation;
  23999. }
  24000. }
  24001. json.type = track.ValueTypeName; // mandatory
  24002. return json;
  24003. }
  24004. InterpolantFactoryMethodDiscrete( result ) {
  24005. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  24006. }
  24007. InterpolantFactoryMethodLinear( result ) {
  24008. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24009. }
  24010. InterpolantFactoryMethodSmooth( result ) {
  24011. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  24012. }
  24013. setInterpolation( interpolation ) {
  24014. let factoryMethod;
  24015. switch ( interpolation ) {
  24016. case InterpolateDiscrete:
  24017. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  24018. break;
  24019. case InterpolateLinear:
  24020. factoryMethod = this.InterpolantFactoryMethodLinear;
  24021. break;
  24022. case InterpolateSmooth:
  24023. factoryMethod = this.InterpolantFactoryMethodSmooth;
  24024. break;
  24025. }
  24026. if ( factoryMethod === undefined ) {
  24027. const message = 'unsupported interpolation for ' +
  24028. this.ValueTypeName + ' keyframe track named ' + this.name;
  24029. if ( this.createInterpolant === undefined ) {
  24030. // fall back to default, unless the default itself is messed up
  24031. if ( interpolation !== this.DefaultInterpolation ) {
  24032. this.setInterpolation( this.DefaultInterpolation );
  24033. } else {
  24034. throw new Error( message ); // fatal, in this case
  24035. }
  24036. }
  24037. console.warn( 'THREE.KeyframeTrack:', message );
  24038. return this;
  24039. }
  24040. this.createInterpolant = factoryMethod;
  24041. return this;
  24042. }
  24043. getInterpolation() {
  24044. switch ( this.createInterpolant ) {
  24045. case this.InterpolantFactoryMethodDiscrete:
  24046. return InterpolateDiscrete;
  24047. case this.InterpolantFactoryMethodLinear:
  24048. return InterpolateLinear;
  24049. case this.InterpolantFactoryMethodSmooth:
  24050. return InterpolateSmooth;
  24051. }
  24052. }
  24053. getValueSize() {
  24054. return this.values.length / this.times.length;
  24055. }
  24056. // move all keyframes either forwards or backwards in time
  24057. shift( timeOffset ) {
  24058. if ( timeOffset !== 0.0 ) {
  24059. const times = this.times;
  24060. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24061. times[ i ] += timeOffset;
  24062. }
  24063. }
  24064. return this;
  24065. }
  24066. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  24067. scale( timeScale ) {
  24068. if ( timeScale !== 1.0 ) {
  24069. const times = this.times;
  24070. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24071. times[ i ] *= timeScale;
  24072. }
  24073. }
  24074. return this;
  24075. }
  24076. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  24077. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  24078. trim( startTime, endTime ) {
  24079. const times = this.times,
  24080. nKeys = times.length;
  24081. let from = 0,
  24082. to = nKeys - 1;
  24083. while ( from !== nKeys && times[ from ] < startTime ) {
  24084. ++ from;
  24085. }
  24086. while ( to !== - 1 && times[ to ] > endTime ) {
  24087. -- to;
  24088. }
  24089. ++ to; // inclusive -> exclusive bound
  24090. if ( from !== 0 || to !== nKeys ) {
  24091. // empty tracks are forbidden, so keep at least one keyframe
  24092. if ( from >= to ) {
  24093. to = Math.max( to, 1 );
  24094. from = to - 1;
  24095. }
  24096. const stride = this.getValueSize();
  24097. this.times = arraySlice( times, from, to );
  24098. this.values = arraySlice( this.values, from * stride, to * stride );
  24099. }
  24100. return this;
  24101. }
  24102. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  24103. validate() {
  24104. let valid = true;
  24105. const valueSize = this.getValueSize();
  24106. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  24107. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  24108. valid = false;
  24109. }
  24110. const times = this.times,
  24111. values = this.values,
  24112. nKeys = times.length;
  24113. if ( nKeys === 0 ) {
  24114. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  24115. valid = false;
  24116. }
  24117. let prevTime = null;
  24118. for ( let i = 0; i !== nKeys; i ++ ) {
  24119. const currTime = times[ i ];
  24120. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  24121. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  24122. valid = false;
  24123. break;
  24124. }
  24125. if ( prevTime !== null && prevTime > currTime ) {
  24126. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  24127. valid = false;
  24128. break;
  24129. }
  24130. prevTime = currTime;
  24131. }
  24132. if ( values !== undefined ) {
  24133. if ( isTypedArray( values ) ) {
  24134. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  24135. const value = values[ i ];
  24136. if ( isNaN( value ) ) {
  24137. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  24138. valid = false;
  24139. break;
  24140. }
  24141. }
  24142. }
  24143. }
  24144. return valid;
  24145. }
  24146. // removes equivalent sequential keys as common in morph target sequences
  24147. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  24148. optimize() {
  24149. // times or values may be shared with other tracks, so overwriting is unsafe
  24150. const times = arraySlice( this.times ),
  24151. values = arraySlice( this.values ),
  24152. stride = this.getValueSize(),
  24153. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  24154. lastIndex = times.length - 1;
  24155. let writeIndex = 1;
  24156. for ( let i = 1; i < lastIndex; ++ i ) {
  24157. let keep = false;
  24158. const time = times[ i ];
  24159. const timeNext = times[ i + 1 ];
  24160. // remove adjacent keyframes scheduled at the same time
  24161. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  24162. if ( ! smoothInterpolation ) {
  24163. // remove unnecessary keyframes same as their neighbors
  24164. const offset = i * stride,
  24165. offsetP = offset - stride,
  24166. offsetN = offset + stride;
  24167. for ( let j = 0; j !== stride; ++ j ) {
  24168. const value = values[ offset + j ];
  24169. if ( value !== values[ offsetP + j ] ||
  24170. value !== values[ offsetN + j ] ) {
  24171. keep = true;
  24172. break;
  24173. }
  24174. }
  24175. } else {
  24176. keep = true;
  24177. }
  24178. }
  24179. // in-place compaction
  24180. if ( keep ) {
  24181. if ( i !== writeIndex ) {
  24182. times[ writeIndex ] = times[ i ];
  24183. const readOffset = i * stride,
  24184. writeOffset = writeIndex * stride;
  24185. for ( let j = 0; j !== stride; ++ j ) {
  24186. values[ writeOffset + j ] = values[ readOffset + j ];
  24187. }
  24188. }
  24189. ++ writeIndex;
  24190. }
  24191. }
  24192. // flush last keyframe (compaction looks ahead)
  24193. if ( lastIndex > 0 ) {
  24194. times[ writeIndex ] = times[ lastIndex ];
  24195. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  24196. values[ writeOffset + j ] = values[ readOffset + j ];
  24197. }
  24198. ++ writeIndex;
  24199. }
  24200. if ( writeIndex !== times.length ) {
  24201. this.times = arraySlice( times, 0, writeIndex );
  24202. this.values = arraySlice( values, 0, writeIndex * stride );
  24203. } else {
  24204. this.times = times;
  24205. this.values = values;
  24206. }
  24207. return this;
  24208. }
  24209. clone() {
  24210. const times = arraySlice( this.times, 0 );
  24211. const values = arraySlice( this.values, 0 );
  24212. const TypedKeyframeTrack = this.constructor;
  24213. const track = new TypedKeyframeTrack( this.name, times, values );
  24214. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  24215. track.createInterpolant = this.createInterpolant;
  24216. return track;
  24217. }
  24218. }
  24219. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  24220. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  24221. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24222. /**
  24223. * A Track of Boolean keyframe values.
  24224. */
  24225. class BooleanKeyframeTrack extends KeyframeTrack {}
  24226. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  24227. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  24228. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24229. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24230. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24231. /**
  24232. * A Track of keyframe values that represent color.
  24233. */
  24234. class ColorKeyframeTrack extends KeyframeTrack {}
  24235. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  24236. /**
  24237. * A Track of numeric keyframe values.
  24238. */
  24239. class NumberKeyframeTrack extends KeyframeTrack {}
  24240. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  24241. /**
  24242. * Spherical linear unit quaternion interpolant.
  24243. */
  24244. class QuaternionLinearInterpolant extends Interpolant {
  24245. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24246. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24247. }
  24248. interpolate_( i1, t0, t, t1 ) {
  24249. const result = this.resultBuffer,
  24250. values = this.sampleValues,
  24251. stride = this.valueSize,
  24252. alpha = ( t - t0 ) / ( t1 - t0 );
  24253. let offset = i1 * stride;
  24254. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  24255. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24256. }
  24257. return result;
  24258. }
  24259. }
  24260. /**
  24261. * A Track of quaternion keyframe values.
  24262. */
  24263. class QuaternionKeyframeTrack extends KeyframeTrack {
  24264. InterpolantFactoryMethodLinear( result ) {
  24265. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24266. }
  24267. }
  24268. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  24269. // ValueBufferType is inherited
  24270. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24271. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24272. /**
  24273. * A Track that interpolates Strings
  24274. */
  24275. class StringKeyframeTrack extends KeyframeTrack {}
  24276. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  24277. StringKeyframeTrack.prototype.ValueBufferType = Array;
  24278. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24279. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24280. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24281. /**
  24282. * A Track of vectored keyframe values.
  24283. */
  24284. class VectorKeyframeTrack extends KeyframeTrack {}
  24285. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  24286. class AnimationClip {
  24287. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  24288. this.name = name;
  24289. this.tracks = tracks;
  24290. this.duration = duration;
  24291. this.blendMode = blendMode;
  24292. this.uuid = generateUUID();
  24293. // this means it should figure out its duration by scanning the tracks
  24294. if ( this.duration < 0 ) {
  24295. this.resetDuration();
  24296. }
  24297. }
  24298. static parse( json ) {
  24299. const tracks = [],
  24300. jsonTracks = json.tracks,
  24301. frameTime = 1.0 / ( json.fps || 1.0 );
  24302. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  24303. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  24304. }
  24305. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  24306. clip.uuid = json.uuid;
  24307. return clip;
  24308. }
  24309. static toJSON( clip ) {
  24310. const tracks = [],
  24311. clipTracks = clip.tracks;
  24312. const json = {
  24313. 'name': clip.name,
  24314. 'duration': clip.duration,
  24315. 'tracks': tracks,
  24316. 'uuid': clip.uuid,
  24317. 'blendMode': clip.blendMode
  24318. };
  24319. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  24320. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  24321. }
  24322. return json;
  24323. }
  24324. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  24325. const numMorphTargets = morphTargetSequence.length;
  24326. const tracks = [];
  24327. for ( let i = 0; i < numMorphTargets; i ++ ) {
  24328. let times = [];
  24329. let values = [];
  24330. times.push(
  24331. ( i + numMorphTargets - 1 ) % numMorphTargets,
  24332. i,
  24333. ( i + 1 ) % numMorphTargets );
  24334. values.push( 0, 1, 0 );
  24335. const order = getKeyframeOrder( times );
  24336. times = sortedArray( times, 1, order );
  24337. values = sortedArray( values, 1, order );
  24338. // if there is a key at the first frame, duplicate it as the
  24339. // last frame as well for perfect loop.
  24340. if ( ! noLoop && times[ 0 ] === 0 ) {
  24341. times.push( numMorphTargets );
  24342. values.push( values[ 0 ] );
  24343. }
  24344. tracks.push(
  24345. new NumberKeyframeTrack(
  24346. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  24347. times, values
  24348. ).scale( 1.0 / fps ) );
  24349. }
  24350. return new this( name, - 1, tracks );
  24351. }
  24352. static findByName( objectOrClipArray, name ) {
  24353. let clipArray = objectOrClipArray;
  24354. if ( ! Array.isArray( objectOrClipArray ) ) {
  24355. const o = objectOrClipArray;
  24356. clipArray = o.geometry && o.geometry.animations || o.animations;
  24357. }
  24358. for ( let i = 0; i < clipArray.length; i ++ ) {
  24359. if ( clipArray[ i ].name === name ) {
  24360. return clipArray[ i ];
  24361. }
  24362. }
  24363. return null;
  24364. }
  24365. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  24366. const animationToMorphTargets = {};
  24367. // tested with https://regex101.com/ on trick sequences
  24368. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24369. const pattern = /^([\w-]*?)([\d]+)$/;
  24370. // sort morph target names into animation groups based
  24371. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24372. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24373. const morphTarget = morphTargets[ i ];
  24374. const parts = morphTarget.name.match( pattern );
  24375. if ( parts && parts.length > 1 ) {
  24376. const name = parts[ 1 ];
  24377. let animationMorphTargets = animationToMorphTargets[ name ];
  24378. if ( ! animationMorphTargets ) {
  24379. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24380. }
  24381. animationMorphTargets.push( morphTarget );
  24382. }
  24383. }
  24384. const clips = [];
  24385. for ( const name in animationToMorphTargets ) {
  24386. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24387. }
  24388. return clips;
  24389. }
  24390. // parse the animation.hierarchy format
  24391. static parseAnimation( animation, bones ) {
  24392. if ( ! animation ) {
  24393. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24394. return null;
  24395. }
  24396. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24397. // only return track if there are actually keys.
  24398. if ( animationKeys.length !== 0 ) {
  24399. const times = [];
  24400. const values = [];
  24401. flattenJSON( animationKeys, times, values, propertyName );
  24402. // empty keys are filtered out, so check again
  24403. if ( times.length !== 0 ) {
  24404. destTracks.push( new trackType( trackName, times, values ) );
  24405. }
  24406. }
  24407. };
  24408. const tracks = [];
  24409. const clipName = animation.name || 'default';
  24410. const fps = animation.fps || 30;
  24411. const blendMode = animation.blendMode;
  24412. // automatic length determination in AnimationClip.
  24413. let duration = animation.length || - 1;
  24414. const hierarchyTracks = animation.hierarchy || [];
  24415. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24416. const animationKeys = hierarchyTracks[ h ].keys;
  24417. // skip empty tracks
  24418. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24419. // process morph targets
  24420. if ( animationKeys[ 0 ].morphTargets ) {
  24421. // figure out all morph targets used in this track
  24422. const morphTargetNames = {};
  24423. let k;
  24424. for ( k = 0; k < animationKeys.length; k ++ ) {
  24425. if ( animationKeys[ k ].morphTargets ) {
  24426. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24427. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  24428. }
  24429. }
  24430. }
  24431. // create a track for each morph target with all zero
  24432. // morphTargetInfluences except for the keys in which
  24433. // the morphTarget is named.
  24434. for ( const morphTargetName in morphTargetNames ) {
  24435. const times = [];
  24436. const values = [];
  24437. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24438. const animationKey = animationKeys[ k ];
  24439. times.push( animationKey.time );
  24440. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24441. }
  24442. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24443. }
  24444. duration = morphTargetNames.length * fps;
  24445. } else {
  24446. // ...assume skeletal animation
  24447. const boneName = '.bones[' + bones[ h ].name + ']';
  24448. addNonemptyTrack(
  24449. VectorKeyframeTrack, boneName + '.position',
  24450. animationKeys, 'pos', tracks );
  24451. addNonemptyTrack(
  24452. QuaternionKeyframeTrack, boneName + '.quaternion',
  24453. animationKeys, 'rot', tracks );
  24454. addNonemptyTrack(
  24455. VectorKeyframeTrack, boneName + '.scale',
  24456. animationKeys, 'scl', tracks );
  24457. }
  24458. }
  24459. if ( tracks.length === 0 ) {
  24460. return null;
  24461. }
  24462. const clip = new this( clipName, duration, tracks, blendMode );
  24463. return clip;
  24464. }
  24465. resetDuration() {
  24466. const tracks = this.tracks;
  24467. let duration = 0;
  24468. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24469. const track = this.tracks[ i ];
  24470. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24471. }
  24472. this.duration = duration;
  24473. return this;
  24474. }
  24475. trim() {
  24476. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24477. this.tracks[ i ].trim( 0, this.duration );
  24478. }
  24479. return this;
  24480. }
  24481. validate() {
  24482. let valid = true;
  24483. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24484. valid = valid && this.tracks[ i ].validate();
  24485. }
  24486. return valid;
  24487. }
  24488. optimize() {
  24489. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24490. this.tracks[ i ].optimize();
  24491. }
  24492. return this;
  24493. }
  24494. clone() {
  24495. const tracks = [];
  24496. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24497. tracks.push( this.tracks[ i ].clone() );
  24498. }
  24499. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24500. }
  24501. toJSON() {
  24502. return this.constructor.toJSON( this );
  24503. }
  24504. }
  24505. function getTrackTypeForValueTypeName( typeName ) {
  24506. switch ( typeName.toLowerCase() ) {
  24507. case 'scalar':
  24508. case 'double':
  24509. case 'float':
  24510. case 'number':
  24511. case 'integer':
  24512. return NumberKeyframeTrack;
  24513. case 'vector':
  24514. case 'vector2':
  24515. case 'vector3':
  24516. case 'vector4':
  24517. return VectorKeyframeTrack;
  24518. case 'color':
  24519. return ColorKeyframeTrack;
  24520. case 'quaternion':
  24521. return QuaternionKeyframeTrack;
  24522. case 'bool':
  24523. case 'boolean':
  24524. return BooleanKeyframeTrack;
  24525. case 'string':
  24526. return StringKeyframeTrack;
  24527. }
  24528. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24529. }
  24530. function parseKeyframeTrack( json ) {
  24531. if ( json.type === undefined ) {
  24532. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24533. }
  24534. const trackType = getTrackTypeForValueTypeName( json.type );
  24535. if ( json.times === undefined ) {
  24536. const times = [], values = [];
  24537. flattenJSON( json.keys, times, values, 'value' );
  24538. json.times = times;
  24539. json.values = values;
  24540. }
  24541. // derived classes can define a static parse method
  24542. if ( trackType.parse !== undefined ) {
  24543. return trackType.parse( json );
  24544. } else {
  24545. // by default, we assume a constructor compatible with the base
  24546. return new trackType( json.name, json.times, json.values, json.interpolation );
  24547. }
  24548. }
  24549. const Cache = {
  24550. enabled: false,
  24551. files: {},
  24552. add: function ( key, file ) {
  24553. if ( this.enabled === false ) return;
  24554. // console.log( 'THREE.Cache', 'Adding key:', key );
  24555. this.files[ key ] = file;
  24556. },
  24557. get: function ( key ) {
  24558. if ( this.enabled === false ) return;
  24559. // console.log( 'THREE.Cache', 'Checking key:', key );
  24560. return this.files[ key ];
  24561. },
  24562. remove: function ( key ) {
  24563. delete this.files[ key ];
  24564. },
  24565. clear: function () {
  24566. this.files = {};
  24567. }
  24568. };
  24569. class LoadingManager {
  24570. constructor( onLoad, onProgress, onError ) {
  24571. const scope = this;
  24572. let isLoading = false;
  24573. let itemsLoaded = 0;
  24574. let itemsTotal = 0;
  24575. let urlModifier = undefined;
  24576. const handlers = [];
  24577. // Refer to #5689 for the reason why we don't set .onStart
  24578. // in the constructor
  24579. this.onStart = undefined;
  24580. this.onLoad = onLoad;
  24581. this.onProgress = onProgress;
  24582. this.onError = onError;
  24583. this.itemStart = function ( url ) {
  24584. itemsTotal ++;
  24585. if ( isLoading === false ) {
  24586. if ( scope.onStart !== undefined ) {
  24587. scope.onStart( url, itemsLoaded, itemsTotal );
  24588. }
  24589. }
  24590. isLoading = true;
  24591. };
  24592. this.itemEnd = function ( url ) {
  24593. itemsLoaded ++;
  24594. if ( scope.onProgress !== undefined ) {
  24595. scope.onProgress( url, itemsLoaded, itemsTotal );
  24596. }
  24597. if ( itemsLoaded === itemsTotal ) {
  24598. isLoading = false;
  24599. if ( scope.onLoad !== undefined ) {
  24600. scope.onLoad();
  24601. }
  24602. }
  24603. };
  24604. this.itemError = function ( url ) {
  24605. if ( scope.onError !== undefined ) {
  24606. scope.onError( url );
  24607. }
  24608. };
  24609. this.resolveURL = function ( url ) {
  24610. if ( urlModifier ) {
  24611. return urlModifier( url );
  24612. }
  24613. return url;
  24614. };
  24615. this.setURLModifier = function ( transform ) {
  24616. urlModifier = transform;
  24617. return this;
  24618. };
  24619. this.addHandler = function ( regex, loader ) {
  24620. handlers.push( regex, loader );
  24621. return this;
  24622. };
  24623. this.removeHandler = function ( regex ) {
  24624. const index = handlers.indexOf( regex );
  24625. if ( index !== - 1 ) {
  24626. handlers.splice( index, 2 );
  24627. }
  24628. return this;
  24629. };
  24630. this.getHandler = function ( file ) {
  24631. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24632. const regex = handlers[ i ];
  24633. const loader = handlers[ i + 1 ];
  24634. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24635. if ( regex.test( file ) ) {
  24636. return loader;
  24637. }
  24638. }
  24639. return null;
  24640. };
  24641. }
  24642. }
  24643. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24644. class Loader {
  24645. constructor( manager ) {
  24646. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24647. this.crossOrigin = 'anonymous';
  24648. this.withCredentials = false;
  24649. this.path = '';
  24650. this.resourcePath = '';
  24651. this.requestHeader = {};
  24652. }
  24653. load( /* url, onLoad, onProgress, onError */ ) {}
  24654. loadAsync( url, onProgress ) {
  24655. const scope = this;
  24656. return new Promise( function ( resolve, reject ) {
  24657. scope.load( url, resolve, onProgress, reject );
  24658. } );
  24659. }
  24660. parse( /* data */ ) {}
  24661. setCrossOrigin( crossOrigin ) {
  24662. this.crossOrigin = crossOrigin;
  24663. return this;
  24664. }
  24665. setWithCredentials( value ) {
  24666. this.withCredentials = value;
  24667. return this;
  24668. }
  24669. setPath( path ) {
  24670. this.path = path;
  24671. return this;
  24672. }
  24673. setResourcePath( resourcePath ) {
  24674. this.resourcePath = resourcePath;
  24675. return this;
  24676. }
  24677. setRequestHeader( requestHeader ) {
  24678. this.requestHeader = requestHeader;
  24679. return this;
  24680. }
  24681. }
  24682. const loading = {};
  24683. class HttpError extends Error {
  24684. constructor( message, response ) {
  24685. super( message );
  24686. this.response = response;
  24687. }
  24688. }
  24689. class FileLoader extends Loader {
  24690. constructor( manager ) {
  24691. super( manager );
  24692. }
  24693. load( url, onLoad, onProgress, onError ) {
  24694. if ( url === undefined ) url = '';
  24695. if ( this.path !== undefined ) url = this.path + url;
  24696. url = this.manager.resolveURL( url );
  24697. const cached = Cache.get( url );
  24698. if ( cached !== undefined ) {
  24699. this.manager.itemStart( url );
  24700. setTimeout( () => {
  24701. if ( onLoad ) onLoad( cached );
  24702. this.manager.itemEnd( url );
  24703. }, 0 );
  24704. return cached;
  24705. }
  24706. // Check if request is duplicate
  24707. if ( loading[ url ] !== undefined ) {
  24708. loading[ url ].push( {
  24709. onLoad: onLoad,
  24710. onProgress: onProgress,
  24711. onError: onError
  24712. } );
  24713. return;
  24714. }
  24715. // Initialise array for duplicate requests
  24716. loading[ url ] = [];
  24717. loading[ url ].push( {
  24718. onLoad: onLoad,
  24719. onProgress: onProgress,
  24720. onError: onError,
  24721. } );
  24722. // create request
  24723. const req = new Request( url, {
  24724. headers: new Headers( this.requestHeader ),
  24725. credentials: this.withCredentials ? 'include' : 'same-origin',
  24726. // An abort controller could be added within a future PR
  24727. } );
  24728. // record states ( avoid data race )
  24729. const mimeType = this.mimeType;
  24730. const responseType = this.responseType;
  24731. // start the fetch
  24732. fetch( req )
  24733. .then( response => {
  24734. if ( response.status === 200 || response.status === 0 ) {
  24735. // Some browsers return HTTP Status 0 when using non-http protocol
  24736. // e.g. 'file://' or 'data://'. Handle as success.
  24737. if ( response.status === 0 ) {
  24738. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24739. }
  24740. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24741. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24742. return response;
  24743. }
  24744. const callbacks = loading[ url ];
  24745. const reader = response.body.getReader();
  24746. // Nginx needs X-File-Size check
  24747. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24748. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24749. const total = contentLength ? parseInt( contentLength ) : 0;
  24750. const lengthComputable = total !== 0;
  24751. let loaded = 0;
  24752. // periodically read data into the new stream tracking while download progress
  24753. const stream = new ReadableStream( {
  24754. start( controller ) {
  24755. readData();
  24756. function readData() {
  24757. reader.read().then( ( { done, value } ) => {
  24758. if ( done ) {
  24759. controller.close();
  24760. } else {
  24761. loaded += value.byteLength;
  24762. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24763. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24764. const callback = callbacks[ i ];
  24765. if ( callback.onProgress ) callback.onProgress( event );
  24766. }
  24767. controller.enqueue( value );
  24768. readData();
  24769. }
  24770. } );
  24771. }
  24772. }
  24773. } );
  24774. return new Response( stream );
  24775. } else {
  24776. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24777. }
  24778. } )
  24779. .then( response => {
  24780. switch ( responseType ) {
  24781. case 'arraybuffer':
  24782. return response.arrayBuffer();
  24783. case 'blob':
  24784. return response.blob();
  24785. case 'document':
  24786. return response.text()
  24787. .then( text => {
  24788. const parser = new DOMParser();
  24789. return parser.parseFromString( text, mimeType );
  24790. } );
  24791. case 'json':
  24792. return response.json();
  24793. default:
  24794. if ( mimeType === undefined ) {
  24795. return response.text();
  24796. } else {
  24797. // sniff encoding
  24798. const re = /charset="?([^;"\s]*)"?/i;
  24799. const exec = re.exec( mimeType );
  24800. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24801. const decoder = new TextDecoder( label );
  24802. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24803. }
  24804. }
  24805. } )
  24806. .then( data => {
  24807. // Add to cache only on HTTP success, so that we do not cache
  24808. // error response bodies as proper responses to requests.
  24809. Cache.add( url, data );
  24810. const callbacks = loading[ url ];
  24811. delete loading[ url ];
  24812. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24813. const callback = callbacks[ i ];
  24814. if ( callback.onLoad ) callback.onLoad( data );
  24815. }
  24816. } )
  24817. .catch( err => {
  24818. // Abort errors and other errors are handled the same
  24819. const callbacks = loading[ url ];
  24820. if ( callbacks === undefined ) {
  24821. // When onLoad was called and url was deleted in `loading`
  24822. this.manager.itemError( url );
  24823. throw err;
  24824. }
  24825. delete loading[ url ];
  24826. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24827. const callback = callbacks[ i ];
  24828. if ( callback.onError ) callback.onError( err );
  24829. }
  24830. this.manager.itemError( url );
  24831. } )
  24832. .finally( () => {
  24833. this.manager.itemEnd( url );
  24834. } );
  24835. this.manager.itemStart( url );
  24836. }
  24837. setResponseType( value ) {
  24838. this.responseType = value;
  24839. return this;
  24840. }
  24841. setMimeType( value ) {
  24842. this.mimeType = value;
  24843. return this;
  24844. }
  24845. }
  24846. class AnimationLoader extends Loader {
  24847. constructor( manager ) {
  24848. super( manager );
  24849. }
  24850. load( url, onLoad, onProgress, onError ) {
  24851. const scope = this;
  24852. const loader = new FileLoader( this.manager );
  24853. loader.setPath( this.path );
  24854. loader.setRequestHeader( this.requestHeader );
  24855. loader.setWithCredentials( this.withCredentials );
  24856. loader.load( url, function ( text ) {
  24857. try {
  24858. onLoad( scope.parse( JSON.parse( text ) ) );
  24859. } catch ( e ) {
  24860. if ( onError ) {
  24861. onError( e );
  24862. } else {
  24863. console.error( e );
  24864. }
  24865. scope.manager.itemError( url );
  24866. }
  24867. }, onProgress, onError );
  24868. }
  24869. parse( json ) {
  24870. const animations = [];
  24871. for ( let i = 0; i < json.length; i ++ ) {
  24872. const clip = AnimationClip.parse( json[ i ] );
  24873. animations.push( clip );
  24874. }
  24875. return animations;
  24876. }
  24877. }
  24878. /**
  24879. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24880. *
  24881. * Sub classes have to implement the parse() method which will be used in load().
  24882. */
  24883. class CompressedTextureLoader extends Loader {
  24884. constructor( manager ) {
  24885. super( manager );
  24886. }
  24887. load( url, onLoad, onProgress, onError ) {
  24888. const scope = this;
  24889. const images = [];
  24890. const texture = new CompressedTexture();
  24891. const loader = new FileLoader( this.manager );
  24892. loader.setPath( this.path );
  24893. loader.setResponseType( 'arraybuffer' );
  24894. loader.setRequestHeader( this.requestHeader );
  24895. loader.setWithCredentials( scope.withCredentials );
  24896. let loaded = 0;
  24897. function loadTexture( i ) {
  24898. loader.load( url[ i ], function ( buffer ) {
  24899. const texDatas = scope.parse( buffer, true );
  24900. images[ i ] = {
  24901. width: texDatas.width,
  24902. height: texDatas.height,
  24903. format: texDatas.format,
  24904. mipmaps: texDatas.mipmaps
  24905. };
  24906. loaded += 1;
  24907. if ( loaded === 6 ) {
  24908. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24909. texture.image = images;
  24910. texture.format = texDatas.format;
  24911. texture.needsUpdate = true;
  24912. if ( onLoad ) onLoad( texture );
  24913. }
  24914. }, onProgress, onError );
  24915. }
  24916. if ( Array.isArray( url ) ) {
  24917. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24918. loadTexture( i );
  24919. }
  24920. } else {
  24921. // compressed cubemap texture stored in a single DDS file
  24922. loader.load( url, function ( buffer ) {
  24923. const texDatas = scope.parse( buffer, true );
  24924. if ( texDatas.isCubemap ) {
  24925. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24926. for ( let f = 0; f < faces; f ++ ) {
  24927. images[ f ] = { mipmaps: [] };
  24928. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24929. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24930. images[ f ].format = texDatas.format;
  24931. images[ f ].width = texDatas.width;
  24932. images[ f ].height = texDatas.height;
  24933. }
  24934. }
  24935. texture.image = images;
  24936. } else {
  24937. texture.image.width = texDatas.width;
  24938. texture.image.height = texDatas.height;
  24939. texture.mipmaps = texDatas.mipmaps;
  24940. }
  24941. if ( texDatas.mipmapCount === 1 ) {
  24942. texture.minFilter = LinearFilter;
  24943. }
  24944. texture.format = texDatas.format;
  24945. texture.needsUpdate = true;
  24946. if ( onLoad ) onLoad( texture );
  24947. }, onProgress, onError );
  24948. }
  24949. return texture;
  24950. }
  24951. }
  24952. class ImageLoader extends Loader {
  24953. constructor( manager ) {
  24954. super( manager );
  24955. }
  24956. load( url, onLoad, onProgress, onError ) {
  24957. if ( this.path !== undefined ) url = this.path + url;
  24958. url = this.manager.resolveURL( url );
  24959. const scope = this;
  24960. const cached = Cache.get( url );
  24961. if ( cached !== undefined ) {
  24962. scope.manager.itemStart( url );
  24963. setTimeout( function () {
  24964. if ( onLoad ) onLoad( cached );
  24965. scope.manager.itemEnd( url );
  24966. }, 0 );
  24967. return cached;
  24968. }
  24969. const image = createElementNS( 'img' );
  24970. function onImageLoad() {
  24971. removeEventListeners();
  24972. Cache.add( url, this );
  24973. if ( onLoad ) onLoad( this );
  24974. scope.manager.itemEnd( url );
  24975. }
  24976. function onImageError( event ) {
  24977. removeEventListeners();
  24978. if ( onError ) onError( event );
  24979. scope.manager.itemError( url );
  24980. scope.manager.itemEnd( url );
  24981. }
  24982. function removeEventListeners() {
  24983. image.removeEventListener( 'load', onImageLoad, false );
  24984. image.removeEventListener( 'error', onImageError, false );
  24985. }
  24986. image.addEventListener( 'load', onImageLoad, false );
  24987. image.addEventListener( 'error', onImageError, false );
  24988. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24989. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24990. }
  24991. scope.manager.itemStart( url );
  24992. image.src = url;
  24993. return image;
  24994. }
  24995. }
  24996. class CubeTextureLoader extends Loader {
  24997. constructor( manager ) {
  24998. super( manager );
  24999. }
  25000. load( urls, onLoad, onProgress, onError ) {
  25001. const texture = new CubeTexture();
  25002. texture.colorSpace = SRGBColorSpace;
  25003. const loader = new ImageLoader( this.manager );
  25004. loader.setCrossOrigin( this.crossOrigin );
  25005. loader.setPath( this.path );
  25006. let loaded = 0;
  25007. function loadTexture( i ) {
  25008. loader.load( urls[ i ], function ( image ) {
  25009. texture.images[ i ] = image;
  25010. loaded ++;
  25011. if ( loaded === 6 ) {
  25012. texture.needsUpdate = true;
  25013. if ( onLoad ) onLoad( texture );
  25014. }
  25015. }, undefined, onError );
  25016. }
  25017. for ( let i = 0; i < urls.length; ++ i ) {
  25018. loadTexture( i );
  25019. }
  25020. return texture;
  25021. }
  25022. }
  25023. /**
  25024. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25025. *
  25026. * Sub classes have to implement the parse() method which will be used in load().
  25027. */
  25028. class DataTextureLoader extends Loader {
  25029. constructor( manager ) {
  25030. super( manager );
  25031. }
  25032. load( url, onLoad, onProgress, onError ) {
  25033. const scope = this;
  25034. const texture = new DataTexture();
  25035. const loader = new FileLoader( this.manager );
  25036. loader.setResponseType( 'arraybuffer' );
  25037. loader.setRequestHeader( this.requestHeader );
  25038. loader.setPath( this.path );
  25039. loader.setWithCredentials( scope.withCredentials );
  25040. loader.load( url, function ( buffer ) {
  25041. const texData = scope.parse( buffer );
  25042. if ( ! texData ) return;
  25043. if ( texData.image !== undefined ) {
  25044. texture.image = texData.image;
  25045. } else if ( texData.data !== undefined ) {
  25046. texture.image.width = texData.width;
  25047. texture.image.height = texData.height;
  25048. texture.image.data = texData.data;
  25049. }
  25050. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25051. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25052. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25053. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  25054. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25055. if ( texData.colorSpace !== undefined ) {
  25056. texture.colorSpace = texData.colorSpace;
  25057. } else if ( texData.encoding !== undefined ) { // @deprecated, r152
  25058. texture.encoding = texData.encoding;
  25059. }
  25060. if ( texData.flipY !== undefined ) {
  25061. texture.flipY = texData.flipY;
  25062. }
  25063. if ( texData.format !== undefined ) {
  25064. texture.format = texData.format;
  25065. }
  25066. if ( texData.type !== undefined ) {
  25067. texture.type = texData.type;
  25068. }
  25069. if ( texData.mipmaps !== undefined ) {
  25070. texture.mipmaps = texData.mipmaps;
  25071. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  25072. }
  25073. if ( texData.mipmapCount === 1 ) {
  25074. texture.minFilter = LinearFilter;
  25075. }
  25076. if ( texData.generateMipmaps !== undefined ) {
  25077. texture.generateMipmaps = texData.generateMipmaps;
  25078. }
  25079. texture.needsUpdate = true;
  25080. if ( onLoad ) onLoad( texture, texData );
  25081. }, onProgress, onError );
  25082. return texture;
  25083. }
  25084. }
  25085. class TextureLoader extends Loader {
  25086. constructor( manager ) {
  25087. super( manager );
  25088. }
  25089. load( url, onLoad, onProgress, onError ) {
  25090. const texture = new Texture();
  25091. const loader = new ImageLoader( this.manager );
  25092. loader.setCrossOrigin( this.crossOrigin );
  25093. loader.setPath( this.path );
  25094. loader.load( url, function ( image ) {
  25095. texture.image = image;
  25096. texture.needsUpdate = true;
  25097. if ( onLoad !== undefined ) {
  25098. onLoad( texture );
  25099. }
  25100. }, onProgress, onError );
  25101. return texture;
  25102. }
  25103. }
  25104. class Light extends Object3D {
  25105. constructor( color, intensity = 1 ) {
  25106. super();
  25107. this.isLight = true;
  25108. this.type = 'Light';
  25109. this.color = new Color( color );
  25110. this.intensity = intensity;
  25111. }
  25112. dispose() {
  25113. // Empty here in base class; some subclasses override.
  25114. }
  25115. copy( source, recursive ) {
  25116. super.copy( source, recursive );
  25117. this.color.copy( source.color );
  25118. this.intensity = source.intensity;
  25119. return this;
  25120. }
  25121. toJSON( meta ) {
  25122. const data = super.toJSON( meta );
  25123. data.object.color = this.color.getHex();
  25124. data.object.intensity = this.intensity;
  25125. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  25126. if ( this.distance !== undefined ) data.object.distance = this.distance;
  25127. if ( this.angle !== undefined ) data.object.angle = this.angle;
  25128. if ( this.decay !== undefined ) data.object.decay = this.decay;
  25129. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  25130. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  25131. return data;
  25132. }
  25133. }
  25134. class HemisphereLight extends Light {
  25135. constructor( skyColor, groundColor, intensity ) {
  25136. super( skyColor, intensity );
  25137. this.isHemisphereLight = true;
  25138. this.type = 'HemisphereLight';
  25139. this.position.copy( Object3D.DEFAULT_UP );
  25140. this.updateMatrix();
  25141. this.groundColor = new Color( groundColor );
  25142. }
  25143. copy( source, recursive ) {
  25144. super.copy( source, recursive );
  25145. this.groundColor.copy( source.groundColor );
  25146. return this;
  25147. }
  25148. }
  25149. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  25150. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  25151. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  25152. class LightShadow {
  25153. constructor( camera ) {
  25154. this.camera = camera;
  25155. this.bias = 0;
  25156. this.normalBias = 0;
  25157. this.radius = 1;
  25158. this.blurSamples = 8;
  25159. this.mapSize = new Vector2( 512, 512 );
  25160. this.map = null;
  25161. this.mapPass = null;
  25162. this.matrix = new Matrix4();
  25163. this.autoUpdate = true;
  25164. this.needsUpdate = false;
  25165. this._frustum = new Frustum();
  25166. this._frameExtents = new Vector2( 1, 1 );
  25167. this._viewportCount = 1;
  25168. this._viewports = [
  25169. new Vector4( 0, 0, 1, 1 )
  25170. ];
  25171. }
  25172. getViewportCount() {
  25173. return this._viewportCount;
  25174. }
  25175. getFrustum() {
  25176. return this._frustum;
  25177. }
  25178. updateMatrices( light ) {
  25179. const shadowCamera = this.camera;
  25180. const shadowMatrix = this.matrix;
  25181. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  25182. shadowCamera.position.copy( _lightPositionWorld$1 );
  25183. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  25184. shadowCamera.lookAt( _lookTarget$1 );
  25185. shadowCamera.updateMatrixWorld();
  25186. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  25187. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  25188. shadowMatrix.set(
  25189. 0.5, 0.0, 0.0, 0.5,
  25190. 0.0, 0.5, 0.0, 0.5,
  25191. 0.0, 0.0, 0.5, 0.5,
  25192. 0.0, 0.0, 0.0, 1.0
  25193. );
  25194. shadowMatrix.multiply( _projScreenMatrix$1 );
  25195. }
  25196. getViewport( viewportIndex ) {
  25197. return this._viewports[ viewportIndex ];
  25198. }
  25199. getFrameExtents() {
  25200. return this._frameExtents;
  25201. }
  25202. dispose() {
  25203. if ( this.map ) {
  25204. this.map.dispose();
  25205. }
  25206. if ( this.mapPass ) {
  25207. this.mapPass.dispose();
  25208. }
  25209. }
  25210. copy( source ) {
  25211. this.camera = source.camera.clone();
  25212. this.bias = source.bias;
  25213. this.radius = source.radius;
  25214. this.mapSize.copy( source.mapSize );
  25215. return this;
  25216. }
  25217. clone() {
  25218. return new this.constructor().copy( this );
  25219. }
  25220. toJSON() {
  25221. const object = {};
  25222. if ( this.bias !== 0 ) object.bias = this.bias;
  25223. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  25224. if ( this.radius !== 1 ) object.radius = this.radius;
  25225. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  25226. object.camera = this.camera.toJSON( false ).object;
  25227. delete object.camera.matrix;
  25228. return object;
  25229. }
  25230. }
  25231. class SpotLightShadow extends LightShadow {
  25232. constructor() {
  25233. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  25234. this.isSpotLightShadow = true;
  25235. this.focus = 1;
  25236. }
  25237. updateMatrices( light ) {
  25238. const camera = this.camera;
  25239. const fov = RAD2DEG * 2 * light.angle * this.focus;
  25240. const aspect = this.mapSize.width / this.mapSize.height;
  25241. const far = light.distance || camera.far;
  25242. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  25243. camera.fov = fov;
  25244. camera.aspect = aspect;
  25245. camera.far = far;
  25246. camera.updateProjectionMatrix();
  25247. }
  25248. super.updateMatrices( light );
  25249. }
  25250. copy( source ) {
  25251. super.copy( source );
  25252. this.focus = source.focus;
  25253. return this;
  25254. }
  25255. }
  25256. class SpotLight extends Light {
  25257. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  25258. super( color, intensity );
  25259. this.isSpotLight = true;
  25260. this.type = 'SpotLight';
  25261. this.position.copy( Object3D.DEFAULT_UP );
  25262. this.updateMatrix();
  25263. this.target = new Object3D();
  25264. this.distance = distance;
  25265. this.angle = angle;
  25266. this.penumbra = penumbra;
  25267. this.decay = decay;
  25268. this.map = null;
  25269. this.shadow = new SpotLightShadow();
  25270. }
  25271. get power() {
  25272. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25273. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  25274. return this.intensity * Math.PI;
  25275. }
  25276. set power( power ) {
  25277. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25278. this.intensity = power / Math.PI;
  25279. }
  25280. dispose() {
  25281. this.shadow.dispose();
  25282. }
  25283. copy( source, recursive ) {
  25284. super.copy( source, recursive );
  25285. this.distance = source.distance;
  25286. this.angle = source.angle;
  25287. this.penumbra = source.penumbra;
  25288. this.decay = source.decay;
  25289. this.target = source.target.clone();
  25290. this.shadow = source.shadow.clone();
  25291. return this;
  25292. }
  25293. }
  25294. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  25295. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  25296. const _lookTarget = /*@__PURE__*/ new Vector3();
  25297. class PointLightShadow extends LightShadow {
  25298. constructor() {
  25299. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25300. this.isPointLightShadow = true;
  25301. this._frameExtents = new Vector2( 4, 2 );
  25302. this._viewportCount = 6;
  25303. this._viewports = [
  25304. // These viewports map a cube-map onto a 2D texture with the
  25305. // following orientation:
  25306. //
  25307. // xzXZ
  25308. // y Y
  25309. //
  25310. // X - Positive x direction
  25311. // x - Negative x direction
  25312. // Y - Positive y direction
  25313. // y - Negative y direction
  25314. // Z - Positive z direction
  25315. // z - Negative z direction
  25316. // positive X
  25317. new Vector4( 2, 1, 1, 1 ),
  25318. // negative X
  25319. new Vector4( 0, 1, 1, 1 ),
  25320. // positive Z
  25321. new Vector4( 3, 1, 1, 1 ),
  25322. // negative Z
  25323. new Vector4( 1, 1, 1, 1 ),
  25324. // positive Y
  25325. new Vector4( 3, 0, 1, 1 ),
  25326. // negative Y
  25327. new Vector4( 1, 0, 1, 1 )
  25328. ];
  25329. this._cubeDirections = [
  25330. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  25331. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  25332. ];
  25333. this._cubeUps = [
  25334. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  25335. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  25336. ];
  25337. }
  25338. updateMatrices( light, viewportIndex = 0 ) {
  25339. const camera = this.camera;
  25340. const shadowMatrix = this.matrix;
  25341. const far = light.distance || camera.far;
  25342. if ( far !== camera.far ) {
  25343. camera.far = far;
  25344. camera.updateProjectionMatrix();
  25345. }
  25346. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  25347. camera.position.copy( _lightPositionWorld );
  25348. _lookTarget.copy( camera.position );
  25349. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  25350. camera.up.copy( this._cubeUps[ viewportIndex ] );
  25351. camera.lookAt( _lookTarget );
  25352. camera.updateMatrixWorld();
  25353. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  25354. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  25355. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  25356. }
  25357. }
  25358. class PointLight extends Light {
  25359. constructor( color, intensity, distance = 0, decay = 2 ) {
  25360. super( color, intensity );
  25361. this.isPointLight = true;
  25362. this.type = 'PointLight';
  25363. this.distance = distance;
  25364. this.decay = decay;
  25365. this.shadow = new PointLightShadow();
  25366. }
  25367. get power() {
  25368. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25369. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25370. return this.intensity * 4 * Math.PI;
  25371. }
  25372. set power( power ) {
  25373. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25374. this.intensity = power / ( 4 * Math.PI );
  25375. }
  25376. dispose() {
  25377. this.shadow.dispose();
  25378. }
  25379. copy( source, recursive ) {
  25380. super.copy( source, recursive );
  25381. this.distance = source.distance;
  25382. this.decay = source.decay;
  25383. this.shadow = source.shadow.clone();
  25384. return this;
  25385. }
  25386. }
  25387. class DirectionalLightShadow extends LightShadow {
  25388. constructor() {
  25389. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25390. this.isDirectionalLightShadow = true;
  25391. }
  25392. }
  25393. class DirectionalLight extends Light {
  25394. constructor( color, intensity ) {
  25395. super( color, intensity );
  25396. this.isDirectionalLight = true;
  25397. this.type = 'DirectionalLight';
  25398. this.position.copy( Object3D.DEFAULT_UP );
  25399. this.updateMatrix();
  25400. this.target = new Object3D();
  25401. this.shadow = new DirectionalLightShadow();
  25402. }
  25403. dispose() {
  25404. this.shadow.dispose();
  25405. }
  25406. copy( source ) {
  25407. super.copy( source );
  25408. this.target = source.target.clone();
  25409. this.shadow = source.shadow.clone();
  25410. return this;
  25411. }
  25412. }
  25413. class AmbientLight extends Light {
  25414. constructor( color, intensity ) {
  25415. super( color, intensity );
  25416. this.isAmbientLight = true;
  25417. this.type = 'AmbientLight';
  25418. }
  25419. }
  25420. class RectAreaLight extends Light {
  25421. constructor( color, intensity, width = 10, height = 10 ) {
  25422. super( color, intensity );
  25423. this.isRectAreaLight = true;
  25424. this.type = 'RectAreaLight';
  25425. this.width = width;
  25426. this.height = height;
  25427. }
  25428. get power() {
  25429. // compute the light's luminous power (in lumens) from its intensity (in nits)
  25430. return this.intensity * this.width * this.height * Math.PI;
  25431. }
  25432. set power( power ) {
  25433. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  25434. this.intensity = power / ( this.width * this.height * Math.PI );
  25435. }
  25436. copy( source ) {
  25437. super.copy( source );
  25438. this.width = source.width;
  25439. this.height = source.height;
  25440. return this;
  25441. }
  25442. toJSON( meta ) {
  25443. const data = super.toJSON( meta );
  25444. data.object.width = this.width;
  25445. data.object.height = this.height;
  25446. return data;
  25447. }
  25448. }
  25449. /**
  25450. * Primary reference:
  25451. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25452. *
  25453. * Secondary reference:
  25454. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25455. */
  25456. // 3-band SH defined by 9 coefficients
  25457. class SphericalHarmonics3 {
  25458. constructor() {
  25459. this.isSphericalHarmonics3 = true;
  25460. this.coefficients = [];
  25461. for ( let i = 0; i < 9; i ++ ) {
  25462. this.coefficients.push( new Vector3() );
  25463. }
  25464. }
  25465. set( coefficients ) {
  25466. for ( let i = 0; i < 9; i ++ ) {
  25467. this.coefficients[ i ].copy( coefficients[ i ] );
  25468. }
  25469. return this;
  25470. }
  25471. zero() {
  25472. for ( let i = 0; i < 9; i ++ ) {
  25473. this.coefficients[ i ].set( 0, 0, 0 );
  25474. }
  25475. return this;
  25476. }
  25477. // get the radiance in the direction of the normal
  25478. // target is a Vector3
  25479. getAt( normal, target ) {
  25480. // normal is assumed to be unit length
  25481. const x = normal.x, y = normal.y, z = normal.z;
  25482. const coeff = this.coefficients;
  25483. // band 0
  25484. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25485. // band 1
  25486. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25487. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25488. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25489. // band 2
  25490. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25491. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25492. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25493. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25494. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25495. return target;
  25496. }
  25497. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25498. // target is a Vector3
  25499. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25500. getIrradianceAt( normal, target ) {
  25501. // normal is assumed to be unit length
  25502. const x = normal.x, y = normal.y, z = normal.z;
  25503. const coeff = this.coefficients;
  25504. // band 0
  25505. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25506. // band 1
  25507. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25508. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25509. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25510. // band 2
  25511. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25512. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25513. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25514. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25515. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25516. return target;
  25517. }
  25518. add( sh ) {
  25519. for ( let i = 0; i < 9; i ++ ) {
  25520. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25521. }
  25522. return this;
  25523. }
  25524. addScaledSH( sh, s ) {
  25525. for ( let i = 0; i < 9; i ++ ) {
  25526. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25527. }
  25528. return this;
  25529. }
  25530. scale( s ) {
  25531. for ( let i = 0; i < 9; i ++ ) {
  25532. this.coefficients[ i ].multiplyScalar( s );
  25533. }
  25534. return this;
  25535. }
  25536. lerp( sh, alpha ) {
  25537. for ( let i = 0; i < 9; i ++ ) {
  25538. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25539. }
  25540. return this;
  25541. }
  25542. equals( sh ) {
  25543. for ( let i = 0; i < 9; i ++ ) {
  25544. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25545. return false;
  25546. }
  25547. }
  25548. return true;
  25549. }
  25550. copy( sh ) {
  25551. return this.set( sh.coefficients );
  25552. }
  25553. clone() {
  25554. return new this.constructor().copy( this );
  25555. }
  25556. fromArray( array, offset = 0 ) {
  25557. const coefficients = this.coefficients;
  25558. for ( let i = 0; i < 9; i ++ ) {
  25559. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25560. }
  25561. return this;
  25562. }
  25563. toArray( array = [], offset = 0 ) {
  25564. const coefficients = this.coefficients;
  25565. for ( let i = 0; i < 9; i ++ ) {
  25566. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25567. }
  25568. return array;
  25569. }
  25570. // evaluate the basis functions
  25571. // shBasis is an Array[ 9 ]
  25572. static getBasisAt( normal, shBasis ) {
  25573. // normal is assumed to be unit length
  25574. const x = normal.x, y = normal.y, z = normal.z;
  25575. // band 0
  25576. shBasis[ 0 ] = 0.282095;
  25577. // band 1
  25578. shBasis[ 1 ] = 0.488603 * y;
  25579. shBasis[ 2 ] = 0.488603 * z;
  25580. shBasis[ 3 ] = 0.488603 * x;
  25581. // band 2
  25582. shBasis[ 4 ] = 1.092548 * x * y;
  25583. shBasis[ 5 ] = 1.092548 * y * z;
  25584. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25585. shBasis[ 7 ] = 1.092548 * x * z;
  25586. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25587. }
  25588. }
  25589. class LightProbe extends Light {
  25590. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25591. super( undefined, intensity );
  25592. this.isLightProbe = true;
  25593. this.sh = sh;
  25594. }
  25595. copy( source ) {
  25596. super.copy( source );
  25597. this.sh.copy( source.sh );
  25598. return this;
  25599. }
  25600. fromJSON( json ) {
  25601. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25602. this.sh.fromArray( json.sh );
  25603. return this;
  25604. }
  25605. toJSON( meta ) {
  25606. const data = super.toJSON( meta );
  25607. data.object.sh = this.sh.toArray();
  25608. return data;
  25609. }
  25610. }
  25611. class MaterialLoader extends Loader {
  25612. constructor( manager ) {
  25613. super( manager );
  25614. this.textures = {};
  25615. }
  25616. load( url, onLoad, onProgress, onError ) {
  25617. const scope = this;
  25618. const loader = new FileLoader( scope.manager );
  25619. loader.setPath( scope.path );
  25620. loader.setRequestHeader( scope.requestHeader );
  25621. loader.setWithCredentials( scope.withCredentials );
  25622. loader.load( url, function ( text ) {
  25623. try {
  25624. onLoad( scope.parse( JSON.parse( text ) ) );
  25625. } catch ( e ) {
  25626. if ( onError ) {
  25627. onError( e );
  25628. } else {
  25629. console.error( e );
  25630. }
  25631. scope.manager.itemError( url );
  25632. }
  25633. }, onProgress, onError );
  25634. }
  25635. parse( json ) {
  25636. const textures = this.textures;
  25637. function getTexture( name ) {
  25638. if ( textures[ name ] === undefined ) {
  25639. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25640. }
  25641. return textures[ name ];
  25642. }
  25643. const material = MaterialLoader.createMaterialFromType( json.type );
  25644. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25645. if ( json.name !== undefined ) material.name = json.name;
  25646. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25647. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25648. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25649. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25650. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25651. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25652. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25653. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25654. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25655. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25656. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25657. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25658. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25659. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25660. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25661. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25662. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25663. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25664. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25665. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25666. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  25667. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  25668. if ( json.fog !== undefined ) material.fog = json.fog;
  25669. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25670. if ( json.blending !== undefined ) material.blending = json.blending;
  25671. if ( json.combine !== undefined ) material.combine = json.combine;
  25672. if ( json.side !== undefined ) material.side = json.side;
  25673. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25674. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25675. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25676. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25677. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25678. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25679. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25680. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25681. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25682. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25683. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25684. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25685. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25686. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25687. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25688. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25689. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25690. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25691. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25692. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25693. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25694. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25695. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25696. if ( json.scale !== undefined ) material.scale = json.scale;
  25697. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25698. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25699. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25700. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25701. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25702. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25703. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25704. if ( json.visible !== undefined ) material.visible = json.visible;
  25705. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25706. if ( json.userData !== undefined ) material.userData = json.userData;
  25707. if ( json.vertexColors !== undefined ) {
  25708. if ( typeof json.vertexColors === 'number' ) {
  25709. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25710. } else {
  25711. material.vertexColors = json.vertexColors;
  25712. }
  25713. }
  25714. // Shader Material
  25715. if ( json.uniforms !== undefined ) {
  25716. for ( const name in json.uniforms ) {
  25717. const uniform = json.uniforms[ name ];
  25718. material.uniforms[ name ] = {};
  25719. switch ( uniform.type ) {
  25720. case 't':
  25721. material.uniforms[ name ].value = getTexture( uniform.value );
  25722. break;
  25723. case 'c':
  25724. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25725. break;
  25726. case 'v2':
  25727. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25728. break;
  25729. case 'v3':
  25730. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25731. break;
  25732. case 'v4':
  25733. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25734. break;
  25735. case 'm3':
  25736. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25737. break;
  25738. case 'm4':
  25739. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25740. break;
  25741. default:
  25742. material.uniforms[ name ].value = uniform.value;
  25743. }
  25744. }
  25745. }
  25746. if ( json.defines !== undefined ) material.defines = json.defines;
  25747. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25748. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25749. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25750. if ( json.extensions !== undefined ) {
  25751. for ( const key in json.extensions ) {
  25752. material.extensions[ key ] = json.extensions[ key ];
  25753. }
  25754. }
  25755. if ( json.lights !== undefined ) material.lights = json.lights;
  25756. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  25757. // for PointsMaterial
  25758. if ( json.size !== undefined ) material.size = json.size;
  25759. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25760. // maps
  25761. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25762. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25763. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25764. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25765. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25766. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25767. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25768. if ( json.normalScale !== undefined ) {
  25769. let normalScale = json.normalScale;
  25770. if ( Array.isArray( normalScale ) === false ) {
  25771. // Blender exporter used to export a scalar. See #7459
  25772. normalScale = [ normalScale, normalScale ];
  25773. }
  25774. material.normalScale = new Vector2().fromArray( normalScale );
  25775. }
  25776. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25777. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25778. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25779. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25780. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25781. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25782. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25783. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25784. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25785. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25786. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25787. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25788. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25789. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25790. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25791. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25792. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25793. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25794. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25795. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25796. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25797. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25798. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25799. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25800. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25801. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25802. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25803. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  25804. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25805. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25806. return material;
  25807. }
  25808. setTextures( value ) {
  25809. this.textures = value;
  25810. return this;
  25811. }
  25812. static createMaterialFromType( type ) {
  25813. const materialLib = {
  25814. ShadowMaterial,
  25815. SpriteMaterial,
  25816. RawShaderMaterial,
  25817. ShaderMaterial,
  25818. PointsMaterial,
  25819. MeshPhysicalMaterial,
  25820. MeshStandardMaterial,
  25821. MeshPhongMaterial,
  25822. MeshToonMaterial,
  25823. MeshNormalMaterial,
  25824. MeshLambertMaterial,
  25825. MeshDepthMaterial,
  25826. MeshDistanceMaterial,
  25827. MeshBasicMaterial,
  25828. MeshMatcapMaterial,
  25829. LineDashedMaterial,
  25830. LineBasicMaterial,
  25831. Material
  25832. };
  25833. return new materialLib[ type ]();
  25834. }
  25835. }
  25836. class LoaderUtils {
  25837. static decodeText( array ) {
  25838. if ( typeof TextDecoder !== 'undefined' ) {
  25839. return new TextDecoder().decode( array );
  25840. }
  25841. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25842. // throws a "maximum call stack size exceeded" error for large arrays.
  25843. let s = '';
  25844. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25845. // Implicitly assumes little-endian.
  25846. s += String.fromCharCode( array[ i ] );
  25847. }
  25848. try {
  25849. // merges multi-byte utf-8 characters.
  25850. return decodeURIComponent( escape( s ) );
  25851. } catch ( e ) { // see #16358
  25852. return s;
  25853. }
  25854. }
  25855. static extractUrlBase( url ) {
  25856. const index = url.lastIndexOf( '/' );
  25857. if ( index === - 1 ) return './';
  25858. return url.slice( 0, index + 1 );
  25859. }
  25860. static resolveURL( url, path ) {
  25861. // Invalid URL
  25862. if ( typeof url !== 'string' || url === '' ) return '';
  25863. // Host Relative URL
  25864. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25865. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25866. }
  25867. // Absolute URL http://,https://,//
  25868. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25869. // Data URI
  25870. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25871. // Blob URL
  25872. if ( /^blob:.*$/i.test( url ) ) return url;
  25873. // Relative URL
  25874. return path + url;
  25875. }
  25876. }
  25877. class InstancedBufferGeometry extends BufferGeometry {
  25878. constructor() {
  25879. super();
  25880. this.isInstancedBufferGeometry = true;
  25881. this.type = 'InstancedBufferGeometry';
  25882. this.instanceCount = Infinity;
  25883. }
  25884. copy( source ) {
  25885. super.copy( source );
  25886. this.instanceCount = source.instanceCount;
  25887. return this;
  25888. }
  25889. toJSON() {
  25890. const data = super.toJSON();
  25891. data.instanceCount = this.instanceCount;
  25892. data.isInstancedBufferGeometry = true;
  25893. return data;
  25894. }
  25895. }
  25896. class BufferGeometryLoader extends Loader {
  25897. constructor( manager ) {
  25898. super( manager );
  25899. }
  25900. load( url, onLoad, onProgress, onError ) {
  25901. const scope = this;
  25902. const loader = new FileLoader( scope.manager );
  25903. loader.setPath( scope.path );
  25904. loader.setRequestHeader( scope.requestHeader );
  25905. loader.setWithCredentials( scope.withCredentials );
  25906. loader.load( url, function ( text ) {
  25907. try {
  25908. onLoad( scope.parse( JSON.parse( text ) ) );
  25909. } catch ( e ) {
  25910. if ( onError ) {
  25911. onError( e );
  25912. } else {
  25913. console.error( e );
  25914. }
  25915. scope.manager.itemError( url );
  25916. }
  25917. }, onProgress, onError );
  25918. }
  25919. parse( json ) {
  25920. const interleavedBufferMap = {};
  25921. const arrayBufferMap = {};
  25922. function getInterleavedBuffer( json, uuid ) {
  25923. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25924. const interleavedBuffers = json.interleavedBuffers;
  25925. const interleavedBuffer = interleavedBuffers[ uuid ];
  25926. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25927. const array = getTypedArray( interleavedBuffer.type, buffer );
  25928. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25929. ib.uuid = interleavedBuffer.uuid;
  25930. interleavedBufferMap[ uuid ] = ib;
  25931. return ib;
  25932. }
  25933. function getArrayBuffer( json, uuid ) {
  25934. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25935. const arrayBuffers = json.arrayBuffers;
  25936. const arrayBuffer = arrayBuffers[ uuid ];
  25937. const ab = new Uint32Array( arrayBuffer ).buffer;
  25938. arrayBufferMap[ uuid ] = ab;
  25939. return ab;
  25940. }
  25941. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25942. const index = json.data.index;
  25943. if ( index !== undefined ) {
  25944. const typedArray = getTypedArray( index.type, index.array );
  25945. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25946. }
  25947. const attributes = json.data.attributes;
  25948. for ( const key in attributes ) {
  25949. const attribute = attributes[ key ];
  25950. let bufferAttribute;
  25951. if ( attribute.isInterleavedBufferAttribute ) {
  25952. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25953. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25954. } else {
  25955. const typedArray = getTypedArray( attribute.type, attribute.array );
  25956. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25957. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25958. }
  25959. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25960. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25961. if ( attribute.updateRange !== undefined ) {
  25962. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25963. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25964. }
  25965. geometry.setAttribute( key, bufferAttribute );
  25966. }
  25967. const morphAttributes = json.data.morphAttributes;
  25968. if ( morphAttributes ) {
  25969. for ( const key in morphAttributes ) {
  25970. const attributeArray = morphAttributes[ key ];
  25971. const array = [];
  25972. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25973. const attribute = attributeArray[ i ];
  25974. let bufferAttribute;
  25975. if ( attribute.isInterleavedBufferAttribute ) {
  25976. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25977. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25978. } else {
  25979. const typedArray = getTypedArray( attribute.type, attribute.array );
  25980. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25981. }
  25982. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25983. array.push( bufferAttribute );
  25984. }
  25985. geometry.morphAttributes[ key ] = array;
  25986. }
  25987. }
  25988. const morphTargetsRelative = json.data.morphTargetsRelative;
  25989. if ( morphTargetsRelative ) {
  25990. geometry.morphTargetsRelative = true;
  25991. }
  25992. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25993. if ( groups !== undefined ) {
  25994. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25995. const group = groups[ i ];
  25996. geometry.addGroup( group.start, group.count, group.materialIndex );
  25997. }
  25998. }
  25999. const boundingSphere = json.data.boundingSphere;
  26000. if ( boundingSphere !== undefined ) {
  26001. const center = new Vector3();
  26002. if ( boundingSphere.center !== undefined ) {
  26003. center.fromArray( boundingSphere.center );
  26004. }
  26005. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  26006. }
  26007. if ( json.name ) geometry.name = json.name;
  26008. if ( json.userData ) geometry.userData = json.userData;
  26009. return geometry;
  26010. }
  26011. }
  26012. class ObjectLoader extends Loader {
  26013. constructor( manager ) {
  26014. super( manager );
  26015. }
  26016. load( url, onLoad, onProgress, onError ) {
  26017. const scope = this;
  26018. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26019. this.resourcePath = this.resourcePath || path;
  26020. const loader = new FileLoader( this.manager );
  26021. loader.setPath( this.path );
  26022. loader.setRequestHeader( this.requestHeader );
  26023. loader.setWithCredentials( this.withCredentials );
  26024. loader.load( url, function ( text ) {
  26025. let json = null;
  26026. try {
  26027. json = JSON.parse( text );
  26028. } catch ( error ) {
  26029. if ( onError !== undefined ) onError( error );
  26030. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26031. return;
  26032. }
  26033. const metadata = json.metadata;
  26034. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26035. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  26036. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26037. return;
  26038. }
  26039. scope.parse( json, onLoad );
  26040. }, onProgress, onError );
  26041. }
  26042. async loadAsync( url, onProgress ) {
  26043. const scope = this;
  26044. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26045. this.resourcePath = this.resourcePath || path;
  26046. const loader = new FileLoader( this.manager );
  26047. loader.setPath( this.path );
  26048. loader.setRequestHeader( this.requestHeader );
  26049. loader.setWithCredentials( this.withCredentials );
  26050. const text = await loader.loadAsync( url, onProgress );
  26051. const json = JSON.parse( text );
  26052. const metadata = json.metadata;
  26053. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26054. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26055. }
  26056. return await scope.parseAsync( json );
  26057. }
  26058. parse( json, onLoad ) {
  26059. const animations = this.parseAnimations( json.animations );
  26060. const shapes = this.parseShapes( json.shapes );
  26061. const geometries = this.parseGeometries( json.geometries, shapes );
  26062. const images = this.parseImages( json.images, function () {
  26063. if ( onLoad !== undefined ) onLoad( object );
  26064. } );
  26065. const textures = this.parseTextures( json.textures, images );
  26066. const materials = this.parseMaterials( json.materials, textures );
  26067. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  26068. const skeletons = this.parseSkeletons( json.skeletons, object );
  26069. this.bindSkeletons( object, skeletons );
  26070. //
  26071. if ( onLoad !== undefined ) {
  26072. let hasImages = false;
  26073. for ( const uuid in images ) {
  26074. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  26075. hasImages = true;
  26076. break;
  26077. }
  26078. }
  26079. if ( hasImages === false ) onLoad( object );
  26080. }
  26081. return object;
  26082. }
  26083. async parseAsync( json ) {
  26084. const animations = this.parseAnimations( json.animations );
  26085. const shapes = this.parseShapes( json.shapes );
  26086. const geometries = this.parseGeometries( json.geometries, shapes );
  26087. const images = await this.parseImagesAsync( json.images );
  26088. const textures = this.parseTextures( json.textures, images );
  26089. const materials = this.parseMaterials( json.materials, textures );
  26090. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  26091. const skeletons = this.parseSkeletons( json.skeletons, object );
  26092. this.bindSkeletons( object, skeletons );
  26093. return object;
  26094. }
  26095. parseShapes( json ) {
  26096. const shapes = {};
  26097. if ( json !== undefined ) {
  26098. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26099. const shape = new Shape().fromJSON( json[ i ] );
  26100. shapes[ shape.uuid ] = shape;
  26101. }
  26102. }
  26103. return shapes;
  26104. }
  26105. parseSkeletons( json, object ) {
  26106. const skeletons = {};
  26107. const bones = {};
  26108. // generate bone lookup table
  26109. object.traverse( function ( child ) {
  26110. if ( child.isBone ) bones[ child.uuid ] = child;
  26111. } );
  26112. // create skeletons
  26113. if ( json !== undefined ) {
  26114. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26115. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  26116. skeletons[ skeleton.uuid ] = skeleton;
  26117. }
  26118. }
  26119. return skeletons;
  26120. }
  26121. parseGeometries( json, shapes ) {
  26122. const geometries = {};
  26123. if ( json !== undefined ) {
  26124. const bufferGeometryLoader = new BufferGeometryLoader();
  26125. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26126. let geometry;
  26127. const data = json[ i ];
  26128. switch ( data.type ) {
  26129. case 'BufferGeometry':
  26130. case 'InstancedBufferGeometry':
  26131. geometry = bufferGeometryLoader.parse( data );
  26132. break;
  26133. default:
  26134. if ( data.type in Geometries ) {
  26135. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  26136. } else {
  26137. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  26138. }
  26139. }
  26140. geometry.uuid = data.uuid;
  26141. if ( data.name !== undefined ) geometry.name = data.name;
  26142. if ( data.userData !== undefined ) geometry.userData = data.userData;
  26143. geometries[ data.uuid ] = geometry;
  26144. }
  26145. }
  26146. return geometries;
  26147. }
  26148. parseMaterials( json, textures ) {
  26149. const cache = {}; // MultiMaterial
  26150. const materials = {};
  26151. if ( json !== undefined ) {
  26152. const loader = new MaterialLoader();
  26153. loader.setTextures( textures );
  26154. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26155. const data = json[ i ];
  26156. if ( cache[ data.uuid ] === undefined ) {
  26157. cache[ data.uuid ] = loader.parse( data );
  26158. }
  26159. materials[ data.uuid ] = cache[ data.uuid ];
  26160. }
  26161. }
  26162. return materials;
  26163. }
  26164. parseAnimations( json ) {
  26165. const animations = {};
  26166. if ( json !== undefined ) {
  26167. for ( let i = 0; i < json.length; i ++ ) {
  26168. const data = json[ i ];
  26169. const clip = AnimationClip.parse( data );
  26170. animations[ clip.uuid ] = clip;
  26171. }
  26172. }
  26173. return animations;
  26174. }
  26175. parseImages( json, onLoad ) {
  26176. const scope = this;
  26177. const images = {};
  26178. let loader;
  26179. function loadImage( url ) {
  26180. scope.manager.itemStart( url );
  26181. return loader.load( url, function () {
  26182. scope.manager.itemEnd( url );
  26183. }, undefined, function () {
  26184. scope.manager.itemError( url );
  26185. scope.manager.itemEnd( url );
  26186. } );
  26187. }
  26188. function deserializeImage( image ) {
  26189. if ( typeof image === 'string' ) {
  26190. const url = image;
  26191. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  26192. return loadImage( path );
  26193. } else {
  26194. if ( image.data ) {
  26195. return {
  26196. data: getTypedArray( image.type, image.data ),
  26197. width: image.width,
  26198. height: image.height
  26199. };
  26200. } else {
  26201. return null;
  26202. }
  26203. }
  26204. }
  26205. if ( json !== undefined && json.length > 0 ) {
  26206. const manager = new LoadingManager( onLoad );
  26207. loader = new ImageLoader( manager );
  26208. loader.setCrossOrigin( this.crossOrigin );
  26209. for ( let i = 0, il = json.length; i < il; i ++ ) {
  26210. const image = json[ i ];
  26211. const url = image.url;
  26212. if ( Array.isArray( url ) ) {
  26213. // load array of images e.g CubeTexture
  26214. const imageArray = [];
  26215. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  26216. const currentUrl = url[ j ];
  26217. const deserializedImage = deserializeImage( currentUrl );
  26218. if ( deserializedImage !== null ) {
  26219. if ( deserializedImage instanceof HTMLImageElement ) {
  26220. imageArray.push( deserializedImage );
  26221. } else {
  26222. // special case: handle array of data textures for cube textures
  26223. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  26224. }
  26225. }
  26226. }
  26227. images[ image.uuid ] = new Source( imageArray );
  26228. } else {
  26229. // load single image
  26230. const deserializedImage = deserializeImage( image.url );
  26231. images[ image.uuid ] = new Source( deserializedImage );
  26232. }
  26233. }
  26234. }
  26235. return images;
  26236. }
  26237. async parseImagesAsync( json ) {
  26238. const scope = this;
  26239. const images = {};
  26240. let loader;
  26241. async function deserializeImage( image ) {
  26242. if ( typeof image === 'string' ) {
  26243. const url = image;
  26244. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  26245. return await loader.loadAsync( path );
  26246. } else {
  26247. if ( image.data ) {
  26248. return {
  26249. data: getTypedArray( image.type, image.data ),
  26250. width: image.width,
  26251. height: image.height
  26252. };
  26253. } else {
  26254. return null;
  26255. }
  26256. }
  26257. }
  26258. if ( json !== undefined && json.length > 0 ) {
  26259. loader = new ImageLoader( this.manager );
  26260. loader.setCrossOrigin( this.crossOrigin );
  26261. for ( let i = 0, il = json.length; i < il; i ++ ) {
  26262. const image = json[ i ];
  26263. const url = image.url;
  26264. if ( Array.isArray( url ) ) {
  26265. // load array of images e.g CubeTexture
  26266. const imageArray = [];
  26267. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  26268. const currentUrl = url[ j ];
  26269. const deserializedImage = await deserializeImage( currentUrl );
  26270. if ( deserializedImage !== null ) {
  26271. if ( deserializedImage instanceof HTMLImageElement ) {
  26272. imageArray.push( deserializedImage );
  26273. } else {
  26274. // special case: handle array of data textures for cube textures
  26275. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  26276. }
  26277. }
  26278. }
  26279. images[ image.uuid ] = new Source( imageArray );
  26280. } else {
  26281. // load single image
  26282. const deserializedImage = await deserializeImage( image.url );
  26283. images[ image.uuid ] = new Source( deserializedImage );
  26284. }
  26285. }
  26286. }
  26287. return images;
  26288. }
  26289. parseTextures( json, images ) {
  26290. function parseConstant( value, type ) {
  26291. if ( typeof value === 'number' ) return value;
  26292. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  26293. return type[ value ];
  26294. }
  26295. const textures = {};
  26296. if ( json !== undefined ) {
  26297. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26298. const data = json[ i ];
  26299. if ( data.image === undefined ) {
  26300. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  26301. }
  26302. if ( images[ data.image ] === undefined ) {
  26303. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  26304. }
  26305. const source = images[ data.image ];
  26306. const image = source.data;
  26307. let texture;
  26308. if ( Array.isArray( image ) ) {
  26309. texture = new CubeTexture();
  26310. if ( image.length === 6 ) texture.needsUpdate = true;
  26311. } else {
  26312. if ( image && image.data ) {
  26313. texture = new DataTexture();
  26314. } else {
  26315. texture = new Texture();
  26316. }
  26317. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  26318. }
  26319. texture.source = source;
  26320. texture.uuid = data.uuid;
  26321. if ( data.name !== undefined ) texture.name = data.name;
  26322. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  26323. if ( data.channel !== undefined ) texture.channel = data.channel;
  26324. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  26325. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  26326. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  26327. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  26328. if ( data.wrap !== undefined ) {
  26329. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  26330. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  26331. }
  26332. if ( data.format !== undefined ) texture.format = data.format;
  26333. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  26334. if ( data.type !== undefined ) texture.type = data.type;
  26335. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  26336. if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152
  26337. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  26338. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  26339. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  26340. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  26341. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  26342. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  26343. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  26344. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  26345. if ( data.userData !== undefined ) texture.userData = data.userData;
  26346. textures[ data.uuid ] = texture;
  26347. }
  26348. }
  26349. return textures;
  26350. }
  26351. parseObject( data, geometries, materials, textures, animations ) {
  26352. let object;
  26353. function getGeometry( name ) {
  26354. if ( geometries[ name ] === undefined ) {
  26355. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  26356. }
  26357. return geometries[ name ];
  26358. }
  26359. function getMaterial( name ) {
  26360. if ( name === undefined ) return undefined;
  26361. if ( Array.isArray( name ) ) {
  26362. const array = [];
  26363. for ( let i = 0, l = name.length; i < l; i ++ ) {
  26364. const uuid = name[ i ];
  26365. if ( materials[ uuid ] === undefined ) {
  26366. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  26367. }
  26368. array.push( materials[ uuid ] );
  26369. }
  26370. return array;
  26371. }
  26372. if ( materials[ name ] === undefined ) {
  26373. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26374. }
  26375. return materials[ name ];
  26376. }
  26377. function getTexture( uuid ) {
  26378. if ( textures[ uuid ] === undefined ) {
  26379. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  26380. }
  26381. return textures[ uuid ];
  26382. }
  26383. let geometry, material;
  26384. switch ( data.type ) {
  26385. case 'Scene':
  26386. object = new Scene();
  26387. if ( data.background !== undefined ) {
  26388. if ( Number.isInteger( data.background ) ) {
  26389. object.background = new Color( data.background );
  26390. } else {
  26391. object.background = getTexture( data.background );
  26392. }
  26393. }
  26394. if ( data.environment !== undefined ) {
  26395. object.environment = getTexture( data.environment );
  26396. }
  26397. if ( data.fog !== undefined ) {
  26398. if ( data.fog.type === 'Fog' ) {
  26399. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26400. } else if ( data.fog.type === 'FogExp2' ) {
  26401. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26402. }
  26403. }
  26404. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  26405. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  26406. break;
  26407. case 'PerspectiveCamera':
  26408. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26409. if ( data.focus !== undefined ) object.focus = data.focus;
  26410. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26411. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26412. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26413. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26414. break;
  26415. case 'OrthographicCamera':
  26416. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26417. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26418. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26419. break;
  26420. case 'AmbientLight':
  26421. object = new AmbientLight( data.color, data.intensity );
  26422. break;
  26423. case 'DirectionalLight':
  26424. object = new DirectionalLight( data.color, data.intensity );
  26425. break;
  26426. case 'PointLight':
  26427. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26428. break;
  26429. case 'RectAreaLight':
  26430. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26431. break;
  26432. case 'SpotLight':
  26433. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26434. break;
  26435. case 'HemisphereLight':
  26436. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26437. break;
  26438. case 'LightProbe':
  26439. object = new LightProbe().fromJSON( data );
  26440. break;
  26441. case 'SkinnedMesh':
  26442. geometry = getGeometry( data.geometry );
  26443. material = getMaterial( data.material );
  26444. object = new SkinnedMesh( geometry, material );
  26445. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  26446. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  26447. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  26448. break;
  26449. case 'Mesh':
  26450. geometry = getGeometry( data.geometry );
  26451. material = getMaterial( data.material );
  26452. object = new Mesh( geometry, material );
  26453. break;
  26454. case 'InstancedMesh':
  26455. geometry = getGeometry( data.geometry );
  26456. material = getMaterial( data.material );
  26457. const count = data.count;
  26458. const instanceMatrix = data.instanceMatrix;
  26459. const instanceColor = data.instanceColor;
  26460. object = new InstancedMesh( geometry, material, count );
  26461. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  26462. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  26463. break;
  26464. case 'LOD':
  26465. object = new LOD();
  26466. break;
  26467. case 'Line':
  26468. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  26469. break;
  26470. case 'LineLoop':
  26471. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26472. break;
  26473. case 'LineSegments':
  26474. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26475. break;
  26476. case 'PointCloud':
  26477. case 'Points':
  26478. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26479. break;
  26480. case 'Sprite':
  26481. object = new Sprite( getMaterial( data.material ) );
  26482. break;
  26483. case 'Group':
  26484. object = new Group();
  26485. break;
  26486. case 'Bone':
  26487. object = new Bone();
  26488. break;
  26489. default:
  26490. object = new Object3D();
  26491. }
  26492. object.uuid = data.uuid;
  26493. if ( data.name !== undefined ) object.name = data.name;
  26494. if ( data.matrix !== undefined ) {
  26495. object.matrix.fromArray( data.matrix );
  26496. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26497. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26498. } else {
  26499. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26500. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26501. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26502. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26503. }
  26504. if ( data.up !== undefined ) object.up.fromArray( data.up );
  26505. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26506. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26507. if ( data.shadow ) {
  26508. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26509. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26510. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26511. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26512. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26513. }
  26514. if ( data.visible !== undefined ) object.visible = data.visible;
  26515. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26516. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26517. if ( data.userData !== undefined ) object.userData = data.userData;
  26518. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26519. if ( data.children !== undefined ) {
  26520. const children = data.children;
  26521. for ( let i = 0; i < children.length; i ++ ) {
  26522. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26523. }
  26524. }
  26525. if ( data.animations !== undefined ) {
  26526. const objectAnimations = data.animations;
  26527. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26528. const uuid = objectAnimations[ i ];
  26529. object.animations.push( animations[ uuid ] );
  26530. }
  26531. }
  26532. if ( data.type === 'LOD' ) {
  26533. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26534. const levels = data.levels;
  26535. for ( let l = 0; l < levels.length; l ++ ) {
  26536. const level = levels[ l ];
  26537. const child = object.getObjectByProperty( 'uuid', level.object );
  26538. if ( child !== undefined ) {
  26539. object.addLevel( child, level.distance, level.hysteresis );
  26540. }
  26541. }
  26542. }
  26543. return object;
  26544. }
  26545. bindSkeletons( object, skeletons ) {
  26546. if ( Object.keys( skeletons ).length === 0 ) return;
  26547. object.traverse( function ( child ) {
  26548. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26549. const skeleton = skeletons[ child.skeleton ];
  26550. if ( skeleton === undefined ) {
  26551. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26552. } else {
  26553. child.bind( skeleton, child.bindMatrix );
  26554. }
  26555. }
  26556. } );
  26557. }
  26558. }
  26559. const TEXTURE_MAPPING = {
  26560. UVMapping: UVMapping,
  26561. CubeReflectionMapping: CubeReflectionMapping,
  26562. CubeRefractionMapping: CubeRefractionMapping,
  26563. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26564. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26565. CubeUVReflectionMapping: CubeUVReflectionMapping
  26566. };
  26567. const TEXTURE_WRAPPING = {
  26568. RepeatWrapping: RepeatWrapping,
  26569. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26570. MirroredRepeatWrapping: MirroredRepeatWrapping
  26571. };
  26572. const TEXTURE_FILTER = {
  26573. NearestFilter: NearestFilter,
  26574. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26575. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26576. LinearFilter: LinearFilter,
  26577. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26578. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26579. };
  26580. class ImageBitmapLoader extends Loader {
  26581. constructor( manager ) {
  26582. super( manager );
  26583. this.isImageBitmapLoader = true;
  26584. if ( typeof createImageBitmap === 'undefined' ) {
  26585. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26586. }
  26587. if ( typeof fetch === 'undefined' ) {
  26588. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26589. }
  26590. this.options = { premultiplyAlpha: 'none' };
  26591. }
  26592. setOptions( options ) {
  26593. this.options = options;
  26594. return this;
  26595. }
  26596. load( url, onLoad, onProgress, onError ) {
  26597. if ( url === undefined ) url = '';
  26598. if ( this.path !== undefined ) url = this.path + url;
  26599. url = this.manager.resolveURL( url );
  26600. const scope = this;
  26601. const cached = Cache.get( url );
  26602. if ( cached !== undefined ) {
  26603. scope.manager.itemStart( url );
  26604. setTimeout( function () {
  26605. if ( onLoad ) onLoad( cached );
  26606. scope.manager.itemEnd( url );
  26607. }, 0 );
  26608. return cached;
  26609. }
  26610. const fetchOptions = {};
  26611. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26612. fetchOptions.headers = this.requestHeader;
  26613. fetch( url, fetchOptions ).then( function ( res ) {
  26614. return res.blob();
  26615. } ).then( function ( blob ) {
  26616. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26617. } ).then( function ( imageBitmap ) {
  26618. Cache.add( url, imageBitmap );
  26619. if ( onLoad ) onLoad( imageBitmap );
  26620. scope.manager.itemEnd( url );
  26621. } ).catch( function ( e ) {
  26622. if ( onError ) onError( e );
  26623. scope.manager.itemError( url );
  26624. scope.manager.itemEnd( url );
  26625. } );
  26626. scope.manager.itemStart( url );
  26627. }
  26628. }
  26629. let _context;
  26630. class AudioContext {
  26631. static getContext() {
  26632. if ( _context === undefined ) {
  26633. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26634. }
  26635. return _context;
  26636. }
  26637. static setContext( value ) {
  26638. _context = value;
  26639. }
  26640. }
  26641. class AudioLoader extends Loader {
  26642. constructor( manager ) {
  26643. super( manager );
  26644. }
  26645. load( url, onLoad, onProgress, onError ) {
  26646. const scope = this;
  26647. const loader = new FileLoader( this.manager );
  26648. loader.setResponseType( 'arraybuffer' );
  26649. loader.setPath( this.path );
  26650. loader.setRequestHeader( this.requestHeader );
  26651. loader.setWithCredentials( this.withCredentials );
  26652. loader.load( url, function ( buffer ) {
  26653. try {
  26654. // Create a copy of the buffer. The `decodeAudioData` method
  26655. // detaches the buffer when complete, preventing reuse.
  26656. const bufferCopy = buffer.slice( 0 );
  26657. const context = AudioContext.getContext();
  26658. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26659. onLoad( audioBuffer );
  26660. }, handleError );
  26661. } catch ( e ) {
  26662. handleError( e );
  26663. }
  26664. }, onProgress, onError );
  26665. function handleError( e ) {
  26666. if ( onError ) {
  26667. onError( e );
  26668. } else {
  26669. console.error( e );
  26670. }
  26671. scope.manager.itemError( url );
  26672. }
  26673. }
  26674. }
  26675. class HemisphereLightProbe extends LightProbe {
  26676. constructor( skyColor, groundColor, intensity = 1 ) {
  26677. super( undefined, intensity );
  26678. this.isHemisphereLightProbe = true;
  26679. const color1 = new Color().set( skyColor );
  26680. const color2 = new Color().set( groundColor );
  26681. const sky = new Vector3( color1.r, color1.g, color1.b );
  26682. const ground = new Vector3( color2.r, color2.g, color2.b );
  26683. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26684. const c0 = Math.sqrt( Math.PI );
  26685. const c1 = c0 * Math.sqrt( 0.75 );
  26686. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26687. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26688. }
  26689. }
  26690. class AmbientLightProbe extends LightProbe {
  26691. constructor( color, intensity = 1 ) {
  26692. super( undefined, intensity );
  26693. this.isAmbientLightProbe = true;
  26694. const color1 = new Color().set( color );
  26695. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26696. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26697. }
  26698. }
  26699. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26700. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26701. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26702. class StereoCamera {
  26703. constructor() {
  26704. this.type = 'StereoCamera';
  26705. this.aspect = 1;
  26706. this.eyeSep = 0.064;
  26707. this.cameraL = new PerspectiveCamera();
  26708. this.cameraL.layers.enable( 1 );
  26709. this.cameraL.matrixAutoUpdate = false;
  26710. this.cameraR = new PerspectiveCamera();
  26711. this.cameraR.layers.enable( 2 );
  26712. this.cameraR.matrixAutoUpdate = false;
  26713. this._cache = {
  26714. focus: null,
  26715. fov: null,
  26716. aspect: null,
  26717. near: null,
  26718. far: null,
  26719. zoom: null,
  26720. eyeSep: null
  26721. };
  26722. }
  26723. update( camera ) {
  26724. const cache = this._cache;
  26725. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26726. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26727. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26728. if ( needsUpdate ) {
  26729. cache.focus = camera.focus;
  26730. cache.fov = camera.fov;
  26731. cache.aspect = camera.aspect * this.aspect;
  26732. cache.near = camera.near;
  26733. cache.far = camera.far;
  26734. cache.zoom = camera.zoom;
  26735. cache.eyeSep = this.eyeSep;
  26736. // Off-axis stereoscopic effect based on
  26737. // http://paulbourke.net/stereographics/stereorender/
  26738. _projectionMatrix.copy( camera.projectionMatrix );
  26739. const eyeSepHalf = cache.eyeSep / 2;
  26740. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26741. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26742. let xmin, xmax;
  26743. // translate xOffset
  26744. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26745. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26746. // for left eye
  26747. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26748. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26749. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26750. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26751. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26752. // for right eye
  26753. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26754. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26755. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26756. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26757. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26758. }
  26759. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26760. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26761. }
  26762. }
  26763. class Clock {
  26764. constructor( autoStart = true ) {
  26765. this.autoStart = autoStart;
  26766. this.startTime = 0;
  26767. this.oldTime = 0;
  26768. this.elapsedTime = 0;
  26769. this.running = false;
  26770. }
  26771. start() {
  26772. this.startTime = now();
  26773. this.oldTime = this.startTime;
  26774. this.elapsedTime = 0;
  26775. this.running = true;
  26776. }
  26777. stop() {
  26778. this.getElapsedTime();
  26779. this.running = false;
  26780. this.autoStart = false;
  26781. }
  26782. getElapsedTime() {
  26783. this.getDelta();
  26784. return this.elapsedTime;
  26785. }
  26786. getDelta() {
  26787. let diff = 0;
  26788. if ( this.autoStart && ! this.running ) {
  26789. this.start();
  26790. return 0;
  26791. }
  26792. if ( this.running ) {
  26793. const newTime = now();
  26794. diff = ( newTime - this.oldTime ) / 1000;
  26795. this.oldTime = newTime;
  26796. this.elapsedTime += diff;
  26797. }
  26798. return diff;
  26799. }
  26800. }
  26801. function now() {
  26802. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26803. }
  26804. const _position$1 = /*@__PURE__*/ new Vector3();
  26805. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26806. const _scale$1 = /*@__PURE__*/ new Vector3();
  26807. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26808. class AudioListener extends Object3D {
  26809. constructor() {
  26810. super();
  26811. this.type = 'AudioListener';
  26812. this.context = AudioContext.getContext();
  26813. this.gain = this.context.createGain();
  26814. this.gain.connect( this.context.destination );
  26815. this.filter = null;
  26816. this.timeDelta = 0;
  26817. // private
  26818. this._clock = new Clock();
  26819. }
  26820. getInput() {
  26821. return this.gain;
  26822. }
  26823. removeFilter() {
  26824. if ( this.filter !== null ) {
  26825. this.gain.disconnect( this.filter );
  26826. this.filter.disconnect( this.context.destination );
  26827. this.gain.connect( this.context.destination );
  26828. this.filter = null;
  26829. }
  26830. return this;
  26831. }
  26832. getFilter() {
  26833. return this.filter;
  26834. }
  26835. setFilter( value ) {
  26836. if ( this.filter !== null ) {
  26837. this.gain.disconnect( this.filter );
  26838. this.filter.disconnect( this.context.destination );
  26839. } else {
  26840. this.gain.disconnect( this.context.destination );
  26841. }
  26842. this.filter = value;
  26843. this.gain.connect( this.filter );
  26844. this.filter.connect( this.context.destination );
  26845. return this;
  26846. }
  26847. getMasterVolume() {
  26848. return this.gain.gain.value;
  26849. }
  26850. setMasterVolume( value ) {
  26851. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26852. return this;
  26853. }
  26854. updateMatrixWorld( force ) {
  26855. super.updateMatrixWorld( force );
  26856. const listener = this.context.listener;
  26857. const up = this.up;
  26858. this.timeDelta = this._clock.getDelta();
  26859. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26860. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26861. if ( listener.positionX ) {
  26862. // code path for Chrome (see #14393)
  26863. const endTime = this.context.currentTime + this.timeDelta;
  26864. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26865. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26866. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26867. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26868. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26869. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26870. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26871. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26872. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26873. } else {
  26874. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26875. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26876. }
  26877. }
  26878. }
  26879. class Audio extends Object3D {
  26880. constructor( listener ) {
  26881. super();
  26882. this.type = 'Audio';
  26883. this.listener = listener;
  26884. this.context = listener.context;
  26885. this.gain = this.context.createGain();
  26886. this.gain.connect( listener.getInput() );
  26887. this.autoplay = false;
  26888. this.buffer = null;
  26889. this.detune = 0;
  26890. this.loop = false;
  26891. this.loopStart = 0;
  26892. this.loopEnd = 0;
  26893. this.offset = 0;
  26894. this.duration = undefined;
  26895. this.playbackRate = 1;
  26896. this.isPlaying = false;
  26897. this.hasPlaybackControl = true;
  26898. this.source = null;
  26899. this.sourceType = 'empty';
  26900. this._startedAt = 0;
  26901. this._progress = 0;
  26902. this._connected = false;
  26903. this.filters = [];
  26904. }
  26905. getOutput() {
  26906. return this.gain;
  26907. }
  26908. setNodeSource( audioNode ) {
  26909. this.hasPlaybackControl = false;
  26910. this.sourceType = 'audioNode';
  26911. this.source = audioNode;
  26912. this.connect();
  26913. return this;
  26914. }
  26915. setMediaElementSource( mediaElement ) {
  26916. this.hasPlaybackControl = false;
  26917. this.sourceType = 'mediaNode';
  26918. this.source = this.context.createMediaElementSource( mediaElement );
  26919. this.connect();
  26920. return this;
  26921. }
  26922. setMediaStreamSource( mediaStream ) {
  26923. this.hasPlaybackControl = false;
  26924. this.sourceType = 'mediaStreamNode';
  26925. this.source = this.context.createMediaStreamSource( mediaStream );
  26926. this.connect();
  26927. return this;
  26928. }
  26929. setBuffer( audioBuffer ) {
  26930. this.buffer = audioBuffer;
  26931. this.sourceType = 'buffer';
  26932. if ( this.autoplay ) this.play();
  26933. return this;
  26934. }
  26935. play( delay = 0 ) {
  26936. if ( this.isPlaying === true ) {
  26937. console.warn( 'THREE.Audio: Audio is already playing.' );
  26938. return;
  26939. }
  26940. if ( this.hasPlaybackControl === false ) {
  26941. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26942. return;
  26943. }
  26944. this._startedAt = this.context.currentTime + delay;
  26945. const source = this.context.createBufferSource();
  26946. source.buffer = this.buffer;
  26947. source.loop = this.loop;
  26948. source.loopStart = this.loopStart;
  26949. source.loopEnd = this.loopEnd;
  26950. source.onended = this.onEnded.bind( this );
  26951. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26952. this.isPlaying = true;
  26953. this.source = source;
  26954. this.setDetune( this.detune );
  26955. this.setPlaybackRate( this.playbackRate );
  26956. return this.connect();
  26957. }
  26958. pause() {
  26959. if ( this.hasPlaybackControl === false ) {
  26960. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26961. return;
  26962. }
  26963. if ( this.isPlaying === true ) {
  26964. // update current progress
  26965. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26966. if ( this.loop === true ) {
  26967. // ensure _progress does not exceed duration with looped audios
  26968. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26969. }
  26970. this.source.stop();
  26971. this.source.onended = null;
  26972. this.isPlaying = false;
  26973. }
  26974. return this;
  26975. }
  26976. stop() {
  26977. if ( this.hasPlaybackControl === false ) {
  26978. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26979. return;
  26980. }
  26981. this._progress = 0;
  26982. if ( this.source !== null ) {
  26983. this.source.stop();
  26984. this.source.onended = null;
  26985. }
  26986. this.isPlaying = false;
  26987. return this;
  26988. }
  26989. connect() {
  26990. if ( this.filters.length > 0 ) {
  26991. this.source.connect( this.filters[ 0 ] );
  26992. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26993. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26994. }
  26995. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26996. } else {
  26997. this.source.connect( this.getOutput() );
  26998. }
  26999. this._connected = true;
  27000. return this;
  27001. }
  27002. disconnect() {
  27003. if ( this.filters.length > 0 ) {
  27004. this.source.disconnect( this.filters[ 0 ] );
  27005. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  27006. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  27007. }
  27008. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27009. } else {
  27010. this.source.disconnect( this.getOutput() );
  27011. }
  27012. this._connected = false;
  27013. return this;
  27014. }
  27015. getFilters() {
  27016. return this.filters;
  27017. }
  27018. setFilters( value ) {
  27019. if ( ! value ) value = [];
  27020. if ( this._connected === true ) {
  27021. this.disconnect();
  27022. this.filters = value.slice();
  27023. this.connect();
  27024. } else {
  27025. this.filters = value.slice();
  27026. }
  27027. return this;
  27028. }
  27029. setDetune( value ) {
  27030. this.detune = value;
  27031. if ( this.source.detune === undefined ) return; // only set detune when available
  27032. if ( this.isPlaying === true ) {
  27033. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  27034. }
  27035. return this;
  27036. }
  27037. getDetune() {
  27038. return this.detune;
  27039. }
  27040. getFilter() {
  27041. return this.getFilters()[ 0 ];
  27042. }
  27043. setFilter( filter ) {
  27044. return this.setFilters( filter ? [ filter ] : [] );
  27045. }
  27046. setPlaybackRate( value ) {
  27047. if ( this.hasPlaybackControl === false ) {
  27048. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27049. return;
  27050. }
  27051. this.playbackRate = value;
  27052. if ( this.isPlaying === true ) {
  27053. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  27054. }
  27055. return this;
  27056. }
  27057. getPlaybackRate() {
  27058. return this.playbackRate;
  27059. }
  27060. onEnded() {
  27061. this.isPlaying = false;
  27062. }
  27063. getLoop() {
  27064. if ( this.hasPlaybackControl === false ) {
  27065. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27066. return false;
  27067. }
  27068. return this.loop;
  27069. }
  27070. setLoop( value ) {
  27071. if ( this.hasPlaybackControl === false ) {
  27072. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27073. return;
  27074. }
  27075. this.loop = value;
  27076. if ( this.isPlaying === true ) {
  27077. this.source.loop = this.loop;
  27078. }
  27079. return this;
  27080. }
  27081. setLoopStart( value ) {
  27082. this.loopStart = value;
  27083. return this;
  27084. }
  27085. setLoopEnd( value ) {
  27086. this.loopEnd = value;
  27087. return this;
  27088. }
  27089. getVolume() {
  27090. return this.gain.gain.value;
  27091. }
  27092. setVolume( value ) {
  27093. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27094. return this;
  27095. }
  27096. }
  27097. const _position = /*@__PURE__*/ new Vector3();
  27098. const _quaternion = /*@__PURE__*/ new Quaternion();
  27099. const _scale = /*@__PURE__*/ new Vector3();
  27100. const _orientation = /*@__PURE__*/ new Vector3();
  27101. class PositionalAudio extends Audio {
  27102. constructor( listener ) {
  27103. super( listener );
  27104. this.panner = this.context.createPanner();
  27105. this.panner.panningModel = 'HRTF';
  27106. this.panner.connect( this.gain );
  27107. }
  27108. connect() {
  27109. super.connect();
  27110. this.panner.connect( this.gain );
  27111. }
  27112. disconnect() {
  27113. super.disconnect();
  27114. this.panner.disconnect( this.gain );
  27115. }
  27116. getOutput() {
  27117. return this.panner;
  27118. }
  27119. getRefDistance() {
  27120. return this.panner.refDistance;
  27121. }
  27122. setRefDistance( value ) {
  27123. this.panner.refDistance = value;
  27124. return this;
  27125. }
  27126. getRolloffFactor() {
  27127. return this.panner.rolloffFactor;
  27128. }
  27129. setRolloffFactor( value ) {
  27130. this.panner.rolloffFactor = value;
  27131. return this;
  27132. }
  27133. getDistanceModel() {
  27134. return this.panner.distanceModel;
  27135. }
  27136. setDistanceModel( value ) {
  27137. this.panner.distanceModel = value;
  27138. return this;
  27139. }
  27140. getMaxDistance() {
  27141. return this.panner.maxDistance;
  27142. }
  27143. setMaxDistance( value ) {
  27144. this.panner.maxDistance = value;
  27145. return this;
  27146. }
  27147. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  27148. this.panner.coneInnerAngle = coneInnerAngle;
  27149. this.panner.coneOuterAngle = coneOuterAngle;
  27150. this.panner.coneOuterGain = coneOuterGain;
  27151. return this;
  27152. }
  27153. updateMatrixWorld( force ) {
  27154. super.updateMatrixWorld( force );
  27155. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  27156. this.matrixWorld.decompose( _position, _quaternion, _scale );
  27157. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  27158. const panner = this.panner;
  27159. if ( panner.positionX ) {
  27160. // code path for Chrome and Firefox (see #14393)
  27161. const endTime = this.context.currentTime + this.listener.timeDelta;
  27162. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  27163. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  27164. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  27165. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  27166. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  27167. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  27168. } else {
  27169. panner.setPosition( _position.x, _position.y, _position.z );
  27170. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  27171. }
  27172. }
  27173. }
  27174. class AudioAnalyser {
  27175. constructor( audio, fftSize = 2048 ) {
  27176. this.analyser = audio.context.createAnalyser();
  27177. this.analyser.fftSize = fftSize;
  27178. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  27179. audio.getOutput().connect( this.analyser );
  27180. }
  27181. getFrequencyData() {
  27182. this.analyser.getByteFrequencyData( this.data );
  27183. return this.data;
  27184. }
  27185. getAverageFrequency() {
  27186. let value = 0;
  27187. const data = this.getFrequencyData();
  27188. for ( let i = 0; i < data.length; i ++ ) {
  27189. value += data[ i ];
  27190. }
  27191. return value / data.length;
  27192. }
  27193. }
  27194. class PropertyMixer {
  27195. constructor( binding, typeName, valueSize ) {
  27196. this.binding = binding;
  27197. this.valueSize = valueSize;
  27198. let mixFunction,
  27199. mixFunctionAdditive,
  27200. setIdentity;
  27201. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  27202. //
  27203. // interpolators can use .buffer as their .result
  27204. // the data then goes to 'incoming'
  27205. //
  27206. // 'accu0' and 'accu1' are used frame-interleaved for
  27207. // the cumulative result and are compared to detect
  27208. // changes
  27209. //
  27210. // 'orig' stores the original state of the property
  27211. //
  27212. // 'add' is used for additive cumulative results
  27213. //
  27214. // 'work' is optional and is only present for quaternion types. It is used
  27215. // to store intermediate quaternion multiplication results
  27216. switch ( typeName ) {
  27217. case 'quaternion':
  27218. mixFunction = this._slerp;
  27219. mixFunctionAdditive = this._slerpAdditive;
  27220. setIdentity = this._setAdditiveIdentityQuaternion;
  27221. this.buffer = new Float64Array( valueSize * 6 );
  27222. this._workIndex = 5;
  27223. break;
  27224. case 'string':
  27225. case 'bool':
  27226. mixFunction = this._select;
  27227. // Use the regular mix function and for additive on these types,
  27228. // additive is not relevant for non-numeric types
  27229. mixFunctionAdditive = this._select;
  27230. setIdentity = this._setAdditiveIdentityOther;
  27231. this.buffer = new Array( valueSize * 5 );
  27232. break;
  27233. default:
  27234. mixFunction = this._lerp;
  27235. mixFunctionAdditive = this._lerpAdditive;
  27236. setIdentity = this._setAdditiveIdentityNumeric;
  27237. this.buffer = new Float64Array( valueSize * 5 );
  27238. }
  27239. this._mixBufferRegion = mixFunction;
  27240. this._mixBufferRegionAdditive = mixFunctionAdditive;
  27241. this._setIdentity = setIdentity;
  27242. this._origIndex = 3;
  27243. this._addIndex = 4;
  27244. this.cumulativeWeight = 0;
  27245. this.cumulativeWeightAdditive = 0;
  27246. this.useCount = 0;
  27247. this.referenceCount = 0;
  27248. }
  27249. // accumulate data in the 'incoming' region into 'accu<i>'
  27250. accumulate( accuIndex, weight ) {
  27251. // note: happily accumulating nothing when weight = 0, the caller knows
  27252. // the weight and shouldn't have made the call in the first place
  27253. const buffer = this.buffer,
  27254. stride = this.valueSize,
  27255. offset = accuIndex * stride + stride;
  27256. let currentWeight = this.cumulativeWeight;
  27257. if ( currentWeight === 0 ) {
  27258. // accuN := incoming * weight
  27259. for ( let i = 0; i !== stride; ++ i ) {
  27260. buffer[ offset + i ] = buffer[ i ];
  27261. }
  27262. currentWeight = weight;
  27263. } else {
  27264. // accuN := accuN + incoming * weight
  27265. currentWeight += weight;
  27266. const mix = weight / currentWeight;
  27267. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27268. }
  27269. this.cumulativeWeight = currentWeight;
  27270. }
  27271. // accumulate data in the 'incoming' region into 'add'
  27272. accumulateAdditive( weight ) {
  27273. const buffer = this.buffer,
  27274. stride = this.valueSize,
  27275. offset = stride * this._addIndex;
  27276. if ( this.cumulativeWeightAdditive === 0 ) {
  27277. // add = identity
  27278. this._setIdentity();
  27279. }
  27280. // add := add + incoming * weight
  27281. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  27282. this.cumulativeWeightAdditive += weight;
  27283. }
  27284. // apply the state of 'accu<i>' to the binding when accus differ
  27285. apply( accuIndex ) {
  27286. const stride = this.valueSize,
  27287. buffer = this.buffer,
  27288. offset = accuIndex * stride + stride,
  27289. weight = this.cumulativeWeight,
  27290. weightAdditive = this.cumulativeWeightAdditive,
  27291. binding = this.binding;
  27292. this.cumulativeWeight = 0;
  27293. this.cumulativeWeightAdditive = 0;
  27294. if ( weight < 1 ) {
  27295. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27296. const originalValueOffset = stride * this._origIndex;
  27297. this._mixBufferRegion(
  27298. buffer, offset, originalValueOffset, 1 - weight, stride );
  27299. }
  27300. if ( weightAdditive > 0 ) {
  27301. // accuN := accuN + additive accuN
  27302. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  27303. }
  27304. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  27305. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27306. // value has changed -> update scene graph
  27307. binding.setValue( buffer, offset );
  27308. break;
  27309. }
  27310. }
  27311. }
  27312. // remember the state of the bound property and copy it to both accus
  27313. saveOriginalState() {
  27314. const binding = this.binding;
  27315. const buffer = this.buffer,
  27316. stride = this.valueSize,
  27317. originalValueOffset = stride * this._origIndex;
  27318. binding.getValue( buffer, originalValueOffset );
  27319. // accu[0..1] := orig -- initially detect changes against the original
  27320. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27321. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27322. }
  27323. // Add to identity for additive
  27324. this._setIdentity();
  27325. this.cumulativeWeight = 0;
  27326. this.cumulativeWeightAdditive = 0;
  27327. }
  27328. // apply the state previously taken via 'saveOriginalState' to the binding
  27329. restoreOriginalState() {
  27330. const originalValueOffset = this.valueSize * 3;
  27331. this.binding.setValue( this.buffer, originalValueOffset );
  27332. }
  27333. _setAdditiveIdentityNumeric() {
  27334. const startIndex = this._addIndex * this.valueSize;
  27335. const endIndex = startIndex + this.valueSize;
  27336. for ( let i = startIndex; i < endIndex; i ++ ) {
  27337. this.buffer[ i ] = 0;
  27338. }
  27339. }
  27340. _setAdditiveIdentityQuaternion() {
  27341. this._setAdditiveIdentityNumeric();
  27342. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  27343. }
  27344. _setAdditiveIdentityOther() {
  27345. const startIndex = this._origIndex * this.valueSize;
  27346. const targetIndex = this._addIndex * this.valueSize;
  27347. for ( let i = 0; i < this.valueSize; i ++ ) {
  27348. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  27349. }
  27350. }
  27351. // mix functions
  27352. _select( buffer, dstOffset, srcOffset, t, stride ) {
  27353. if ( t >= 0.5 ) {
  27354. for ( let i = 0; i !== stride; ++ i ) {
  27355. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27356. }
  27357. }
  27358. }
  27359. _slerp( buffer, dstOffset, srcOffset, t ) {
  27360. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27361. }
  27362. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27363. const workOffset = this._workIndex * stride;
  27364. // Store result in intermediate buffer offset
  27365. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  27366. // Slerp to the intermediate result
  27367. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  27368. }
  27369. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  27370. const s = 1 - t;
  27371. for ( let i = 0; i !== stride; ++ i ) {
  27372. const j = dstOffset + i;
  27373. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27374. }
  27375. }
  27376. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27377. for ( let i = 0; i !== stride; ++ i ) {
  27378. const j = dstOffset + i;
  27379. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  27380. }
  27381. }
  27382. }
  27383. // Characters [].:/ are reserved for track binding syntax.
  27384. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27385. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27386. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27387. // only latin characters, and the unicode \p{L} is not yet supported. So
  27388. // instead, we exclude reserved characters and match everything else.
  27389. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27390. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27391. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27392. // be matched to parse the rest of the track name.
  27393. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27394. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27395. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27396. // Object on target node, and accessor. May not contain reserved
  27397. // characters. Accessor may contain any character except closing bracket.
  27398. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27399. // Property and accessor. May not contain reserved characters. Accessor may
  27400. // contain any non-bracket characters.
  27401. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27402. const _trackRe = new RegExp( ''
  27403. + '^'
  27404. + _directoryRe
  27405. + _nodeRe
  27406. + _objectRe
  27407. + _propertyRe
  27408. + '$'
  27409. );
  27410. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  27411. class Composite {
  27412. constructor( targetGroup, path, optionalParsedPath ) {
  27413. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27414. this._targetGroup = targetGroup;
  27415. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27416. }
  27417. getValue( array, offset ) {
  27418. this.bind(); // bind all binding
  27419. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27420. binding = this._bindings[ firstValidIndex ];
  27421. // and only call .getValue on the first
  27422. if ( binding !== undefined ) binding.getValue( array, offset );
  27423. }
  27424. setValue( array, offset ) {
  27425. const bindings = this._bindings;
  27426. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27427. bindings[ i ].setValue( array, offset );
  27428. }
  27429. }
  27430. bind() {
  27431. const bindings = this._bindings;
  27432. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27433. bindings[ i ].bind();
  27434. }
  27435. }
  27436. unbind() {
  27437. const bindings = this._bindings;
  27438. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27439. bindings[ i ].unbind();
  27440. }
  27441. }
  27442. }
  27443. // Note: This class uses a State pattern on a per-method basis:
  27444. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27445. // prototype version of these methods with one that represents
  27446. // the bound state. When the property is not found, the methods
  27447. // become no-ops.
  27448. class PropertyBinding {
  27449. constructor( rootNode, path, parsedPath ) {
  27450. this.path = path;
  27451. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27452. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  27453. this.rootNode = rootNode;
  27454. // initial state of these methods that calls 'bind'
  27455. this.getValue = this._getValue_unbound;
  27456. this.setValue = this._setValue_unbound;
  27457. }
  27458. static create( root, path, parsedPath ) {
  27459. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27460. return new PropertyBinding( root, path, parsedPath );
  27461. } else {
  27462. return new PropertyBinding.Composite( root, path, parsedPath );
  27463. }
  27464. }
  27465. /**
  27466. * Replaces spaces with underscores and removes unsupported characters from
  27467. * node names, to ensure compatibility with parseTrackName().
  27468. *
  27469. * @param {string} name Node name to be sanitized.
  27470. * @return {string}
  27471. */
  27472. static sanitizeNodeName( name ) {
  27473. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27474. }
  27475. static parseTrackName( trackName ) {
  27476. const matches = _trackRe.exec( trackName );
  27477. if ( matches === null ) {
  27478. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27479. }
  27480. const results = {
  27481. // directoryName: matches[ 1 ], // (tschw) currently unused
  27482. nodeName: matches[ 2 ],
  27483. objectName: matches[ 3 ],
  27484. objectIndex: matches[ 4 ],
  27485. propertyName: matches[ 5 ], // required
  27486. propertyIndex: matches[ 6 ]
  27487. };
  27488. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27489. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27490. const objectName = results.nodeName.substring( lastDot + 1 );
  27491. // Object names must be checked against an allowlist. Otherwise, there
  27492. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27493. // 'bar' could be the objectName, or part of a nodeName (which can
  27494. // include '.' characters).
  27495. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27496. results.nodeName = results.nodeName.substring( 0, lastDot );
  27497. results.objectName = objectName;
  27498. }
  27499. }
  27500. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27501. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27502. }
  27503. return results;
  27504. }
  27505. static findNode( root, nodeName ) {
  27506. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27507. return root;
  27508. }
  27509. // search into skeleton bones.
  27510. if ( root.skeleton ) {
  27511. const bone = root.skeleton.getBoneByName( nodeName );
  27512. if ( bone !== undefined ) {
  27513. return bone;
  27514. }
  27515. }
  27516. // search into node subtree.
  27517. if ( root.children ) {
  27518. const searchNodeSubtree = function ( children ) {
  27519. for ( let i = 0; i < children.length; i ++ ) {
  27520. const childNode = children[ i ];
  27521. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27522. return childNode;
  27523. }
  27524. const result = searchNodeSubtree( childNode.children );
  27525. if ( result ) return result;
  27526. }
  27527. return null;
  27528. };
  27529. const subTreeNode = searchNodeSubtree( root.children );
  27530. if ( subTreeNode ) {
  27531. return subTreeNode;
  27532. }
  27533. }
  27534. return null;
  27535. }
  27536. // these are used to "bind" a nonexistent property
  27537. _getValue_unavailable() {}
  27538. _setValue_unavailable() {}
  27539. // Getters
  27540. _getValue_direct( buffer, offset ) {
  27541. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27542. }
  27543. _getValue_array( buffer, offset ) {
  27544. const source = this.resolvedProperty;
  27545. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27546. buffer[ offset ++ ] = source[ i ];
  27547. }
  27548. }
  27549. _getValue_arrayElement( buffer, offset ) {
  27550. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27551. }
  27552. _getValue_toArray( buffer, offset ) {
  27553. this.resolvedProperty.toArray( buffer, offset );
  27554. }
  27555. // Direct
  27556. _setValue_direct( buffer, offset ) {
  27557. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27558. }
  27559. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27560. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27561. this.targetObject.needsUpdate = true;
  27562. }
  27563. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27564. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27565. this.targetObject.matrixWorldNeedsUpdate = true;
  27566. }
  27567. // EntireArray
  27568. _setValue_array( buffer, offset ) {
  27569. const dest = this.resolvedProperty;
  27570. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27571. dest[ i ] = buffer[ offset ++ ];
  27572. }
  27573. }
  27574. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27575. const dest = this.resolvedProperty;
  27576. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27577. dest[ i ] = buffer[ offset ++ ];
  27578. }
  27579. this.targetObject.needsUpdate = true;
  27580. }
  27581. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27582. const dest = this.resolvedProperty;
  27583. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27584. dest[ i ] = buffer[ offset ++ ];
  27585. }
  27586. this.targetObject.matrixWorldNeedsUpdate = true;
  27587. }
  27588. // ArrayElement
  27589. _setValue_arrayElement( buffer, offset ) {
  27590. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27591. }
  27592. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27593. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27594. this.targetObject.needsUpdate = true;
  27595. }
  27596. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27597. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27598. this.targetObject.matrixWorldNeedsUpdate = true;
  27599. }
  27600. // HasToFromArray
  27601. _setValue_fromArray( buffer, offset ) {
  27602. this.resolvedProperty.fromArray( buffer, offset );
  27603. }
  27604. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27605. this.resolvedProperty.fromArray( buffer, offset );
  27606. this.targetObject.needsUpdate = true;
  27607. }
  27608. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27609. this.resolvedProperty.fromArray( buffer, offset );
  27610. this.targetObject.matrixWorldNeedsUpdate = true;
  27611. }
  27612. _getValue_unbound( targetArray, offset ) {
  27613. this.bind();
  27614. this.getValue( targetArray, offset );
  27615. }
  27616. _setValue_unbound( sourceArray, offset ) {
  27617. this.bind();
  27618. this.setValue( sourceArray, offset );
  27619. }
  27620. // create getter / setter pair for a property in the scene graph
  27621. bind() {
  27622. let targetObject = this.node;
  27623. const parsedPath = this.parsedPath;
  27624. const objectName = parsedPath.objectName;
  27625. const propertyName = parsedPath.propertyName;
  27626. let propertyIndex = parsedPath.propertyIndex;
  27627. if ( ! targetObject ) {
  27628. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27629. this.node = targetObject;
  27630. }
  27631. // set fail state so we can just 'return' on error
  27632. this.getValue = this._getValue_unavailable;
  27633. this.setValue = this._setValue_unavailable;
  27634. // ensure there is a value node
  27635. if ( ! targetObject ) {
  27636. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27637. return;
  27638. }
  27639. if ( objectName ) {
  27640. let objectIndex = parsedPath.objectIndex;
  27641. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27642. switch ( objectName ) {
  27643. case 'materials':
  27644. if ( ! targetObject.material ) {
  27645. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27646. return;
  27647. }
  27648. if ( ! targetObject.material.materials ) {
  27649. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27650. return;
  27651. }
  27652. targetObject = targetObject.material.materials;
  27653. break;
  27654. case 'bones':
  27655. if ( ! targetObject.skeleton ) {
  27656. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27657. return;
  27658. }
  27659. // potential future optimization: skip this if propertyIndex is already an integer
  27660. // and convert the integer string to a true integer.
  27661. targetObject = targetObject.skeleton.bones;
  27662. // support resolving morphTarget names into indices.
  27663. for ( let i = 0; i < targetObject.length; i ++ ) {
  27664. if ( targetObject[ i ].name === objectIndex ) {
  27665. objectIndex = i;
  27666. break;
  27667. }
  27668. }
  27669. break;
  27670. case 'map':
  27671. if ( 'map' in targetObject ) {
  27672. targetObject = targetObject.map;
  27673. break;
  27674. }
  27675. if ( ! targetObject.material ) {
  27676. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27677. return;
  27678. }
  27679. if ( ! targetObject.material.map ) {
  27680. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27681. return;
  27682. }
  27683. targetObject = targetObject.material.map;
  27684. break;
  27685. default:
  27686. if ( targetObject[ objectName ] === undefined ) {
  27687. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27688. return;
  27689. }
  27690. targetObject = targetObject[ objectName ];
  27691. }
  27692. if ( objectIndex !== undefined ) {
  27693. if ( targetObject[ objectIndex ] === undefined ) {
  27694. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27695. return;
  27696. }
  27697. targetObject = targetObject[ objectIndex ];
  27698. }
  27699. }
  27700. // resolve property
  27701. const nodeProperty = targetObject[ propertyName ];
  27702. if ( nodeProperty === undefined ) {
  27703. const nodeName = parsedPath.nodeName;
  27704. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27705. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27706. return;
  27707. }
  27708. // determine versioning scheme
  27709. let versioning = this.Versioning.None;
  27710. this.targetObject = targetObject;
  27711. if ( targetObject.needsUpdate !== undefined ) { // material
  27712. versioning = this.Versioning.NeedsUpdate;
  27713. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27714. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27715. }
  27716. // determine how the property gets bound
  27717. let bindingType = this.BindingType.Direct;
  27718. if ( propertyIndex !== undefined ) {
  27719. // access a sub element of the property array (only primitives are supported right now)
  27720. if ( propertyName === 'morphTargetInfluences' ) {
  27721. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27722. // support resolving morphTarget names into indices.
  27723. if ( ! targetObject.geometry ) {
  27724. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27725. return;
  27726. }
  27727. if ( ! targetObject.geometry.morphAttributes ) {
  27728. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27729. return;
  27730. }
  27731. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27732. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27733. }
  27734. }
  27735. bindingType = this.BindingType.ArrayElement;
  27736. this.resolvedProperty = nodeProperty;
  27737. this.propertyIndex = propertyIndex;
  27738. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27739. // must use copy for Object3D.Euler/Quaternion
  27740. bindingType = this.BindingType.HasFromToArray;
  27741. this.resolvedProperty = nodeProperty;
  27742. } else if ( Array.isArray( nodeProperty ) ) {
  27743. bindingType = this.BindingType.EntireArray;
  27744. this.resolvedProperty = nodeProperty;
  27745. } else {
  27746. this.propertyName = propertyName;
  27747. }
  27748. // select getter / setter
  27749. this.getValue = this.GetterByBindingType[ bindingType ];
  27750. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27751. }
  27752. unbind() {
  27753. this.node = null;
  27754. // back to the prototype version of getValue / setValue
  27755. // note: avoiding to mutate the shape of 'this' via 'delete'
  27756. this.getValue = this._getValue_unbound;
  27757. this.setValue = this._setValue_unbound;
  27758. }
  27759. }
  27760. PropertyBinding.Composite = Composite;
  27761. PropertyBinding.prototype.BindingType = {
  27762. Direct: 0,
  27763. EntireArray: 1,
  27764. ArrayElement: 2,
  27765. HasFromToArray: 3
  27766. };
  27767. PropertyBinding.prototype.Versioning = {
  27768. None: 0,
  27769. NeedsUpdate: 1,
  27770. MatrixWorldNeedsUpdate: 2
  27771. };
  27772. PropertyBinding.prototype.GetterByBindingType = [
  27773. PropertyBinding.prototype._getValue_direct,
  27774. PropertyBinding.prototype._getValue_array,
  27775. PropertyBinding.prototype._getValue_arrayElement,
  27776. PropertyBinding.prototype._getValue_toArray,
  27777. ];
  27778. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27779. [
  27780. // Direct
  27781. PropertyBinding.prototype._setValue_direct,
  27782. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27783. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27784. ], [
  27785. // EntireArray
  27786. PropertyBinding.prototype._setValue_array,
  27787. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27788. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27789. ], [
  27790. // ArrayElement
  27791. PropertyBinding.prototype._setValue_arrayElement,
  27792. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27793. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27794. ], [
  27795. // HasToFromArray
  27796. PropertyBinding.prototype._setValue_fromArray,
  27797. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27798. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27799. ]
  27800. ];
  27801. /**
  27802. *
  27803. * A group of objects that receives a shared animation state.
  27804. *
  27805. * Usage:
  27806. *
  27807. * - Add objects you would otherwise pass as 'root' to the
  27808. * constructor or the .clipAction method of AnimationMixer.
  27809. *
  27810. * - Instead pass this object as 'root'.
  27811. *
  27812. * - You can also add and remove objects later when the mixer
  27813. * is running.
  27814. *
  27815. * Note:
  27816. *
  27817. * Objects of this class appear as one object to the mixer,
  27818. * so cache control of the individual objects must be done
  27819. * on the group.
  27820. *
  27821. * Limitation:
  27822. *
  27823. * - The animated properties must be compatible among the
  27824. * all objects in the group.
  27825. *
  27826. * - A single property can either be controlled through a
  27827. * target group or directly, but not both.
  27828. */
  27829. class AnimationObjectGroup {
  27830. constructor() {
  27831. this.isAnimationObjectGroup = true;
  27832. this.uuid = generateUUID();
  27833. // cached objects followed by the active ones
  27834. this._objects = Array.prototype.slice.call( arguments );
  27835. this.nCachedObjects_ = 0; // threshold
  27836. // note: read by PropertyBinding.Composite
  27837. const indices = {};
  27838. this._indicesByUUID = indices; // for bookkeeping
  27839. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27840. indices[ arguments[ i ].uuid ] = i;
  27841. }
  27842. this._paths = []; // inside: string
  27843. this._parsedPaths = []; // inside: { we don't care, here }
  27844. this._bindings = []; // inside: Array< PropertyBinding >
  27845. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27846. const scope = this;
  27847. this.stats = {
  27848. objects: {
  27849. get total() {
  27850. return scope._objects.length;
  27851. },
  27852. get inUse() {
  27853. return this.total - scope.nCachedObjects_;
  27854. }
  27855. },
  27856. get bindingsPerObject() {
  27857. return scope._bindings.length;
  27858. }
  27859. };
  27860. }
  27861. add() {
  27862. const objects = this._objects,
  27863. indicesByUUID = this._indicesByUUID,
  27864. paths = this._paths,
  27865. parsedPaths = this._parsedPaths,
  27866. bindings = this._bindings,
  27867. nBindings = bindings.length;
  27868. let knownObject = undefined,
  27869. nObjects = objects.length,
  27870. nCachedObjects = this.nCachedObjects_;
  27871. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27872. const object = arguments[ i ],
  27873. uuid = object.uuid;
  27874. let index = indicesByUUID[ uuid ];
  27875. if ( index === undefined ) {
  27876. // unknown object -> add it to the ACTIVE region
  27877. index = nObjects ++;
  27878. indicesByUUID[ uuid ] = index;
  27879. objects.push( object );
  27880. // accounting is done, now do the same for all bindings
  27881. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27882. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27883. }
  27884. } else if ( index < nCachedObjects ) {
  27885. knownObject = objects[ index ];
  27886. // move existing object to the ACTIVE region
  27887. const firstActiveIndex = -- nCachedObjects,
  27888. lastCachedObject = objects[ firstActiveIndex ];
  27889. indicesByUUID[ lastCachedObject.uuid ] = index;
  27890. objects[ index ] = lastCachedObject;
  27891. indicesByUUID[ uuid ] = firstActiveIndex;
  27892. objects[ firstActiveIndex ] = object;
  27893. // accounting is done, now do the same for all bindings
  27894. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27895. const bindingsForPath = bindings[ j ],
  27896. lastCached = bindingsForPath[ firstActiveIndex ];
  27897. let binding = bindingsForPath[ index ];
  27898. bindingsForPath[ index ] = lastCached;
  27899. if ( binding === undefined ) {
  27900. // since we do not bother to create new bindings
  27901. // for objects that are cached, the binding may
  27902. // or may not exist
  27903. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27904. }
  27905. bindingsForPath[ firstActiveIndex ] = binding;
  27906. }
  27907. } else if ( objects[ index ] !== knownObject ) {
  27908. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27909. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27910. } // else the object is already where we want it to be
  27911. } // for arguments
  27912. this.nCachedObjects_ = nCachedObjects;
  27913. }
  27914. remove() {
  27915. const objects = this._objects,
  27916. indicesByUUID = this._indicesByUUID,
  27917. bindings = this._bindings,
  27918. nBindings = bindings.length;
  27919. let nCachedObjects = this.nCachedObjects_;
  27920. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27921. const object = arguments[ i ],
  27922. uuid = object.uuid,
  27923. index = indicesByUUID[ uuid ];
  27924. if ( index !== undefined && index >= nCachedObjects ) {
  27925. // move existing object into the CACHED region
  27926. const lastCachedIndex = nCachedObjects ++,
  27927. firstActiveObject = objects[ lastCachedIndex ];
  27928. indicesByUUID[ firstActiveObject.uuid ] = index;
  27929. objects[ index ] = firstActiveObject;
  27930. indicesByUUID[ uuid ] = lastCachedIndex;
  27931. objects[ lastCachedIndex ] = object;
  27932. // accounting is done, now do the same for all bindings
  27933. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27934. const bindingsForPath = bindings[ j ],
  27935. firstActive = bindingsForPath[ lastCachedIndex ],
  27936. binding = bindingsForPath[ index ];
  27937. bindingsForPath[ index ] = firstActive;
  27938. bindingsForPath[ lastCachedIndex ] = binding;
  27939. }
  27940. }
  27941. } // for arguments
  27942. this.nCachedObjects_ = nCachedObjects;
  27943. }
  27944. // remove & forget
  27945. uncache() {
  27946. const objects = this._objects,
  27947. indicesByUUID = this._indicesByUUID,
  27948. bindings = this._bindings,
  27949. nBindings = bindings.length;
  27950. let nCachedObjects = this.nCachedObjects_,
  27951. nObjects = objects.length;
  27952. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27953. const object = arguments[ i ],
  27954. uuid = object.uuid,
  27955. index = indicesByUUID[ uuid ];
  27956. if ( index !== undefined ) {
  27957. delete indicesByUUID[ uuid ];
  27958. if ( index < nCachedObjects ) {
  27959. // object is cached, shrink the CACHED region
  27960. const firstActiveIndex = -- nCachedObjects,
  27961. lastCachedObject = objects[ firstActiveIndex ],
  27962. lastIndex = -- nObjects,
  27963. lastObject = objects[ lastIndex ];
  27964. // last cached object takes this object's place
  27965. indicesByUUID[ lastCachedObject.uuid ] = index;
  27966. objects[ index ] = lastCachedObject;
  27967. // last object goes to the activated slot and pop
  27968. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27969. objects[ firstActiveIndex ] = lastObject;
  27970. objects.pop();
  27971. // accounting is done, now do the same for all bindings
  27972. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27973. const bindingsForPath = bindings[ j ],
  27974. lastCached = bindingsForPath[ firstActiveIndex ],
  27975. last = bindingsForPath[ lastIndex ];
  27976. bindingsForPath[ index ] = lastCached;
  27977. bindingsForPath[ firstActiveIndex ] = last;
  27978. bindingsForPath.pop();
  27979. }
  27980. } else {
  27981. // object is active, just swap with the last and pop
  27982. const lastIndex = -- nObjects,
  27983. lastObject = objects[ lastIndex ];
  27984. if ( lastIndex > 0 ) {
  27985. indicesByUUID[ lastObject.uuid ] = index;
  27986. }
  27987. objects[ index ] = lastObject;
  27988. objects.pop();
  27989. // accounting is done, now do the same for all bindings
  27990. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27991. const bindingsForPath = bindings[ j ];
  27992. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27993. bindingsForPath.pop();
  27994. }
  27995. } // cached or active
  27996. } // if object is known
  27997. } // for arguments
  27998. this.nCachedObjects_ = nCachedObjects;
  27999. }
  28000. // Internal interface used by befriended PropertyBinding.Composite:
  28001. subscribe_( path, parsedPath ) {
  28002. // returns an array of bindings for the given path that is changed
  28003. // according to the contained objects in the group
  28004. const indicesByPath = this._bindingsIndicesByPath;
  28005. let index = indicesByPath[ path ];
  28006. const bindings = this._bindings;
  28007. if ( index !== undefined ) return bindings[ index ];
  28008. const paths = this._paths,
  28009. parsedPaths = this._parsedPaths,
  28010. objects = this._objects,
  28011. nObjects = objects.length,
  28012. nCachedObjects = this.nCachedObjects_,
  28013. bindingsForPath = new Array( nObjects );
  28014. index = bindings.length;
  28015. indicesByPath[ path ] = index;
  28016. paths.push( path );
  28017. parsedPaths.push( parsedPath );
  28018. bindings.push( bindingsForPath );
  28019. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  28020. const object = objects[ i ];
  28021. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  28022. }
  28023. return bindingsForPath;
  28024. }
  28025. unsubscribe_( path ) {
  28026. // tells the group to forget about a property path and no longer
  28027. // update the array previously obtained with 'subscribe_'
  28028. const indicesByPath = this._bindingsIndicesByPath,
  28029. index = indicesByPath[ path ];
  28030. if ( index !== undefined ) {
  28031. const paths = this._paths,
  28032. parsedPaths = this._parsedPaths,
  28033. bindings = this._bindings,
  28034. lastBindingsIndex = bindings.length - 1,
  28035. lastBindings = bindings[ lastBindingsIndex ],
  28036. lastBindingsPath = path[ lastBindingsIndex ];
  28037. indicesByPath[ lastBindingsPath ] = index;
  28038. bindings[ index ] = lastBindings;
  28039. bindings.pop();
  28040. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  28041. parsedPaths.pop();
  28042. paths[ index ] = paths[ lastBindingsIndex ];
  28043. paths.pop();
  28044. }
  28045. }
  28046. }
  28047. class AnimationAction {
  28048. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  28049. this._mixer = mixer;
  28050. this._clip = clip;
  28051. this._localRoot = localRoot;
  28052. this.blendMode = blendMode;
  28053. const tracks = clip.tracks,
  28054. nTracks = tracks.length,
  28055. interpolants = new Array( nTracks );
  28056. const interpolantSettings = {
  28057. endingStart: ZeroCurvatureEnding,
  28058. endingEnd: ZeroCurvatureEnding
  28059. };
  28060. for ( let i = 0; i !== nTracks; ++ i ) {
  28061. const interpolant = tracks[ i ].createInterpolant( null );
  28062. interpolants[ i ] = interpolant;
  28063. interpolant.settings = interpolantSettings;
  28064. }
  28065. this._interpolantSettings = interpolantSettings;
  28066. this._interpolants = interpolants; // bound by the mixer
  28067. // inside: PropertyMixer (managed by the mixer)
  28068. this._propertyBindings = new Array( nTracks );
  28069. this._cacheIndex = null; // for the memory manager
  28070. this._byClipCacheIndex = null; // for the memory manager
  28071. this._timeScaleInterpolant = null;
  28072. this._weightInterpolant = null;
  28073. this.loop = LoopRepeat;
  28074. this._loopCount = - 1;
  28075. // global mixer time when the action is to be started
  28076. // it's set back to 'null' upon start of the action
  28077. this._startTime = null;
  28078. // scaled local time of the action
  28079. // gets clamped or wrapped to 0..clip.duration according to loop
  28080. this.time = 0;
  28081. this.timeScale = 1;
  28082. this._effectiveTimeScale = 1;
  28083. this.weight = 1;
  28084. this._effectiveWeight = 1;
  28085. this.repetitions = Infinity; // no. of repetitions when looping
  28086. this.paused = false; // true -> zero effective time scale
  28087. this.enabled = true; // false -> zero effective weight
  28088. this.clampWhenFinished = false;// keep feeding the last frame?
  28089. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  28090. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  28091. }
  28092. // State & Scheduling
  28093. play() {
  28094. this._mixer._activateAction( this );
  28095. return this;
  28096. }
  28097. stop() {
  28098. this._mixer._deactivateAction( this );
  28099. return this.reset();
  28100. }
  28101. reset() {
  28102. this.paused = false;
  28103. this.enabled = true;
  28104. this.time = 0; // restart clip
  28105. this._loopCount = - 1;// forget previous loops
  28106. this._startTime = null;// forget scheduling
  28107. return this.stopFading().stopWarping();
  28108. }
  28109. isRunning() {
  28110. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  28111. this._startTime === null && this._mixer._isActiveAction( this );
  28112. }
  28113. // return true when play has been called
  28114. isScheduled() {
  28115. return this._mixer._isActiveAction( this );
  28116. }
  28117. startAt( time ) {
  28118. this._startTime = time;
  28119. return this;
  28120. }
  28121. setLoop( mode, repetitions ) {
  28122. this.loop = mode;
  28123. this.repetitions = repetitions;
  28124. return this;
  28125. }
  28126. // Weight
  28127. // set the weight stopping any scheduled fading
  28128. // although .enabled = false yields an effective weight of zero, this
  28129. // method does *not* change .enabled, because it would be confusing
  28130. setEffectiveWeight( weight ) {
  28131. this.weight = weight;
  28132. // note: same logic as when updated at runtime
  28133. this._effectiveWeight = this.enabled ? weight : 0;
  28134. return this.stopFading();
  28135. }
  28136. // return the weight considering fading and .enabled
  28137. getEffectiveWeight() {
  28138. return this._effectiveWeight;
  28139. }
  28140. fadeIn( duration ) {
  28141. return this._scheduleFading( duration, 0, 1 );
  28142. }
  28143. fadeOut( duration ) {
  28144. return this._scheduleFading( duration, 1, 0 );
  28145. }
  28146. crossFadeFrom( fadeOutAction, duration, warp ) {
  28147. fadeOutAction.fadeOut( duration );
  28148. this.fadeIn( duration );
  28149. if ( warp ) {
  28150. const fadeInDuration = this._clip.duration,
  28151. fadeOutDuration = fadeOutAction._clip.duration,
  28152. startEndRatio = fadeOutDuration / fadeInDuration,
  28153. endStartRatio = fadeInDuration / fadeOutDuration;
  28154. fadeOutAction.warp( 1.0, startEndRatio, duration );
  28155. this.warp( endStartRatio, 1.0, duration );
  28156. }
  28157. return this;
  28158. }
  28159. crossFadeTo( fadeInAction, duration, warp ) {
  28160. return fadeInAction.crossFadeFrom( this, duration, warp );
  28161. }
  28162. stopFading() {
  28163. const weightInterpolant = this._weightInterpolant;
  28164. if ( weightInterpolant !== null ) {
  28165. this._weightInterpolant = null;
  28166. this._mixer._takeBackControlInterpolant( weightInterpolant );
  28167. }
  28168. return this;
  28169. }
  28170. // Time Scale Control
  28171. // set the time scale stopping any scheduled warping
  28172. // although .paused = true yields an effective time scale of zero, this
  28173. // method does *not* change .paused, because it would be confusing
  28174. setEffectiveTimeScale( timeScale ) {
  28175. this.timeScale = timeScale;
  28176. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  28177. return this.stopWarping();
  28178. }
  28179. // return the time scale considering warping and .paused
  28180. getEffectiveTimeScale() {
  28181. return this._effectiveTimeScale;
  28182. }
  28183. setDuration( duration ) {
  28184. this.timeScale = this._clip.duration / duration;
  28185. return this.stopWarping();
  28186. }
  28187. syncWith( action ) {
  28188. this.time = action.time;
  28189. this.timeScale = action.timeScale;
  28190. return this.stopWarping();
  28191. }
  28192. halt( duration ) {
  28193. return this.warp( this._effectiveTimeScale, 0, duration );
  28194. }
  28195. warp( startTimeScale, endTimeScale, duration ) {
  28196. const mixer = this._mixer,
  28197. now = mixer.time,
  28198. timeScale = this.timeScale;
  28199. let interpolant = this._timeScaleInterpolant;
  28200. if ( interpolant === null ) {
  28201. interpolant = mixer._lendControlInterpolant();
  28202. this._timeScaleInterpolant = interpolant;
  28203. }
  28204. const times = interpolant.parameterPositions,
  28205. values = interpolant.sampleValues;
  28206. times[ 0 ] = now;
  28207. times[ 1 ] = now + duration;
  28208. values[ 0 ] = startTimeScale / timeScale;
  28209. values[ 1 ] = endTimeScale / timeScale;
  28210. return this;
  28211. }
  28212. stopWarping() {
  28213. const timeScaleInterpolant = this._timeScaleInterpolant;
  28214. if ( timeScaleInterpolant !== null ) {
  28215. this._timeScaleInterpolant = null;
  28216. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  28217. }
  28218. return this;
  28219. }
  28220. // Object Accessors
  28221. getMixer() {
  28222. return this._mixer;
  28223. }
  28224. getClip() {
  28225. return this._clip;
  28226. }
  28227. getRoot() {
  28228. return this._localRoot || this._mixer._root;
  28229. }
  28230. // Interna
  28231. _update( time, deltaTime, timeDirection, accuIndex ) {
  28232. // called by the mixer
  28233. if ( ! this.enabled ) {
  28234. // call ._updateWeight() to update ._effectiveWeight
  28235. this._updateWeight( time );
  28236. return;
  28237. }
  28238. const startTime = this._startTime;
  28239. if ( startTime !== null ) {
  28240. // check for scheduled start of action
  28241. const timeRunning = ( time - startTime ) * timeDirection;
  28242. if ( timeRunning < 0 || timeDirection === 0 ) {
  28243. deltaTime = 0;
  28244. } else {
  28245. this._startTime = null; // unschedule
  28246. deltaTime = timeDirection * timeRunning;
  28247. }
  28248. }
  28249. // apply time scale and advance time
  28250. deltaTime *= this._updateTimeScale( time );
  28251. const clipTime = this._updateTime( deltaTime );
  28252. // note: _updateTime may disable the action resulting in
  28253. // an effective weight of 0
  28254. const weight = this._updateWeight( time );
  28255. if ( weight > 0 ) {
  28256. const interpolants = this._interpolants;
  28257. const propertyMixers = this._propertyBindings;
  28258. switch ( this.blendMode ) {
  28259. case AdditiveAnimationBlendMode:
  28260. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28261. interpolants[ j ].evaluate( clipTime );
  28262. propertyMixers[ j ].accumulateAdditive( weight );
  28263. }
  28264. break;
  28265. case NormalAnimationBlendMode:
  28266. default:
  28267. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28268. interpolants[ j ].evaluate( clipTime );
  28269. propertyMixers[ j ].accumulate( accuIndex, weight );
  28270. }
  28271. }
  28272. }
  28273. }
  28274. _updateWeight( time ) {
  28275. let weight = 0;
  28276. if ( this.enabled ) {
  28277. weight = this.weight;
  28278. const interpolant = this._weightInterpolant;
  28279. if ( interpolant !== null ) {
  28280. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28281. weight *= interpolantValue;
  28282. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28283. this.stopFading();
  28284. if ( interpolantValue === 0 ) {
  28285. // faded out, disable
  28286. this.enabled = false;
  28287. }
  28288. }
  28289. }
  28290. }
  28291. this._effectiveWeight = weight;
  28292. return weight;
  28293. }
  28294. _updateTimeScale( time ) {
  28295. let timeScale = 0;
  28296. if ( ! this.paused ) {
  28297. timeScale = this.timeScale;
  28298. const interpolant = this._timeScaleInterpolant;
  28299. if ( interpolant !== null ) {
  28300. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28301. timeScale *= interpolantValue;
  28302. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28303. this.stopWarping();
  28304. if ( timeScale === 0 ) {
  28305. // motion has halted, pause
  28306. this.paused = true;
  28307. } else {
  28308. // warp done - apply final time scale
  28309. this.timeScale = timeScale;
  28310. }
  28311. }
  28312. }
  28313. }
  28314. this._effectiveTimeScale = timeScale;
  28315. return timeScale;
  28316. }
  28317. _updateTime( deltaTime ) {
  28318. const duration = this._clip.duration;
  28319. const loop = this.loop;
  28320. let time = this.time + deltaTime;
  28321. let loopCount = this._loopCount;
  28322. const pingPong = ( loop === LoopPingPong );
  28323. if ( deltaTime === 0 ) {
  28324. if ( loopCount === - 1 ) return time;
  28325. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  28326. }
  28327. if ( loop === LoopOnce ) {
  28328. if ( loopCount === - 1 ) {
  28329. // just started
  28330. this._loopCount = 0;
  28331. this._setEndings( true, true, false );
  28332. }
  28333. handle_stop: {
  28334. if ( time >= duration ) {
  28335. time = duration;
  28336. } else if ( time < 0 ) {
  28337. time = 0;
  28338. } else {
  28339. this.time = time;
  28340. break handle_stop;
  28341. }
  28342. if ( this.clampWhenFinished ) this.paused = true;
  28343. else this.enabled = false;
  28344. this.time = time;
  28345. this._mixer.dispatchEvent( {
  28346. type: 'finished', action: this,
  28347. direction: deltaTime < 0 ? - 1 : 1
  28348. } );
  28349. }
  28350. } else { // repetitive Repeat or PingPong
  28351. if ( loopCount === - 1 ) {
  28352. // just started
  28353. if ( deltaTime >= 0 ) {
  28354. loopCount = 0;
  28355. this._setEndings( true, this.repetitions === 0, pingPong );
  28356. } else {
  28357. // when looping in reverse direction, the initial
  28358. // transition through zero counts as a repetition,
  28359. // so leave loopCount at -1
  28360. this._setEndings( this.repetitions === 0, true, pingPong );
  28361. }
  28362. }
  28363. if ( time >= duration || time < 0 ) {
  28364. // wrap around
  28365. const loopDelta = Math.floor( time / duration ); // signed
  28366. time -= duration * loopDelta;
  28367. loopCount += Math.abs( loopDelta );
  28368. const pending = this.repetitions - loopCount;
  28369. if ( pending <= 0 ) {
  28370. // have to stop (switch state, clamp time, fire event)
  28371. if ( this.clampWhenFinished ) this.paused = true;
  28372. else this.enabled = false;
  28373. time = deltaTime > 0 ? duration : 0;
  28374. this.time = time;
  28375. this._mixer.dispatchEvent( {
  28376. type: 'finished', action: this,
  28377. direction: deltaTime > 0 ? 1 : - 1
  28378. } );
  28379. } else {
  28380. // keep running
  28381. if ( pending === 1 ) {
  28382. // entering the last round
  28383. const atStart = deltaTime < 0;
  28384. this._setEndings( atStart, ! atStart, pingPong );
  28385. } else {
  28386. this._setEndings( false, false, pingPong );
  28387. }
  28388. this._loopCount = loopCount;
  28389. this.time = time;
  28390. this._mixer.dispatchEvent( {
  28391. type: 'loop', action: this, loopDelta: loopDelta
  28392. } );
  28393. }
  28394. } else {
  28395. this.time = time;
  28396. }
  28397. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28398. // invert time for the "pong round"
  28399. return duration - time;
  28400. }
  28401. }
  28402. return time;
  28403. }
  28404. _setEndings( atStart, atEnd, pingPong ) {
  28405. const settings = this._interpolantSettings;
  28406. if ( pingPong ) {
  28407. settings.endingStart = ZeroSlopeEnding;
  28408. settings.endingEnd = ZeroSlopeEnding;
  28409. } else {
  28410. // assuming for LoopOnce atStart == atEnd == true
  28411. if ( atStart ) {
  28412. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28413. } else {
  28414. settings.endingStart = WrapAroundEnding;
  28415. }
  28416. if ( atEnd ) {
  28417. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28418. } else {
  28419. settings.endingEnd = WrapAroundEnding;
  28420. }
  28421. }
  28422. }
  28423. _scheduleFading( duration, weightNow, weightThen ) {
  28424. const mixer = this._mixer, now = mixer.time;
  28425. let interpolant = this._weightInterpolant;
  28426. if ( interpolant === null ) {
  28427. interpolant = mixer._lendControlInterpolant();
  28428. this._weightInterpolant = interpolant;
  28429. }
  28430. const times = interpolant.parameterPositions,
  28431. values = interpolant.sampleValues;
  28432. times[ 0 ] = now;
  28433. values[ 0 ] = weightNow;
  28434. times[ 1 ] = now + duration;
  28435. values[ 1 ] = weightThen;
  28436. return this;
  28437. }
  28438. }
  28439. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  28440. class AnimationMixer extends EventDispatcher {
  28441. constructor( root ) {
  28442. super();
  28443. this._root = root;
  28444. this._initMemoryManager();
  28445. this._accuIndex = 0;
  28446. this.time = 0;
  28447. this.timeScale = 1.0;
  28448. }
  28449. _bindAction( action, prototypeAction ) {
  28450. const root = action._localRoot || this._root,
  28451. tracks = action._clip.tracks,
  28452. nTracks = tracks.length,
  28453. bindings = action._propertyBindings,
  28454. interpolants = action._interpolants,
  28455. rootUuid = root.uuid,
  28456. bindingsByRoot = this._bindingsByRootAndName;
  28457. let bindingsByName = bindingsByRoot[ rootUuid ];
  28458. if ( bindingsByName === undefined ) {
  28459. bindingsByName = {};
  28460. bindingsByRoot[ rootUuid ] = bindingsByName;
  28461. }
  28462. for ( let i = 0; i !== nTracks; ++ i ) {
  28463. const track = tracks[ i ],
  28464. trackName = track.name;
  28465. let binding = bindingsByName[ trackName ];
  28466. if ( binding !== undefined ) {
  28467. ++ binding.referenceCount;
  28468. bindings[ i ] = binding;
  28469. } else {
  28470. binding = bindings[ i ];
  28471. if ( binding !== undefined ) {
  28472. // existing binding, make sure the cache knows
  28473. if ( binding._cacheIndex === null ) {
  28474. ++ binding.referenceCount;
  28475. this._addInactiveBinding( binding, rootUuid, trackName );
  28476. }
  28477. continue;
  28478. }
  28479. const path = prototypeAction && prototypeAction.
  28480. _propertyBindings[ i ].binding.parsedPath;
  28481. binding = new PropertyMixer(
  28482. PropertyBinding.create( root, trackName, path ),
  28483. track.ValueTypeName, track.getValueSize() );
  28484. ++ binding.referenceCount;
  28485. this._addInactiveBinding( binding, rootUuid, trackName );
  28486. bindings[ i ] = binding;
  28487. }
  28488. interpolants[ i ].resultBuffer = binding.buffer;
  28489. }
  28490. }
  28491. _activateAction( action ) {
  28492. if ( ! this._isActiveAction( action ) ) {
  28493. if ( action._cacheIndex === null ) {
  28494. // this action has been forgotten by the cache, but the user
  28495. // appears to be still using it -> rebind
  28496. const rootUuid = ( action._localRoot || this._root ).uuid,
  28497. clipUuid = action._clip.uuid,
  28498. actionsForClip = this._actionsByClip[ clipUuid ];
  28499. this._bindAction( action,
  28500. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28501. this._addInactiveAction( action, clipUuid, rootUuid );
  28502. }
  28503. const bindings = action._propertyBindings;
  28504. // increment reference counts / sort out state
  28505. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28506. const binding = bindings[ i ];
  28507. if ( binding.useCount ++ === 0 ) {
  28508. this._lendBinding( binding );
  28509. binding.saveOriginalState();
  28510. }
  28511. }
  28512. this._lendAction( action );
  28513. }
  28514. }
  28515. _deactivateAction( action ) {
  28516. if ( this._isActiveAction( action ) ) {
  28517. const bindings = action._propertyBindings;
  28518. // decrement reference counts / sort out state
  28519. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28520. const binding = bindings[ i ];
  28521. if ( -- binding.useCount === 0 ) {
  28522. binding.restoreOriginalState();
  28523. this._takeBackBinding( binding );
  28524. }
  28525. }
  28526. this._takeBackAction( action );
  28527. }
  28528. }
  28529. // Memory manager
  28530. _initMemoryManager() {
  28531. this._actions = []; // 'nActiveActions' followed by inactive ones
  28532. this._nActiveActions = 0;
  28533. this._actionsByClip = {};
  28534. // inside:
  28535. // {
  28536. // knownActions: Array< AnimationAction > - used as prototypes
  28537. // actionByRoot: AnimationAction - lookup
  28538. // }
  28539. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28540. this._nActiveBindings = 0;
  28541. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28542. this._controlInterpolants = []; // same game as above
  28543. this._nActiveControlInterpolants = 0;
  28544. const scope = this;
  28545. this.stats = {
  28546. actions: {
  28547. get total() {
  28548. return scope._actions.length;
  28549. },
  28550. get inUse() {
  28551. return scope._nActiveActions;
  28552. }
  28553. },
  28554. bindings: {
  28555. get total() {
  28556. return scope._bindings.length;
  28557. },
  28558. get inUse() {
  28559. return scope._nActiveBindings;
  28560. }
  28561. },
  28562. controlInterpolants: {
  28563. get total() {
  28564. return scope._controlInterpolants.length;
  28565. },
  28566. get inUse() {
  28567. return scope._nActiveControlInterpolants;
  28568. }
  28569. }
  28570. };
  28571. }
  28572. // Memory management for AnimationAction objects
  28573. _isActiveAction( action ) {
  28574. const index = action._cacheIndex;
  28575. return index !== null && index < this._nActiveActions;
  28576. }
  28577. _addInactiveAction( action, clipUuid, rootUuid ) {
  28578. const actions = this._actions,
  28579. actionsByClip = this._actionsByClip;
  28580. let actionsForClip = actionsByClip[ clipUuid ];
  28581. if ( actionsForClip === undefined ) {
  28582. actionsForClip = {
  28583. knownActions: [ action ],
  28584. actionByRoot: {}
  28585. };
  28586. action._byClipCacheIndex = 0;
  28587. actionsByClip[ clipUuid ] = actionsForClip;
  28588. } else {
  28589. const knownActions = actionsForClip.knownActions;
  28590. action._byClipCacheIndex = knownActions.length;
  28591. knownActions.push( action );
  28592. }
  28593. action._cacheIndex = actions.length;
  28594. actions.push( action );
  28595. actionsForClip.actionByRoot[ rootUuid ] = action;
  28596. }
  28597. _removeInactiveAction( action ) {
  28598. const actions = this._actions,
  28599. lastInactiveAction = actions[ actions.length - 1 ],
  28600. cacheIndex = action._cacheIndex;
  28601. lastInactiveAction._cacheIndex = cacheIndex;
  28602. actions[ cacheIndex ] = lastInactiveAction;
  28603. actions.pop();
  28604. action._cacheIndex = null;
  28605. const clipUuid = action._clip.uuid,
  28606. actionsByClip = this._actionsByClip,
  28607. actionsForClip = actionsByClip[ clipUuid ],
  28608. knownActionsForClip = actionsForClip.knownActions,
  28609. lastKnownAction =
  28610. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28611. byClipCacheIndex = action._byClipCacheIndex;
  28612. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28613. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28614. knownActionsForClip.pop();
  28615. action._byClipCacheIndex = null;
  28616. const actionByRoot = actionsForClip.actionByRoot,
  28617. rootUuid = ( action._localRoot || this._root ).uuid;
  28618. delete actionByRoot[ rootUuid ];
  28619. if ( knownActionsForClip.length === 0 ) {
  28620. delete actionsByClip[ clipUuid ];
  28621. }
  28622. this._removeInactiveBindingsForAction( action );
  28623. }
  28624. _removeInactiveBindingsForAction( action ) {
  28625. const bindings = action._propertyBindings;
  28626. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28627. const binding = bindings[ i ];
  28628. if ( -- binding.referenceCount === 0 ) {
  28629. this._removeInactiveBinding( binding );
  28630. }
  28631. }
  28632. }
  28633. _lendAction( action ) {
  28634. // [ active actions | inactive actions ]
  28635. // [ active actions >| inactive actions ]
  28636. // s a
  28637. // <-swap->
  28638. // a s
  28639. const actions = this._actions,
  28640. prevIndex = action._cacheIndex,
  28641. lastActiveIndex = this._nActiveActions ++,
  28642. firstInactiveAction = actions[ lastActiveIndex ];
  28643. action._cacheIndex = lastActiveIndex;
  28644. actions[ lastActiveIndex ] = action;
  28645. firstInactiveAction._cacheIndex = prevIndex;
  28646. actions[ prevIndex ] = firstInactiveAction;
  28647. }
  28648. _takeBackAction( action ) {
  28649. // [ active actions | inactive actions ]
  28650. // [ active actions |< inactive actions ]
  28651. // a s
  28652. // <-swap->
  28653. // s a
  28654. const actions = this._actions,
  28655. prevIndex = action._cacheIndex,
  28656. firstInactiveIndex = -- this._nActiveActions,
  28657. lastActiveAction = actions[ firstInactiveIndex ];
  28658. action._cacheIndex = firstInactiveIndex;
  28659. actions[ firstInactiveIndex ] = action;
  28660. lastActiveAction._cacheIndex = prevIndex;
  28661. actions[ prevIndex ] = lastActiveAction;
  28662. }
  28663. // Memory management for PropertyMixer objects
  28664. _addInactiveBinding( binding, rootUuid, trackName ) {
  28665. const bindingsByRoot = this._bindingsByRootAndName,
  28666. bindings = this._bindings;
  28667. let bindingByName = bindingsByRoot[ rootUuid ];
  28668. if ( bindingByName === undefined ) {
  28669. bindingByName = {};
  28670. bindingsByRoot[ rootUuid ] = bindingByName;
  28671. }
  28672. bindingByName[ trackName ] = binding;
  28673. binding._cacheIndex = bindings.length;
  28674. bindings.push( binding );
  28675. }
  28676. _removeInactiveBinding( binding ) {
  28677. const bindings = this._bindings,
  28678. propBinding = binding.binding,
  28679. rootUuid = propBinding.rootNode.uuid,
  28680. trackName = propBinding.path,
  28681. bindingsByRoot = this._bindingsByRootAndName,
  28682. bindingByName = bindingsByRoot[ rootUuid ],
  28683. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28684. cacheIndex = binding._cacheIndex;
  28685. lastInactiveBinding._cacheIndex = cacheIndex;
  28686. bindings[ cacheIndex ] = lastInactiveBinding;
  28687. bindings.pop();
  28688. delete bindingByName[ trackName ];
  28689. if ( Object.keys( bindingByName ).length === 0 ) {
  28690. delete bindingsByRoot[ rootUuid ];
  28691. }
  28692. }
  28693. _lendBinding( binding ) {
  28694. const bindings = this._bindings,
  28695. prevIndex = binding._cacheIndex,
  28696. lastActiveIndex = this._nActiveBindings ++,
  28697. firstInactiveBinding = bindings[ lastActiveIndex ];
  28698. binding._cacheIndex = lastActiveIndex;
  28699. bindings[ lastActiveIndex ] = binding;
  28700. firstInactiveBinding._cacheIndex = prevIndex;
  28701. bindings[ prevIndex ] = firstInactiveBinding;
  28702. }
  28703. _takeBackBinding( binding ) {
  28704. const bindings = this._bindings,
  28705. prevIndex = binding._cacheIndex,
  28706. firstInactiveIndex = -- this._nActiveBindings,
  28707. lastActiveBinding = bindings[ firstInactiveIndex ];
  28708. binding._cacheIndex = firstInactiveIndex;
  28709. bindings[ firstInactiveIndex ] = binding;
  28710. lastActiveBinding._cacheIndex = prevIndex;
  28711. bindings[ prevIndex ] = lastActiveBinding;
  28712. }
  28713. // Memory management of Interpolants for weight and time scale
  28714. _lendControlInterpolant() {
  28715. const interpolants = this._controlInterpolants,
  28716. lastActiveIndex = this._nActiveControlInterpolants ++;
  28717. let interpolant = interpolants[ lastActiveIndex ];
  28718. if ( interpolant === undefined ) {
  28719. interpolant = new LinearInterpolant(
  28720. new Float32Array( 2 ), new Float32Array( 2 ),
  28721. 1, _controlInterpolantsResultBuffer );
  28722. interpolant.__cacheIndex = lastActiveIndex;
  28723. interpolants[ lastActiveIndex ] = interpolant;
  28724. }
  28725. return interpolant;
  28726. }
  28727. _takeBackControlInterpolant( interpolant ) {
  28728. const interpolants = this._controlInterpolants,
  28729. prevIndex = interpolant.__cacheIndex,
  28730. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28731. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28732. interpolant.__cacheIndex = firstInactiveIndex;
  28733. interpolants[ firstInactiveIndex ] = interpolant;
  28734. lastActiveInterpolant.__cacheIndex = prevIndex;
  28735. interpolants[ prevIndex ] = lastActiveInterpolant;
  28736. }
  28737. // return an action for a clip optionally using a custom root target
  28738. // object (this method allocates a lot of dynamic memory in case a
  28739. // previously unknown clip/root combination is specified)
  28740. clipAction( clip, optionalRoot, blendMode ) {
  28741. const root = optionalRoot || this._root,
  28742. rootUuid = root.uuid;
  28743. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28744. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28745. const actionsForClip = this._actionsByClip[ clipUuid ];
  28746. let prototypeAction = null;
  28747. if ( blendMode === undefined ) {
  28748. if ( clipObject !== null ) {
  28749. blendMode = clipObject.blendMode;
  28750. } else {
  28751. blendMode = NormalAnimationBlendMode;
  28752. }
  28753. }
  28754. if ( actionsForClip !== undefined ) {
  28755. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28756. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28757. return existingAction;
  28758. }
  28759. // we know the clip, so we don't have to parse all
  28760. // the bindings again but can just copy
  28761. prototypeAction = actionsForClip.knownActions[ 0 ];
  28762. // also, take the clip from the prototype action
  28763. if ( clipObject === null )
  28764. clipObject = prototypeAction._clip;
  28765. }
  28766. // clip must be known when specified via string
  28767. if ( clipObject === null ) return null;
  28768. // allocate all resources required to run it
  28769. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28770. this._bindAction( newAction, prototypeAction );
  28771. // and make the action known to the memory manager
  28772. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28773. return newAction;
  28774. }
  28775. // get an existing action
  28776. existingAction( clip, optionalRoot ) {
  28777. const root = optionalRoot || this._root,
  28778. rootUuid = root.uuid,
  28779. clipObject = typeof clip === 'string' ?
  28780. AnimationClip.findByName( root, clip ) : clip,
  28781. clipUuid = clipObject ? clipObject.uuid : clip,
  28782. actionsForClip = this._actionsByClip[ clipUuid ];
  28783. if ( actionsForClip !== undefined ) {
  28784. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28785. }
  28786. return null;
  28787. }
  28788. // deactivates all previously scheduled actions
  28789. stopAllAction() {
  28790. const actions = this._actions,
  28791. nActions = this._nActiveActions;
  28792. for ( let i = nActions - 1; i >= 0; -- i ) {
  28793. actions[ i ].stop();
  28794. }
  28795. return this;
  28796. }
  28797. // advance the time and update apply the animation
  28798. update( deltaTime ) {
  28799. deltaTime *= this.timeScale;
  28800. const actions = this._actions,
  28801. nActions = this._nActiveActions,
  28802. time = this.time += deltaTime,
  28803. timeDirection = Math.sign( deltaTime ),
  28804. accuIndex = this._accuIndex ^= 1;
  28805. // run active actions
  28806. for ( let i = 0; i !== nActions; ++ i ) {
  28807. const action = actions[ i ];
  28808. action._update( time, deltaTime, timeDirection, accuIndex );
  28809. }
  28810. // update scene graph
  28811. const bindings = this._bindings,
  28812. nBindings = this._nActiveBindings;
  28813. for ( let i = 0; i !== nBindings; ++ i ) {
  28814. bindings[ i ].apply( accuIndex );
  28815. }
  28816. return this;
  28817. }
  28818. // Allows you to seek to a specific time in an animation.
  28819. setTime( timeInSeconds ) {
  28820. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28821. for ( let i = 0; i < this._actions.length; i ++ ) {
  28822. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28823. }
  28824. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28825. }
  28826. // return this mixer's root target object
  28827. getRoot() {
  28828. return this._root;
  28829. }
  28830. // free all resources specific to a particular clip
  28831. uncacheClip( clip ) {
  28832. const actions = this._actions,
  28833. clipUuid = clip.uuid,
  28834. actionsByClip = this._actionsByClip,
  28835. actionsForClip = actionsByClip[ clipUuid ];
  28836. if ( actionsForClip !== undefined ) {
  28837. // note: just calling _removeInactiveAction would mess up the
  28838. // iteration state and also require updating the state we can
  28839. // just throw away
  28840. const actionsToRemove = actionsForClip.knownActions;
  28841. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28842. const action = actionsToRemove[ i ];
  28843. this._deactivateAction( action );
  28844. const cacheIndex = action._cacheIndex,
  28845. lastInactiveAction = actions[ actions.length - 1 ];
  28846. action._cacheIndex = null;
  28847. action._byClipCacheIndex = null;
  28848. lastInactiveAction._cacheIndex = cacheIndex;
  28849. actions[ cacheIndex ] = lastInactiveAction;
  28850. actions.pop();
  28851. this._removeInactiveBindingsForAction( action );
  28852. }
  28853. delete actionsByClip[ clipUuid ];
  28854. }
  28855. }
  28856. // free all resources specific to a particular root target object
  28857. uncacheRoot( root ) {
  28858. const rootUuid = root.uuid,
  28859. actionsByClip = this._actionsByClip;
  28860. for ( const clipUuid in actionsByClip ) {
  28861. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28862. action = actionByRoot[ rootUuid ];
  28863. if ( action !== undefined ) {
  28864. this._deactivateAction( action );
  28865. this._removeInactiveAction( action );
  28866. }
  28867. }
  28868. const bindingsByRoot = this._bindingsByRootAndName,
  28869. bindingByName = bindingsByRoot[ rootUuid ];
  28870. if ( bindingByName !== undefined ) {
  28871. for ( const trackName in bindingByName ) {
  28872. const binding = bindingByName[ trackName ];
  28873. binding.restoreOriginalState();
  28874. this._removeInactiveBinding( binding );
  28875. }
  28876. }
  28877. }
  28878. // remove a targeted clip from the cache
  28879. uncacheAction( clip, optionalRoot ) {
  28880. const action = this.existingAction( clip, optionalRoot );
  28881. if ( action !== null ) {
  28882. this._deactivateAction( action );
  28883. this._removeInactiveAction( action );
  28884. }
  28885. }
  28886. }
  28887. class Uniform {
  28888. constructor( value ) {
  28889. this.value = value;
  28890. }
  28891. clone() {
  28892. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28893. }
  28894. }
  28895. let id = 0;
  28896. class UniformsGroup extends EventDispatcher {
  28897. constructor() {
  28898. super();
  28899. this.isUniformsGroup = true;
  28900. Object.defineProperty( this, 'id', { value: id ++ } );
  28901. this.name = '';
  28902. this.usage = StaticDrawUsage;
  28903. this.uniforms = [];
  28904. }
  28905. add( uniform ) {
  28906. this.uniforms.push( uniform );
  28907. return this;
  28908. }
  28909. remove( uniform ) {
  28910. const index = this.uniforms.indexOf( uniform );
  28911. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28912. return this;
  28913. }
  28914. setName( name ) {
  28915. this.name = name;
  28916. return this;
  28917. }
  28918. setUsage( value ) {
  28919. this.usage = value;
  28920. return this;
  28921. }
  28922. dispose() {
  28923. this.dispatchEvent( { type: 'dispose' } );
  28924. return this;
  28925. }
  28926. copy( source ) {
  28927. this.name = source.name;
  28928. this.usage = source.usage;
  28929. const uniformsSource = source.uniforms;
  28930. this.uniforms.length = 0;
  28931. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28932. this.uniforms.push( uniformsSource[ i ].clone() );
  28933. }
  28934. return this;
  28935. }
  28936. clone() {
  28937. return new this.constructor().copy( this );
  28938. }
  28939. }
  28940. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28941. constructor( array, stride, meshPerAttribute = 1 ) {
  28942. super( array, stride );
  28943. this.isInstancedInterleavedBuffer = true;
  28944. this.meshPerAttribute = meshPerAttribute;
  28945. }
  28946. copy( source ) {
  28947. super.copy( source );
  28948. this.meshPerAttribute = source.meshPerAttribute;
  28949. return this;
  28950. }
  28951. clone( data ) {
  28952. const ib = super.clone( data );
  28953. ib.meshPerAttribute = this.meshPerAttribute;
  28954. return ib;
  28955. }
  28956. toJSON( data ) {
  28957. const json = super.toJSON( data );
  28958. json.isInstancedInterleavedBuffer = true;
  28959. json.meshPerAttribute = this.meshPerAttribute;
  28960. return json;
  28961. }
  28962. }
  28963. class GLBufferAttribute {
  28964. constructor( buffer, type, itemSize, elementSize, count ) {
  28965. this.isGLBufferAttribute = true;
  28966. this.name = '';
  28967. this.buffer = buffer;
  28968. this.type = type;
  28969. this.itemSize = itemSize;
  28970. this.elementSize = elementSize;
  28971. this.count = count;
  28972. this.version = 0;
  28973. }
  28974. set needsUpdate( value ) {
  28975. if ( value === true ) this.version ++;
  28976. }
  28977. setBuffer( buffer ) {
  28978. this.buffer = buffer;
  28979. return this;
  28980. }
  28981. setType( type, elementSize ) {
  28982. this.type = type;
  28983. this.elementSize = elementSize;
  28984. return this;
  28985. }
  28986. setItemSize( itemSize ) {
  28987. this.itemSize = itemSize;
  28988. return this;
  28989. }
  28990. setCount( count ) {
  28991. this.count = count;
  28992. return this;
  28993. }
  28994. }
  28995. class Raycaster {
  28996. constructor( origin, direction, near = 0, far = Infinity ) {
  28997. this.ray = new Ray( origin, direction );
  28998. // direction is assumed to be normalized (for accurate distance calculations)
  28999. this.near = near;
  29000. this.far = far;
  29001. this.camera = null;
  29002. this.layers = new Layers();
  29003. this.params = {
  29004. Mesh: {},
  29005. Line: { threshold: 1 },
  29006. LOD: {},
  29007. Points: { threshold: 1 },
  29008. Sprite: {}
  29009. };
  29010. }
  29011. set( origin, direction ) {
  29012. // direction is assumed to be normalized (for accurate distance calculations)
  29013. this.ray.set( origin, direction );
  29014. }
  29015. setFromCamera( coords, camera ) {
  29016. if ( camera.isPerspectiveCamera ) {
  29017. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  29018. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  29019. this.camera = camera;
  29020. } else if ( camera.isOrthographicCamera ) {
  29021. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  29022. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  29023. this.camera = camera;
  29024. } else {
  29025. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  29026. }
  29027. }
  29028. intersectObject( object, recursive = true, intersects = [] ) {
  29029. intersectObject( object, this, intersects, recursive );
  29030. intersects.sort( ascSort );
  29031. return intersects;
  29032. }
  29033. intersectObjects( objects, recursive = true, intersects = [] ) {
  29034. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  29035. intersectObject( objects[ i ], this, intersects, recursive );
  29036. }
  29037. intersects.sort( ascSort );
  29038. return intersects;
  29039. }
  29040. }
  29041. function ascSort( a, b ) {
  29042. return a.distance - b.distance;
  29043. }
  29044. function intersectObject( object, raycaster, intersects, recursive ) {
  29045. if ( object.layers.test( raycaster.layers ) ) {
  29046. object.raycast( raycaster, intersects );
  29047. }
  29048. if ( recursive === true ) {
  29049. const children = object.children;
  29050. for ( let i = 0, l = children.length; i < l; i ++ ) {
  29051. intersectObject( children[ i ], raycaster, intersects, true );
  29052. }
  29053. }
  29054. }
  29055. /**
  29056. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  29057. *
  29058. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  29059. * The azimuthal angle (theta) is measured from the positive z-axis.
  29060. */
  29061. class Spherical {
  29062. constructor( radius = 1, phi = 0, theta = 0 ) {
  29063. this.radius = radius;
  29064. this.phi = phi; // polar angle
  29065. this.theta = theta; // azimuthal angle
  29066. return this;
  29067. }
  29068. set( radius, phi, theta ) {
  29069. this.radius = radius;
  29070. this.phi = phi;
  29071. this.theta = theta;
  29072. return this;
  29073. }
  29074. copy( other ) {
  29075. this.radius = other.radius;
  29076. this.phi = other.phi;
  29077. this.theta = other.theta;
  29078. return this;
  29079. }
  29080. // restrict phi to be between EPS and PI-EPS
  29081. makeSafe() {
  29082. const EPS = 0.000001;
  29083. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  29084. return this;
  29085. }
  29086. setFromVector3( v ) {
  29087. return this.setFromCartesianCoords( v.x, v.y, v.z );
  29088. }
  29089. setFromCartesianCoords( x, y, z ) {
  29090. this.radius = Math.sqrt( x * x + y * y + z * z );
  29091. if ( this.radius === 0 ) {
  29092. this.theta = 0;
  29093. this.phi = 0;
  29094. } else {
  29095. this.theta = Math.atan2( x, z );
  29096. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  29097. }
  29098. return this;
  29099. }
  29100. clone() {
  29101. return new this.constructor().copy( this );
  29102. }
  29103. }
  29104. /**
  29105. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  29106. */
  29107. class Cylindrical {
  29108. constructor( radius = 1, theta = 0, y = 0 ) {
  29109. this.radius = radius; // distance from the origin to a point in the x-z plane
  29110. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  29111. this.y = y; // height above the x-z plane
  29112. return this;
  29113. }
  29114. set( radius, theta, y ) {
  29115. this.radius = radius;
  29116. this.theta = theta;
  29117. this.y = y;
  29118. return this;
  29119. }
  29120. copy( other ) {
  29121. this.radius = other.radius;
  29122. this.theta = other.theta;
  29123. this.y = other.y;
  29124. return this;
  29125. }
  29126. setFromVector3( v ) {
  29127. return this.setFromCartesianCoords( v.x, v.y, v.z );
  29128. }
  29129. setFromCartesianCoords( x, y, z ) {
  29130. this.radius = Math.sqrt( x * x + z * z );
  29131. this.theta = Math.atan2( x, z );
  29132. this.y = y;
  29133. return this;
  29134. }
  29135. clone() {
  29136. return new this.constructor().copy( this );
  29137. }
  29138. }
  29139. const _vector$4 = /*@__PURE__*/ new Vector2();
  29140. class Box2 {
  29141. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  29142. this.isBox2 = true;
  29143. this.min = min;
  29144. this.max = max;
  29145. }
  29146. set( min, max ) {
  29147. this.min.copy( min );
  29148. this.max.copy( max );
  29149. return this;
  29150. }
  29151. setFromPoints( points ) {
  29152. this.makeEmpty();
  29153. for ( let i = 0, il = points.length; i < il; i ++ ) {
  29154. this.expandByPoint( points[ i ] );
  29155. }
  29156. return this;
  29157. }
  29158. setFromCenterAndSize( center, size ) {
  29159. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  29160. this.min.copy( center ).sub( halfSize );
  29161. this.max.copy( center ).add( halfSize );
  29162. return this;
  29163. }
  29164. clone() {
  29165. return new this.constructor().copy( this );
  29166. }
  29167. copy( box ) {
  29168. this.min.copy( box.min );
  29169. this.max.copy( box.max );
  29170. return this;
  29171. }
  29172. makeEmpty() {
  29173. this.min.x = this.min.y = + Infinity;
  29174. this.max.x = this.max.y = - Infinity;
  29175. return this;
  29176. }
  29177. isEmpty() {
  29178. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  29179. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  29180. }
  29181. getCenter( target ) {
  29182. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  29183. }
  29184. getSize( target ) {
  29185. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  29186. }
  29187. expandByPoint( point ) {
  29188. this.min.min( point );
  29189. this.max.max( point );
  29190. return this;
  29191. }
  29192. expandByVector( vector ) {
  29193. this.min.sub( vector );
  29194. this.max.add( vector );
  29195. return this;
  29196. }
  29197. expandByScalar( scalar ) {
  29198. this.min.addScalar( - scalar );
  29199. this.max.addScalar( scalar );
  29200. return this;
  29201. }
  29202. containsPoint( point ) {
  29203. return point.x < this.min.x || point.x > this.max.x ||
  29204. point.y < this.min.y || point.y > this.max.y ? false : true;
  29205. }
  29206. containsBox( box ) {
  29207. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  29208. this.min.y <= box.min.y && box.max.y <= this.max.y;
  29209. }
  29210. getParameter( point, target ) {
  29211. // This can potentially have a divide by zero if the box
  29212. // has a size dimension of 0.
  29213. return target.set(
  29214. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  29215. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  29216. );
  29217. }
  29218. intersectsBox( box ) {
  29219. // using 4 splitting planes to rule out intersections
  29220. return box.max.x < this.min.x || box.min.x > this.max.x ||
  29221. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  29222. }
  29223. clampPoint( point, target ) {
  29224. return target.copy( point ).clamp( this.min, this.max );
  29225. }
  29226. distanceToPoint( point ) {
  29227. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  29228. }
  29229. intersect( box ) {
  29230. this.min.max( box.min );
  29231. this.max.min( box.max );
  29232. if ( this.isEmpty() ) this.makeEmpty();
  29233. return this;
  29234. }
  29235. union( box ) {
  29236. this.min.min( box.min );
  29237. this.max.max( box.max );
  29238. return this;
  29239. }
  29240. translate( offset ) {
  29241. this.min.add( offset );
  29242. this.max.add( offset );
  29243. return this;
  29244. }
  29245. equals( box ) {
  29246. return box.min.equals( this.min ) && box.max.equals( this.max );
  29247. }
  29248. }
  29249. const _startP = /*@__PURE__*/ new Vector3();
  29250. const _startEnd = /*@__PURE__*/ new Vector3();
  29251. class Line3 {
  29252. constructor( start = new Vector3(), end = new Vector3() ) {
  29253. this.start = start;
  29254. this.end = end;
  29255. }
  29256. set( start, end ) {
  29257. this.start.copy( start );
  29258. this.end.copy( end );
  29259. return this;
  29260. }
  29261. copy( line ) {
  29262. this.start.copy( line.start );
  29263. this.end.copy( line.end );
  29264. return this;
  29265. }
  29266. getCenter( target ) {
  29267. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  29268. }
  29269. delta( target ) {
  29270. return target.subVectors( this.end, this.start );
  29271. }
  29272. distanceSq() {
  29273. return this.start.distanceToSquared( this.end );
  29274. }
  29275. distance() {
  29276. return this.start.distanceTo( this.end );
  29277. }
  29278. at( t, target ) {
  29279. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29280. }
  29281. closestPointToPointParameter( point, clampToLine ) {
  29282. _startP.subVectors( point, this.start );
  29283. _startEnd.subVectors( this.end, this.start );
  29284. const startEnd2 = _startEnd.dot( _startEnd );
  29285. const startEnd_startP = _startEnd.dot( _startP );
  29286. let t = startEnd_startP / startEnd2;
  29287. if ( clampToLine ) {
  29288. t = clamp( t, 0, 1 );
  29289. }
  29290. return t;
  29291. }
  29292. closestPointToPoint( point, clampToLine, target ) {
  29293. const t = this.closestPointToPointParameter( point, clampToLine );
  29294. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29295. }
  29296. applyMatrix4( matrix ) {
  29297. this.start.applyMatrix4( matrix );
  29298. this.end.applyMatrix4( matrix );
  29299. return this;
  29300. }
  29301. equals( line ) {
  29302. return line.start.equals( this.start ) && line.end.equals( this.end );
  29303. }
  29304. clone() {
  29305. return new this.constructor().copy( this );
  29306. }
  29307. }
  29308. const _vector$3 = /*@__PURE__*/ new Vector3();
  29309. class SpotLightHelper extends Object3D {
  29310. constructor( light, color ) {
  29311. super();
  29312. this.light = light;
  29313. this.matrix = light.matrixWorld;
  29314. this.matrixAutoUpdate = false;
  29315. this.color = color;
  29316. this.type = 'SpotLightHelper';
  29317. const geometry = new BufferGeometry();
  29318. const positions = [
  29319. 0, 0, 0, 0, 0, 1,
  29320. 0, 0, 0, 1, 0, 1,
  29321. 0, 0, 0, - 1, 0, 1,
  29322. 0, 0, 0, 0, 1, 1,
  29323. 0, 0, 0, 0, - 1, 1
  29324. ];
  29325. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  29326. const p1 = ( i / l ) * Math.PI * 2;
  29327. const p2 = ( j / l ) * Math.PI * 2;
  29328. positions.push(
  29329. Math.cos( p1 ), Math.sin( p1 ), 1,
  29330. Math.cos( p2 ), Math.sin( p2 ), 1
  29331. );
  29332. }
  29333. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29334. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29335. this.cone = new LineSegments( geometry, material );
  29336. this.add( this.cone );
  29337. this.update();
  29338. }
  29339. dispose() {
  29340. this.cone.geometry.dispose();
  29341. this.cone.material.dispose();
  29342. }
  29343. update() {
  29344. this.light.updateWorldMatrix( true, false );
  29345. this.light.target.updateWorldMatrix( true, false );
  29346. const coneLength = this.light.distance ? this.light.distance : 1000;
  29347. const coneWidth = coneLength * Math.tan( this.light.angle );
  29348. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  29349. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29350. this.cone.lookAt( _vector$3 );
  29351. if ( this.color !== undefined ) {
  29352. this.cone.material.color.set( this.color );
  29353. } else {
  29354. this.cone.material.color.copy( this.light.color );
  29355. }
  29356. }
  29357. }
  29358. const _vector$2 = /*@__PURE__*/ new Vector3();
  29359. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  29360. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  29361. class SkeletonHelper extends LineSegments {
  29362. constructor( object ) {
  29363. const bones = getBoneList( object );
  29364. const geometry = new BufferGeometry();
  29365. const vertices = [];
  29366. const colors = [];
  29367. const color1 = new Color( 0, 0, 1 );
  29368. const color2 = new Color( 0, 1, 0 );
  29369. for ( let i = 0; i < bones.length; i ++ ) {
  29370. const bone = bones[ i ];
  29371. if ( bone.parent && bone.parent.isBone ) {
  29372. vertices.push( 0, 0, 0 );
  29373. vertices.push( 0, 0, 0 );
  29374. colors.push( color1.r, color1.g, color1.b );
  29375. colors.push( color2.r, color2.g, color2.b );
  29376. }
  29377. }
  29378. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29379. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29380. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  29381. super( geometry, material );
  29382. this.isSkeletonHelper = true;
  29383. this.type = 'SkeletonHelper';
  29384. this.root = object;
  29385. this.bones = bones;
  29386. this.matrix = object.matrixWorld;
  29387. this.matrixAutoUpdate = false;
  29388. }
  29389. updateMatrixWorld( force ) {
  29390. const bones = this.bones;
  29391. const geometry = this.geometry;
  29392. const position = geometry.getAttribute( 'position' );
  29393. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29394. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29395. const bone = bones[ i ];
  29396. if ( bone.parent && bone.parent.isBone ) {
  29397. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29398. _vector$2.setFromMatrixPosition( _boneMatrix );
  29399. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29400. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29401. _vector$2.setFromMatrixPosition( _boneMatrix );
  29402. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29403. j += 2;
  29404. }
  29405. }
  29406. geometry.getAttribute( 'position' ).needsUpdate = true;
  29407. super.updateMatrixWorld( force );
  29408. }
  29409. dispose() {
  29410. this.geometry.dispose();
  29411. this.material.dispose();
  29412. }
  29413. }
  29414. function getBoneList( object ) {
  29415. const boneList = [];
  29416. if ( object.isBone === true ) {
  29417. boneList.push( object );
  29418. }
  29419. for ( let i = 0; i < object.children.length; i ++ ) {
  29420. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29421. }
  29422. return boneList;
  29423. }
  29424. class PointLightHelper extends Mesh {
  29425. constructor( light, sphereSize, color ) {
  29426. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29427. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29428. super( geometry, material );
  29429. this.light = light;
  29430. this.color = color;
  29431. this.type = 'PointLightHelper';
  29432. this.matrix = this.light.matrixWorld;
  29433. this.matrixAutoUpdate = false;
  29434. this.update();
  29435. /*
  29436. // TODO: delete this comment?
  29437. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  29438. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29439. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29440. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29441. const d = light.distance;
  29442. if ( d === 0.0 ) {
  29443. this.lightDistance.visible = false;
  29444. } else {
  29445. this.lightDistance.scale.set( d, d, d );
  29446. }
  29447. this.add( this.lightDistance );
  29448. */
  29449. }
  29450. dispose() {
  29451. this.geometry.dispose();
  29452. this.material.dispose();
  29453. }
  29454. update() {
  29455. this.light.updateWorldMatrix( true, false );
  29456. if ( this.color !== undefined ) {
  29457. this.material.color.set( this.color );
  29458. } else {
  29459. this.material.color.copy( this.light.color );
  29460. }
  29461. /*
  29462. const d = this.light.distance;
  29463. if ( d === 0.0 ) {
  29464. this.lightDistance.visible = false;
  29465. } else {
  29466. this.lightDistance.visible = true;
  29467. this.lightDistance.scale.set( d, d, d );
  29468. }
  29469. */
  29470. }
  29471. }
  29472. const _vector$1 = /*@__PURE__*/ new Vector3();
  29473. const _color1 = /*@__PURE__*/ new Color();
  29474. const _color2 = /*@__PURE__*/ new Color();
  29475. class HemisphereLightHelper extends Object3D {
  29476. constructor( light, size, color ) {
  29477. super();
  29478. this.light = light;
  29479. this.matrix = light.matrixWorld;
  29480. this.matrixAutoUpdate = false;
  29481. this.color = color;
  29482. this.type = 'HemisphereLightHelper';
  29483. const geometry = new OctahedronGeometry( size );
  29484. geometry.rotateY( Math.PI * 0.5 );
  29485. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29486. if ( this.color === undefined ) this.material.vertexColors = true;
  29487. const position = geometry.getAttribute( 'position' );
  29488. const colors = new Float32Array( position.count * 3 );
  29489. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29490. this.add( new Mesh( geometry, this.material ) );
  29491. this.update();
  29492. }
  29493. dispose() {
  29494. this.children[ 0 ].geometry.dispose();
  29495. this.children[ 0 ].material.dispose();
  29496. }
  29497. update() {
  29498. const mesh = this.children[ 0 ];
  29499. if ( this.color !== undefined ) {
  29500. this.material.color.set( this.color );
  29501. } else {
  29502. const colors = mesh.geometry.getAttribute( 'color' );
  29503. _color1.copy( this.light.color );
  29504. _color2.copy( this.light.groundColor );
  29505. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29506. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29507. colors.setXYZ( i, color.r, color.g, color.b );
  29508. }
  29509. colors.needsUpdate = true;
  29510. }
  29511. this.light.updateWorldMatrix( true, false );
  29512. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29513. }
  29514. }
  29515. class GridHelper extends LineSegments {
  29516. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29517. color1 = new Color( color1 );
  29518. color2 = new Color( color2 );
  29519. const center = divisions / 2;
  29520. const step = size / divisions;
  29521. const halfSize = size / 2;
  29522. const vertices = [], colors = [];
  29523. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29524. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29525. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29526. const color = i === center ? color1 : color2;
  29527. color.toArray( colors, j ); j += 3;
  29528. color.toArray( colors, j ); j += 3;
  29529. color.toArray( colors, j ); j += 3;
  29530. color.toArray( colors, j ); j += 3;
  29531. }
  29532. const geometry = new BufferGeometry();
  29533. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29534. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29535. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29536. super( geometry, material );
  29537. this.type = 'GridHelper';
  29538. }
  29539. dispose() {
  29540. this.geometry.dispose();
  29541. this.material.dispose();
  29542. }
  29543. }
  29544. class PolarGridHelper extends LineSegments {
  29545. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29546. color1 = new Color( color1 );
  29547. color2 = new Color( color2 );
  29548. const vertices = [];
  29549. const colors = [];
  29550. // create the sectors
  29551. if ( sectors > 1 ) {
  29552. for ( let i = 0; i < sectors; i ++ ) {
  29553. const v = ( i / sectors ) * ( Math.PI * 2 );
  29554. const x = Math.sin( v ) * radius;
  29555. const z = Math.cos( v ) * radius;
  29556. vertices.push( 0, 0, 0 );
  29557. vertices.push( x, 0, z );
  29558. const color = ( i & 1 ) ? color1 : color2;
  29559. colors.push( color.r, color.g, color.b );
  29560. colors.push( color.r, color.g, color.b );
  29561. }
  29562. }
  29563. // create the rings
  29564. for ( let i = 0; i < rings; i ++ ) {
  29565. const color = ( i & 1 ) ? color1 : color2;
  29566. const r = radius - ( radius / rings * i );
  29567. for ( let j = 0; j < divisions; j ++ ) {
  29568. // first vertex
  29569. let v = ( j / divisions ) * ( Math.PI * 2 );
  29570. let x = Math.sin( v ) * r;
  29571. let z = Math.cos( v ) * r;
  29572. vertices.push( x, 0, z );
  29573. colors.push( color.r, color.g, color.b );
  29574. // second vertex
  29575. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29576. x = Math.sin( v ) * r;
  29577. z = Math.cos( v ) * r;
  29578. vertices.push( x, 0, z );
  29579. colors.push( color.r, color.g, color.b );
  29580. }
  29581. }
  29582. const geometry = new BufferGeometry();
  29583. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29584. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29585. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29586. super( geometry, material );
  29587. this.type = 'PolarGridHelper';
  29588. }
  29589. dispose() {
  29590. this.geometry.dispose();
  29591. this.material.dispose();
  29592. }
  29593. }
  29594. const _v1 = /*@__PURE__*/ new Vector3();
  29595. const _v2 = /*@__PURE__*/ new Vector3();
  29596. const _v3 = /*@__PURE__*/ new Vector3();
  29597. class DirectionalLightHelper 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 = 'DirectionalLightHelper';
  29605. if ( size === undefined ) size = 1;
  29606. let geometry = new BufferGeometry();
  29607. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29608. - size, size, 0,
  29609. size, size, 0,
  29610. size, - size, 0,
  29611. - size, - size, 0,
  29612. - size, size, 0
  29613. ], 3 ) );
  29614. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29615. this.lightPlane = new Line( geometry, material );
  29616. this.add( this.lightPlane );
  29617. geometry = new BufferGeometry();
  29618. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29619. this.targetLine = new Line( geometry, material );
  29620. this.add( this.targetLine );
  29621. this.update();
  29622. }
  29623. dispose() {
  29624. this.lightPlane.geometry.dispose();
  29625. this.lightPlane.material.dispose();
  29626. this.targetLine.geometry.dispose();
  29627. this.targetLine.material.dispose();
  29628. }
  29629. update() {
  29630. this.light.updateWorldMatrix( true, false );
  29631. this.light.target.updateWorldMatrix( true, false );
  29632. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29633. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29634. _v3.subVectors( _v2, _v1 );
  29635. this.lightPlane.lookAt( _v2 );
  29636. if ( this.color !== undefined ) {
  29637. this.lightPlane.material.color.set( this.color );
  29638. this.targetLine.material.color.set( this.color );
  29639. } else {
  29640. this.lightPlane.material.color.copy( this.light.color );
  29641. this.targetLine.material.color.copy( this.light.color );
  29642. }
  29643. this.targetLine.lookAt( _v2 );
  29644. this.targetLine.scale.z = _v3.length();
  29645. }
  29646. }
  29647. const _vector = /*@__PURE__*/ new Vector3();
  29648. const _camera = /*@__PURE__*/ new Camera();
  29649. /**
  29650. * - shows frustum, line of sight and up of the camera
  29651. * - suitable for fast updates
  29652. * - based on frustum visualization in lightgl.js shadowmap example
  29653. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29654. */
  29655. class CameraHelper extends LineSegments {
  29656. constructor( camera ) {
  29657. const geometry = new BufferGeometry();
  29658. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29659. const vertices = [];
  29660. const colors = [];
  29661. const pointMap = {};
  29662. // near
  29663. addLine( 'n1', 'n2' );
  29664. addLine( 'n2', 'n4' );
  29665. addLine( 'n4', 'n3' );
  29666. addLine( 'n3', 'n1' );
  29667. // far
  29668. addLine( 'f1', 'f2' );
  29669. addLine( 'f2', 'f4' );
  29670. addLine( 'f4', 'f3' );
  29671. addLine( 'f3', 'f1' );
  29672. // sides
  29673. addLine( 'n1', 'f1' );
  29674. addLine( 'n2', 'f2' );
  29675. addLine( 'n3', 'f3' );
  29676. addLine( 'n4', 'f4' );
  29677. // cone
  29678. addLine( 'p', 'n1' );
  29679. addLine( 'p', 'n2' );
  29680. addLine( 'p', 'n3' );
  29681. addLine( 'p', 'n4' );
  29682. // up
  29683. addLine( 'u1', 'u2' );
  29684. addLine( 'u2', 'u3' );
  29685. addLine( 'u3', 'u1' );
  29686. // target
  29687. addLine( 'c', 't' );
  29688. addLine( 'p', 'c' );
  29689. // cross
  29690. addLine( 'cn1', 'cn2' );
  29691. addLine( 'cn3', 'cn4' );
  29692. addLine( 'cf1', 'cf2' );
  29693. addLine( 'cf3', 'cf4' );
  29694. function addLine( a, b ) {
  29695. addPoint( a );
  29696. addPoint( b );
  29697. }
  29698. function addPoint( id ) {
  29699. vertices.push( 0, 0, 0 );
  29700. colors.push( 0, 0, 0 );
  29701. if ( pointMap[ id ] === undefined ) {
  29702. pointMap[ id ] = [];
  29703. }
  29704. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29705. }
  29706. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29707. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29708. super( geometry, material );
  29709. this.type = 'CameraHelper';
  29710. this.camera = camera;
  29711. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29712. this.matrix = camera.matrixWorld;
  29713. this.matrixAutoUpdate = false;
  29714. this.pointMap = pointMap;
  29715. this.update();
  29716. // colors
  29717. const colorFrustum = new Color( 0xffaa00 );
  29718. const colorCone = new Color( 0xff0000 );
  29719. const colorUp = new Color( 0x00aaff );
  29720. const colorTarget = new Color( 0xffffff );
  29721. const colorCross = new Color( 0x333333 );
  29722. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29723. }
  29724. setColors( frustum, cone, up, target, cross ) {
  29725. const geometry = this.geometry;
  29726. const colorAttribute = geometry.getAttribute( 'color' );
  29727. // near
  29728. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29729. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29730. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29731. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29732. // far
  29733. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29734. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29735. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29736. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29737. // sides
  29738. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29739. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29740. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29741. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29742. // cone
  29743. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29744. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29745. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29746. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29747. // up
  29748. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29749. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29750. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29751. // target
  29752. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29753. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29754. // cross
  29755. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29756. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29757. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29758. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29759. colorAttribute.needsUpdate = true;
  29760. }
  29761. update() {
  29762. const geometry = this.geometry;
  29763. const pointMap = this.pointMap;
  29764. const w = 1, h = 1;
  29765. // we need just camera projection matrix inverse
  29766. // world matrix must be identity
  29767. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29768. // center / target
  29769. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29770. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29771. // near
  29772. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29773. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29774. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29775. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29776. // far
  29777. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29778. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29779. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29780. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29781. // up
  29782. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29783. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29784. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29785. // cross
  29786. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29787. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29788. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29789. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29790. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29791. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29792. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29793. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29794. geometry.getAttribute( 'position' ).needsUpdate = true;
  29795. }
  29796. dispose() {
  29797. this.geometry.dispose();
  29798. this.material.dispose();
  29799. }
  29800. }
  29801. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29802. _vector.set( x, y, z ).unproject( camera );
  29803. const points = pointMap[ point ];
  29804. if ( points !== undefined ) {
  29805. const position = geometry.getAttribute( 'position' );
  29806. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29807. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29808. }
  29809. }
  29810. }
  29811. const _box = /*@__PURE__*/ new Box3();
  29812. class BoxHelper extends LineSegments {
  29813. constructor( object, color = 0xffff00 ) {
  29814. 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 ] );
  29815. const positions = new Float32Array( 8 * 3 );
  29816. const geometry = new BufferGeometry();
  29817. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29818. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29819. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29820. this.object = object;
  29821. this.type = 'BoxHelper';
  29822. this.matrixAutoUpdate = false;
  29823. this.update();
  29824. }
  29825. update( object ) {
  29826. if ( object !== undefined ) {
  29827. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29828. }
  29829. if ( this.object !== undefined ) {
  29830. _box.setFromObject( this.object );
  29831. }
  29832. if ( _box.isEmpty() ) return;
  29833. const min = _box.min;
  29834. const max = _box.max;
  29835. /*
  29836. 5____4
  29837. 1/___0/|
  29838. | 6__|_7
  29839. 2/___3/
  29840. 0: max.x, max.y, max.z
  29841. 1: min.x, max.y, max.z
  29842. 2: min.x, min.y, max.z
  29843. 3: max.x, min.y, max.z
  29844. 4: max.x, max.y, min.z
  29845. 5: min.x, max.y, min.z
  29846. 6: min.x, min.y, min.z
  29847. 7: max.x, min.y, min.z
  29848. */
  29849. const position = this.geometry.attributes.position;
  29850. const array = position.array;
  29851. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29852. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29853. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29854. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29855. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29856. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29857. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29858. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29859. position.needsUpdate = true;
  29860. this.geometry.computeBoundingSphere();
  29861. }
  29862. setFromObject( object ) {
  29863. this.object = object;
  29864. this.update();
  29865. return this;
  29866. }
  29867. copy( source, recursive ) {
  29868. super.copy( source, recursive );
  29869. this.object = source.object;
  29870. return this;
  29871. }
  29872. dispose() {
  29873. this.geometry.dispose();
  29874. this.material.dispose();
  29875. }
  29876. }
  29877. class Box3Helper extends LineSegments {
  29878. constructor( box, color = 0xffff00 ) {
  29879. 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 ] );
  29880. 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 ];
  29881. const geometry = new BufferGeometry();
  29882. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29883. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29884. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29885. this.box = box;
  29886. this.type = 'Box3Helper';
  29887. this.geometry.computeBoundingSphere();
  29888. }
  29889. updateMatrixWorld( force ) {
  29890. const box = this.box;
  29891. if ( box.isEmpty() ) return;
  29892. box.getCenter( this.position );
  29893. box.getSize( this.scale );
  29894. this.scale.multiplyScalar( 0.5 );
  29895. super.updateMatrixWorld( force );
  29896. }
  29897. dispose() {
  29898. this.geometry.dispose();
  29899. this.material.dispose();
  29900. }
  29901. }
  29902. class PlaneHelper extends Line {
  29903. constructor( plane, size = 1, hex = 0xffff00 ) {
  29904. const color = hex;
  29905. 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 ];
  29906. const geometry = new BufferGeometry();
  29907. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29908. geometry.computeBoundingSphere();
  29909. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29910. this.type = 'PlaneHelper';
  29911. this.plane = plane;
  29912. this.size = size;
  29913. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29914. const geometry2 = new BufferGeometry();
  29915. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29916. geometry2.computeBoundingSphere();
  29917. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29918. }
  29919. updateMatrixWorld( force ) {
  29920. this.position.set( 0, 0, 0 );
  29921. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29922. this.lookAt( this.plane.normal );
  29923. this.translateZ( - this.plane.constant );
  29924. super.updateMatrixWorld( force );
  29925. }
  29926. dispose() {
  29927. this.geometry.dispose();
  29928. this.material.dispose();
  29929. this.children[ 0 ].geometry.dispose();
  29930. this.children[ 0 ].material.dispose();
  29931. }
  29932. }
  29933. const _axis = /*@__PURE__*/ new Vector3();
  29934. let _lineGeometry, _coneGeometry;
  29935. class ArrowHelper extends Object3D {
  29936. // dir is assumed to be normalized
  29937. 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 ) {
  29938. super();
  29939. this.type = 'ArrowHelper';
  29940. if ( _lineGeometry === undefined ) {
  29941. _lineGeometry = new BufferGeometry();
  29942. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29943. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29944. _coneGeometry.translate( 0, - 0.5, 0 );
  29945. }
  29946. this.position.copy( origin );
  29947. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29948. this.line.matrixAutoUpdate = false;
  29949. this.add( this.line );
  29950. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29951. this.cone.matrixAutoUpdate = false;
  29952. this.add( this.cone );
  29953. this.setDirection( dir );
  29954. this.setLength( length, headLength, headWidth );
  29955. }
  29956. setDirection( dir ) {
  29957. // dir is assumed to be normalized
  29958. if ( dir.y > 0.99999 ) {
  29959. this.quaternion.set( 0, 0, 0, 1 );
  29960. } else if ( dir.y < - 0.99999 ) {
  29961. this.quaternion.set( 1, 0, 0, 0 );
  29962. } else {
  29963. _axis.set( dir.z, 0, - dir.x ).normalize();
  29964. const radians = Math.acos( dir.y );
  29965. this.quaternion.setFromAxisAngle( _axis, radians );
  29966. }
  29967. }
  29968. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29969. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29970. this.line.updateMatrix();
  29971. this.cone.scale.set( headWidth, headLength, headWidth );
  29972. this.cone.position.y = length;
  29973. this.cone.updateMatrix();
  29974. }
  29975. setColor( color ) {
  29976. this.line.material.color.set( color );
  29977. this.cone.material.color.set( color );
  29978. }
  29979. copy( source ) {
  29980. super.copy( source, false );
  29981. this.line.copy( source.line );
  29982. this.cone.copy( source.cone );
  29983. return this;
  29984. }
  29985. dispose() {
  29986. this.line.geometry.dispose();
  29987. this.line.material.dispose();
  29988. this.cone.geometry.dispose();
  29989. this.cone.material.dispose();
  29990. }
  29991. }
  29992. class AxesHelper extends LineSegments {
  29993. constructor( size = 1 ) {
  29994. const vertices = [
  29995. 0, 0, 0, size, 0, 0,
  29996. 0, 0, 0, 0, size, 0,
  29997. 0, 0, 0, 0, 0, size
  29998. ];
  29999. const colors = [
  30000. 1, 0, 0, 1, 0.6, 0,
  30001. 0, 1, 0, 0.6, 1, 0,
  30002. 0, 0, 1, 0, 0.6, 1
  30003. ];
  30004. const geometry = new BufferGeometry();
  30005. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30006. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30007. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30008. super( geometry, material );
  30009. this.type = 'AxesHelper';
  30010. }
  30011. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  30012. const color = new Color();
  30013. const array = this.geometry.attributes.color.array;
  30014. color.set( xAxisColor );
  30015. color.toArray( array, 0 );
  30016. color.toArray( array, 3 );
  30017. color.set( yAxisColor );
  30018. color.toArray( array, 6 );
  30019. color.toArray( array, 9 );
  30020. color.set( zAxisColor );
  30021. color.toArray( array, 12 );
  30022. color.toArray( array, 15 );
  30023. this.geometry.attributes.color.needsUpdate = true;
  30024. return this;
  30025. }
  30026. dispose() {
  30027. this.geometry.dispose();
  30028. this.material.dispose();
  30029. }
  30030. }
  30031. class ShapePath {
  30032. constructor() {
  30033. this.type = 'ShapePath';
  30034. this.color = new Color();
  30035. this.subPaths = [];
  30036. this.currentPath = null;
  30037. }
  30038. moveTo( x, y ) {
  30039. this.currentPath = new Path();
  30040. this.subPaths.push( this.currentPath );
  30041. this.currentPath.moveTo( x, y );
  30042. return this;
  30043. }
  30044. lineTo( x, y ) {
  30045. this.currentPath.lineTo( x, y );
  30046. return this;
  30047. }
  30048. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  30049. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  30050. return this;
  30051. }
  30052. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  30053. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  30054. return this;
  30055. }
  30056. splineThru( pts ) {
  30057. this.currentPath.splineThru( pts );
  30058. return this;
  30059. }
  30060. toShapes( isCCW ) {
  30061. function toShapesNoHoles( inSubpaths ) {
  30062. const shapes = [];
  30063. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  30064. const tmpPath = inSubpaths[ i ];
  30065. const tmpShape = new Shape();
  30066. tmpShape.curves = tmpPath.curves;
  30067. shapes.push( tmpShape );
  30068. }
  30069. return shapes;
  30070. }
  30071. function isPointInsidePolygon( inPt, inPolygon ) {
  30072. const polyLen = inPolygon.length;
  30073. // inPt on polygon contour => immediate success or
  30074. // toggling of inside/outside at every single! intersection point of an edge
  30075. // with the horizontal line through inPt, left of inPt
  30076. // not counting lowerY endpoints of edges and whole edges on that line
  30077. let inside = false;
  30078. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  30079. let edgeLowPt = inPolygon[ p ];
  30080. let edgeHighPt = inPolygon[ q ];
  30081. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  30082. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  30083. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  30084. // not parallel
  30085. if ( edgeDy < 0 ) {
  30086. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  30087. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  30088. }
  30089. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  30090. if ( inPt.y === edgeLowPt.y ) {
  30091. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  30092. // continue; // no intersection or edgeLowPt => doesn't count !!!
  30093. } else {
  30094. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  30095. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  30096. if ( perpEdge < 0 ) continue;
  30097. inside = ! inside; // true intersection left of inPt
  30098. }
  30099. } else {
  30100. // parallel or collinear
  30101. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  30102. // edge lies on the same horizontal line as inPt
  30103. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  30104. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  30105. // continue;
  30106. }
  30107. }
  30108. return inside;
  30109. }
  30110. const isClockWise = ShapeUtils.isClockWise;
  30111. const subPaths = this.subPaths;
  30112. if ( subPaths.length === 0 ) return [];
  30113. let solid, tmpPath, tmpShape;
  30114. const shapes = [];
  30115. if ( subPaths.length === 1 ) {
  30116. tmpPath = subPaths[ 0 ];
  30117. tmpShape = new Shape();
  30118. tmpShape.curves = tmpPath.curves;
  30119. shapes.push( tmpShape );
  30120. return shapes;
  30121. }
  30122. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  30123. holesFirst = isCCW ? ! holesFirst : holesFirst;
  30124. // console.log("Holes first", holesFirst);
  30125. const betterShapeHoles = [];
  30126. const newShapes = [];
  30127. let newShapeHoles = [];
  30128. let mainIdx = 0;
  30129. let tmpPoints;
  30130. newShapes[ mainIdx ] = undefined;
  30131. newShapeHoles[ mainIdx ] = [];
  30132. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  30133. tmpPath = subPaths[ i ];
  30134. tmpPoints = tmpPath.getPoints();
  30135. solid = isClockWise( tmpPoints );
  30136. solid = isCCW ? ! solid : solid;
  30137. if ( solid ) {
  30138. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  30139. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  30140. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  30141. if ( holesFirst ) mainIdx ++;
  30142. newShapeHoles[ mainIdx ] = [];
  30143. //console.log('cw', i);
  30144. } else {
  30145. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  30146. //console.log('ccw', i);
  30147. }
  30148. }
  30149. // only Holes? -> probably all Shapes with wrong orientation
  30150. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  30151. if ( newShapes.length > 1 ) {
  30152. let ambiguous = false;
  30153. let toChange = 0;
  30154. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30155. betterShapeHoles[ sIdx ] = [];
  30156. }
  30157. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30158. const sho = newShapeHoles[ sIdx ];
  30159. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  30160. const ho = sho[ hIdx ];
  30161. let hole_unassigned = true;
  30162. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  30163. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  30164. if ( sIdx !== s2Idx ) toChange ++;
  30165. if ( hole_unassigned ) {
  30166. hole_unassigned = false;
  30167. betterShapeHoles[ s2Idx ].push( ho );
  30168. } else {
  30169. ambiguous = true;
  30170. }
  30171. }
  30172. }
  30173. if ( hole_unassigned ) {
  30174. betterShapeHoles[ sIdx ].push( ho );
  30175. }
  30176. }
  30177. }
  30178. if ( toChange > 0 && ambiguous === false ) {
  30179. newShapeHoles = betterShapeHoles;
  30180. }
  30181. }
  30182. let tmpHoles;
  30183. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  30184. tmpShape = newShapes[ i ].s;
  30185. shapes.push( tmpShape );
  30186. tmpHoles = newShapeHoles[ i ];
  30187. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  30188. tmpShape.holes.push( tmpHoles[ j ].h );
  30189. }
  30190. }
  30191. //console.log("shape", shapes);
  30192. return shapes;
  30193. }
  30194. }
  30195. class BoxBufferGeometry extends BoxGeometry { // @deprecated, r144
  30196. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  30197. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  30198. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  30199. }
  30200. }
  30201. class CapsuleBufferGeometry extends CapsuleGeometry { // @deprecated, r144
  30202. constructor( radius, length, capSegments, radialSegments ) {
  30203. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  30204. super( radius, length, capSegments, radialSegments );
  30205. }
  30206. }
  30207. class CircleBufferGeometry extends CircleGeometry { // @deprecated, r144
  30208. constructor( radius, segments, thetaStart, thetaLength ) {
  30209. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  30210. super( radius, segments, thetaStart, thetaLength );
  30211. }
  30212. }
  30213. class ConeBufferGeometry extends ConeGeometry { // @deprecated, r144
  30214. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  30215. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  30216. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  30217. }
  30218. }
  30219. class CylinderBufferGeometry extends CylinderGeometry { // @deprecated, r144
  30220. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  30221. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  30222. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  30223. }
  30224. }
  30225. class DodecahedronBufferGeometry extends DodecahedronGeometry { // @deprecated, r144
  30226. constructor( radius, detail ) {
  30227. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  30228. super( radius, detail );
  30229. }
  30230. }
  30231. class ExtrudeBufferGeometry extends ExtrudeGeometry { // @deprecated, r144
  30232. constructor( shapes, options ) {
  30233. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  30234. super( shapes, options );
  30235. }
  30236. }
  30237. class IcosahedronBufferGeometry extends IcosahedronGeometry { // @deprecated, r144
  30238. constructor( radius, detail ) {
  30239. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  30240. super( radius, detail );
  30241. }
  30242. }
  30243. class LatheBufferGeometry extends LatheGeometry { // @deprecated, r144
  30244. constructor( points, segments, phiStart, phiLength ) {
  30245. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  30246. super( points, segments, phiStart, phiLength );
  30247. }
  30248. }
  30249. class OctahedronBufferGeometry extends OctahedronGeometry { // @deprecated, r144
  30250. constructor( radius, detail ) {
  30251. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  30252. super( radius, detail );
  30253. }
  30254. }
  30255. class PlaneBufferGeometry extends PlaneGeometry { // @deprecated, r144
  30256. constructor( width, height, widthSegments, heightSegments ) {
  30257. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  30258. super( width, height, widthSegments, heightSegments );
  30259. }
  30260. }
  30261. class PolyhedronBufferGeometry extends PolyhedronGeometry { // @deprecated, r144
  30262. constructor( vertices, indices, radius, detail ) {
  30263. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  30264. super( vertices, indices, radius, detail );
  30265. }
  30266. }
  30267. class RingBufferGeometry extends RingGeometry { // @deprecated, r144
  30268. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  30269. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  30270. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  30271. }
  30272. }
  30273. class ShapeBufferGeometry extends ShapeGeometry { // @deprecated, r144
  30274. constructor( shapes, curveSegments ) {
  30275. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  30276. super( shapes, curveSegments );
  30277. }
  30278. }
  30279. class SphereBufferGeometry extends SphereGeometry { // @deprecated, r144
  30280. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  30281. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  30282. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  30283. }
  30284. }
  30285. class TetrahedronBufferGeometry extends TetrahedronGeometry { // @deprecated, r144
  30286. constructor( radius, detail ) {
  30287. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  30288. super( radius, detail );
  30289. }
  30290. }
  30291. class TorusBufferGeometry extends TorusGeometry { // @deprecated, r144
  30292. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  30293. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  30294. super( radius, tube, radialSegments, tubularSegments, arc );
  30295. }
  30296. }
  30297. class TorusKnotBufferGeometry extends TorusKnotGeometry { // @deprecated, r144
  30298. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  30299. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  30300. super( radius, tube, tubularSegments, radialSegments, p, q );
  30301. }
  30302. }
  30303. class TubeBufferGeometry extends TubeGeometry { // @deprecated, r144
  30304. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  30305. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  30306. super( path, tubularSegments, radius, radialSegments, closed );
  30307. }
  30308. }
  30309. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30310. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30311. revision: REVISION,
  30312. } } ) );
  30313. }
  30314. if ( typeof window !== 'undefined' ) {
  30315. if ( window.__THREE__ ) {
  30316. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30317. } else {
  30318. window.__THREE__ = REVISION;
  30319. }
  30320. }
  30321. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  30322. exports.AddEquation = AddEquation;
  30323. exports.AddOperation = AddOperation;
  30324. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  30325. exports.AdditiveBlending = AdditiveBlending;
  30326. exports.AlphaFormat = AlphaFormat;
  30327. exports.AlwaysCompare = AlwaysCompare;
  30328. exports.AlwaysDepth = AlwaysDepth;
  30329. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  30330. exports.AmbientLight = AmbientLight;
  30331. exports.AmbientLightProbe = AmbientLightProbe;
  30332. exports.AnimationAction = AnimationAction;
  30333. exports.AnimationClip = AnimationClip;
  30334. exports.AnimationLoader = AnimationLoader;
  30335. exports.AnimationMixer = AnimationMixer;
  30336. exports.AnimationObjectGroup = AnimationObjectGroup;
  30337. exports.AnimationUtils = AnimationUtils;
  30338. exports.ArcCurve = ArcCurve;
  30339. exports.ArrayCamera = ArrayCamera;
  30340. exports.ArrowHelper = ArrowHelper;
  30341. exports.Audio = Audio;
  30342. exports.AudioAnalyser = AudioAnalyser;
  30343. exports.AudioContext = AudioContext;
  30344. exports.AudioListener = AudioListener;
  30345. exports.AudioLoader = AudioLoader;
  30346. exports.AxesHelper = AxesHelper;
  30347. exports.BackSide = BackSide;
  30348. exports.BasicDepthPacking = BasicDepthPacking;
  30349. exports.BasicShadowMap = BasicShadowMap;
  30350. exports.Bone = Bone;
  30351. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  30352. exports.Box2 = Box2;
  30353. exports.Box3 = Box3;
  30354. exports.Box3Helper = Box3Helper;
  30355. exports.BoxBufferGeometry = BoxBufferGeometry;
  30356. exports.BoxGeometry = BoxGeometry;
  30357. exports.BoxHelper = BoxHelper;
  30358. exports.BufferAttribute = BufferAttribute;
  30359. exports.BufferGeometry = BufferGeometry;
  30360. exports.BufferGeometryLoader = BufferGeometryLoader;
  30361. exports.ByteType = ByteType;
  30362. exports.Cache = Cache;
  30363. exports.Camera = Camera;
  30364. exports.CameraHelper = CameraHelper;
  30365. exports.CanvasTexture = CanvasTexture;
  30366. exports.CapsuleBufferGeometry = CapsuleBufferGeometry;
  30367. exports.CapsuleGeometry = CapsuleGeometry;
  30368. exports.CatmullRomCurve3 = CatmullRomCurve3;
  30369. exports.CineonToneMapping = CineonToneMapping;
  30370. exports.CircleBufferGeometry = CircleBufferGeometry;
  30371. exports.CircleGeometry = CircleGeometry;
  30372. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  30373. exports.Clock = Clock;
  30374. exports.Color = Color;
  30375. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  30376. exports.ColorManagement = ColorManagement;
  30377. exports.CompressedArrayTexture = CompressedArrayTexture;
  30378. exports.CompressedTexture = CompressedTexture;
  30379. exports.CompressedTextureLoader = CompressedTextureLoader;
  30380. exports.ConeBufferGeometry = ConeBufferGeometry;
  30381. exports.ConeGeometry = ConeGeometry;
  30382. exports.CubeCamera = CubeCamera;
  30383. exports.CubeReflectionMapping = CubeReflectionMapping;
  30384. exports.CubeRefractionMapping = CubeRefractionMapping;
  30385. exports.CubeTexture = CubeTexture;
  30386. exports.CubeTextureLoader = CubeTextureLoader;
  30387. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  30388. exports.CubicBezierCurve = CubicBezierCurve;
  30389. exports.CubicBezierCurve3 = CubicBezierCurve3;
  30390. exports.CubicInterpolant = CubicInterpolant;
  30391. exports.CullFaceBack = CullFaceBack;
  30392. exports.CullFaceFront = CullFaceFront;
  30393. exports.CullFaceFrontBack = CullFaceFrontBack;
  30394. exports.CullFaceNone = CullFaceNone;
  30395. exports.Curve = Curve;
  30396. exports.CurvePath = CurvePath;
  30397. exports.CustomBlending = CustomBlending;
  30398. exports.CustomToneMapping = CustomToneMapping;
  30399. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  30400. exports.CylinderGeometry = CylinderGeometry;
  30401. exports.Cylindrical = Cylindrical;
  30402. exports.Data3DTexture = Data3DTexture;
  30403. exports.DataArrayTexture = DataArrayTexture;
  30404. exports.DataTexture = DataTexture;
  30405. exports.DataTextureLoader = DataTextureLoader;
  30406. exports.DataUtils = DataUtils;
  30407. exports.DecrementStencilOp = DecrementStencilOp;
  30408. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  30409. exports.DefaultLoadingManager = DefaultLoadingManager;
  30410. exports.DepthFormat = DepthFormat;
  30411. exports.DepthStencilFormat = DepthStencilFormat;
  30412. exports.DepthTexture = DepthTexture;
  30413. exports.DirectionalLight = DirectionalLight;
  30414. exports.DirectionalLightHelper = DirectionalLightHelper;
  30415. exports.DiscreteInterpolant = DiscreteInterpolant;
  30416. exports.DisplayP3ColorSpace = DisplayP3ColorSpace;
  30417. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  30418. exports.DodecahedronGeometry = DodecahedronGeometry;
  30419. exports.DoubleSide = DoubleSide;
  30420. exports.DstAlphaFactor = DstAlphaFactor;
  30421. exports.DstColorFactor = DstColorFactor;
  30422. exports.DynamicCopyUsage = DynamicCopyUsage;
  30423. exports.DynamicDrawUsage = DynamicDrawUsage;
  30424. exports.DynamicReadUsage = DynamicReadUsage;
  30425. exports.EdgesGeometry = EdgesGeometry;
  30426. exports.EllipseCurve = EllipseCurve;
  30427. exports.EqualCompare = EqualCompare;
  30428. exports.EqualDepth = EqualDepth;
  30429. exports.EqualStencilFunc = EqualStencilFunc;
  30430. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  30431. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  30432. exports.Euler = Euler;
  30433. exports.EventDispatcher = EventDispatcher;
  30434. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  30435. exports.ExtrudeGeometry = ExtrudeGeometry;
  30436. exports.FileLoader = FileLoader;
  30437. exports.Float16BufferAttribute = Float16BufferAttribute;
  30438. exports.Float32BufferAttribute = Float32BufferAttribute;
  30439. exports.Float64BufferAttribute = Float64BufferAttribute;
  30440. exports.FloatType = FloatType;
  30441. exports.Fog = Fog;
  30442. exports.FogExp2 = FogExp2;
  30443. exports.FramebufferTexture = FramebufferTexture;
  30444. exports.FrontSide = FrontSide;
  30445. exports.Frustum = Frustum;
  30446. exports.GLBufferAttribute = GLBufferAttribute;
  30447. exports.GLSL1 = GLSL1;
  30448. exports.GLSL3 = GLSL3;
  30449. exports.GreaterCompare = GreaterCompare;
  30450. exports.GreaterDepth = GreaterDepth;
  30451. exports.GreaterEqualCompare = GreaterEqualCompare;
  30452. exports.GreaterEqualDepth = GreaterEqualDepth;
  30453. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  30454. exports.GreaterStencilFunc = GreaterStencilFunc;
  30455. exports.GridHelper = GridHelper;
  30456. exports.Group = Group;
  30457. exports.HalfFloatType = HalfFloatType;
  30458. exports.HemisphereLight = HemisphereLight;
  30459. exports.HemisphereLightHelper = HemisphereLightHelper;
  30460. exports.HemisphereLightProbe = HemisphereLightProbe;
  30461. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  30462. exports.IcosahedronGeometry = IcosahedronGeometry;
  30463. exports.ImageBitmapLoader = ImageBitmapLoader;
  30464. exports.ImageLoader = ImageLoader;
  30465. exports.ImageUtils = ImageUtils;
  30466. exports.IncrementStencilOp = IncrementStencilOp;
  30467. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  30468. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  30469. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  30470. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  30471. exports.InstancedMesh = InstancedMesh;
  30472. exports.Int16BufferAttribute = Int16BufferAttribute;
  30473. exports.Int32BufferAttribute = Int32BufferAttribute;
  30474. exports.Int8BufferAttribute = Int8BufferAttribute;
  30475. exports.IntType = IntType;
  30476. exports.InterleavedBuffer = InterleavedBuffer;
  30477. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  30478. exports.Interpolant = Interpolant;
  30479. exports.InterpolateDiscrete = InterpolateDiscrete;
  30480. exports.InterpolateLinear = InterpolateLinear;
  30481. exports.InterpolateSmooth = InterpolateSmooth;
  30482. exports.InvertStencilOp = InvertStencilOp;
  30483. exports.KeepStencilOp = KeepStencilOp;
  30484. exports.KeyframeTrack = KeyframeTrack;
  30485. exports.LOD = LOD;
  30486. exports.LatheBufferGeometry = LatheBufferGeometry;
  30487. exports.LatheGeometry = LatheGeometry;
  30488. exports.Layers = Layers;
  30489. exports.LessCompare = LessCompare;
  30490. exports.LessDepth = LessDepth;
  30491. exports.LessEqualCompare = LessEqualCompare;
  30492. exports.LessEqualDepth = LessEqualDepth;
  30493. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  30494. exports.LessStencilFunc = LessStencilFunc;
  30495. exports.Light = Light;
  30496. exports.LightProbe = LightProbe;
  30497. exports.Line = Line;
  30498. exports.Line3 = Line3;
  30499. exports.LineBasicMaterial = LineBasicMaterial;
  30500. exports.LineCurve = LineCurve;
  30501. exports.LineCurve3 = LineCurve3;
  30502. exports.LineDashedMaterial = LineDashedMaterial;
  30503. exports.LineLoop = LineLoop;
  30504. exports.LineSegments = LineSegments;
  30505. exports.LinearEncoding = LinearEncoding;
  30506. exports.LinearFilter = LinearFilter;
  30507. exports.LinearInterpolant = LinearInterpolant;
  30508. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30509. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30510. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  30511. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  30512. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  30513. exports.LinearToneMapping = LinearToneMapping;
  30514. exports.Loader = Loader;
  30515. exports.LoaderUtils = LoaderUtils;
  30516. exports.LoadingManager = LoadingManager;
  30517. exports.LoopOnce = LoopOnce;
  30518. exports.LoopPingPong = LoopPingPong;
  30519. exports.LoopRepeat = LoopRepeat;
  30520. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30521. exports.LuminanceFormat = LuminanceFormat;
  30522. exports.MOUSE = MOUSE;
  30523. exports.Material = Material;
  30524. exports.MaterialLoader = MaterialLoader;
  30525. exports.MathUtils = MathUtils;
  30526. exports.Matrix3 = Matrix3;
  30527. exports.Matrix4 = Matrix4;
  30528. exports.MaxEquation = MaxEquation;
  30529. exports.Mesh = Mesh;
  30530. exports.MeshBasicMaterial = MeshBasicMaterial;
  30531. exports.MeshDepthMaterial = MeshDepthMaterial;
  30532. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  30533. exports.MeshLambertMaterial = MeshLambertMaterial;
  30534. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  30535. exports.MeshNormalMaterial = MeshNormalMaterial;
  30536. exports.MeshPhongMaterial = MeshPhongMaterial;
  30537. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  30538. exports.MeshStandardMaterial = MeshStandardMaterial;
  30539. exports.MeshToonMaterial = MeshToonMaterial;
  30540. exports.MinEquation = MinEquation;
  30541. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30542. exports.MixOperation = MixOperation;
  30543. exports.MultiplyBlending = MultiplyBlending;
  30544. exports.MultiplyOperation = MultiplyOperation;
  30545. exports.NearestFilter = NearestFilter;
  30546. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30547. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30548. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  30549. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  30550. exports.NeverCompare = NeverCompare;
  30551. exports.NeverDepth = NeverDepth;
  30552. exports.NeverStencilFunc = NeverStencilFunc;
  30553. exports.NoBlending = NoBlending;
  30554. exports.NoColorSpace = NoColorSpace;
  30555. exports.NoToneMapping = NoToneMapping;
  30556. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  30557. exports.NormalBlending = NormalBlending;
  30558. exports.NotEqualCompare = NotEqualCompare;
  30559. exports.NotEqualDepth = NotEqualDepth;
  30560. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  30561. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  30562. exports.Object3D = Object3D;
  30563. exports.ObjectLoader = ObjectLoader;
  30564. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  30565. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  30566. exports.OctahedronGeometry = OctahedronGeometry;
  30567. exports.OneFactor = OneFactor;
  30568. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30569. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30570. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30571. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30572. exports.OrthographicCamera = OrthographicCamera;
  30573. exports.PCFShadowMap = PCFShadowMap;
  30574. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30575. exports.PMREMGenerator = PMREMGenerator;
  30576. exports.Path = Path;
  30577. exports.PerspectiveCamera = PerspectiveCamera;
  30578. exports.Plane = Plane;
  30579. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  30580. exports.PlaneGeometry = PlaneGeometry;
  30581. exports.PlaneHelper = PlaneHelper;
  30582. exports.PointLight = PointLight;
  30583. exports.PointLightHelper = PointLightHelper;
  30584. exports.Points = Points;
  30585. exports.PointsMaterial = PointsMaterial;
  30586. exports.PolarGridHelper = PolarGridHelper;
  30587. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  30588. exports.PolyhedronGeometry = PolyhedronGeometry;
  30589. exports.PositionalAudio = PositionalAudio;
  30590. exports.PropertyBinding = PropertyBinding;
  30591. exports.PropertyMixer = PropertyMixer;
  30592. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  30593. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  30594. exports.Quaternion = Quaternion;
  30595. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  30596. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  30597. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  30598. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  30599. exports.REVISION = REVISION;
  30600. exports.RGBADepthPacking = RGBADepthPacking;
  30601. exports.RGBAFormat = RGBAFormat;
  30602. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  30603. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  30604. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  30605. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  30606. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  30607. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  30608. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  30609. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  30610. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  30611. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  30612. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  30613. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  30614. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  30615. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  30616. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  30617. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  30618. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  30619. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  30620. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  30621. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  30622. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  30623. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  30624. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  30625. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  30626. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  30627. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  30628. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  30629. exports.RGFormat = RGFormat;
  30630. exports.RGIntegerFormat = RGIntegerFormat;
  30631. exports.RawShaderMaterial = RawShaderMaterial;
  30632. exports.Ray = Ray;
  30633. exports.Raycaster = Raycaster;
  30634. exports.RectAreaLight = RectAreaLight;
  30635. exports.RedFormat = RedFormat;
  30636. exports.RedIntegerFormat = RedIntegerFormat;
  30637. exports.ReinhardToneMapping = ReinhardToneMapping;
  30638. exports.RepeatWrapping = RepeatWrapping;
  30639. exports.ReplaceStencilOp = ReplaceStencilOp;
  30640. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30641. exports.RingBufferGeometry = RingBufferGeometry;
  30642. exports.RingGeometry = RingGeometry;
  30643. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  30644. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  30645. exports.SRGBColorSpace = SRGBColorSpace;
  30646. exports.Scene = Scene;
  30647. exports.ShaderChunk = ShaderChunk;
  30648. exports.ShaderLib = ShaderLib;
  30649. exports.ShaderMaterial = ShaderMaterial;
  30650. exports.ShadowMaterial = ShadowMaterial;
  30651. exports.Shape = Shape;
  30652. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  30653. exports.ShapeGeometry = ShapeGeometry;
  30654. exports.ShapePath = ShapePath;
  30655. exports.ShapeUtils = ShapeUtils;
  30656. exports.ShortType = ShortType;
  30657. exports.Skeleton = Skeleton;
  30658. exports.SkeletonHelper = SkeletonHelper;
  30659. exports.SkinnedMesh = SkinnedMesh;
  30660. exports.Source = Source;
  30661. exports.Sphere = Sphere;
  30662. exports.SphereBufferGeometry = SphereBufferGeometry;
  30663. exports.SphereGeometry = SphereGeometry;
  30664. exports.Spherical = Spherical;
  30665. exports.SphericalHarmonics3 = SphericalHarmonics3;
  30666. exports.SplineCurve = SplineCurve;
  30667. exports.SpotLight = SpotLight;
  30668. exports.SpotLightHelper = SpotLightHelper;
  30669. exports.Sprite = Sprite;
  30670. exports.SpriteMaterial = SpriteMaterial;
  30671. exports.SrcAlphaFactor = SrcAlphaFactor;
  30672. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30673. exports.SrcColorFactor = SrcColorFactor;
  30674. exports.StaticCopyUsage = StaticCopyUsage;
  30675. exports.StaticDrawUsage = StaticDrawUsage;
  30676. exports.StaticReadUsage = StaticReadUsage;
  30677. exports.StereoCamera = StereoCamera;
  30678. exports.StreamCopyUsage = StreamCopyUsage;
  30679. exports.StreamDrawUsage = StreamDrawUsage;
  30680. exports.StreamReadUsage = StreamReadUsage;
  30681. exports.StringKeyframeTrack = StringKeyframeTrack;
  30682. exports.SubtractEquation = SubtractEquation;
  30683. exports.SubtractiveBlending = SubtractiveBlending;
  30684. exports.TOUCH = TOUCH;
  30685. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  30686. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  30687. exports.TetrahedronGeometry = TetrahedronGeometry;
  30688. exports.Texture = Texture;
  30689. exports.TextureLoader = TextureLoader;
  30690. exports.TorusBufferGeometry = TorusBufferGeometry;
  30691. exports.TorusGeometry = TorusGeometry;
  30692. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  30693. exports.TorusKnotGeometry = TorusKnotGeometry;
  30694. exports.Triangle = Triangle;
  30695. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  30696. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  30697. exports.TrianglesDrawMode = TrianglesDrawMode;
  30698. exports.TubeBufferGeometry = TubeBufferGeometry;
  30699. exports.TubeGeometry = TubeGeometry;
  30700. exports.TwoPassDoubleSide = TwoPassDoubleSide;
  30701. exports.UVMapping = UVMapping;
  30702. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  30703. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  30704. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  30705. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  30706. exports.Uniform = Uniform;
  30707. exports.UniformsGroup = UniformsGroup;
  30708. exports.UniformsLib = UniformsLib;
  30709. exports.UniformsUtils = UniformsUtils;
  30710. exports.UnsignedByteType = UnsignedByteType;
  30711. exports.UnsignedInt248Type = UnsignedInt248Type;
  30712. exports.UnsignedIntType = UnsignedIntType;
  30713. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30714. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30715. exports.UnsignedShortType = UnsignedShortType;
  30716. exports.VSMShadowMap = VSMShadowMap;
  30717. exports.Vector2 = Vector2;
  30718. exports.Vector3 = Vector3;
  30719. exports.Vector4 = Vector4;
  30720. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  30721. exports.VideoTexture = VideoTexture;
  30722. exports.WebGL1Renderer = WebGL1Renderer;
  30723. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  30724. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  30725. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  30726. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  30727. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  30728. exports.WebGLRenderTarget = WebGLRenderTarget;
  30729. exports.WebGLRenderer = WebGLRenderer;
  30730. exports.WebGLUtils = WebGLUtils;
  30731. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  30732. exports.WireframeGeometry = WireframeGeometry;
  30733. exports.WrapAroundEnding = WrapAroundEnding;
  30734. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  30735. exports.ZeroFactor = ZeroFactor;
  30736. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  30737. exports.ZeroStencilOp = ZeroStencilOp;
  30738. exports._SRGBAFormat = _SRGBAFormat;
  30739. exports.sRGBEncoding = sRGBEncoding;